(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 z of M.addedNodes)z.tagName==="LINK"&&z.rel==="modulepreload"&&S(z)}).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(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Fi={exports:{}},Bo={},bi={exports:{}},ge={};var Xc;function Cf(){if(Xc)return ge;Xc=1;var a=Symbol.for("react.element"),m=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),S=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),M=Symbol.for("react.provider"),z=Symbol.for("react.context"),ae=Symbol.for("react.forward_ref"),ne=Symbol.for("react.suspense"),F=Symbol.for("react.memo"),X=Symbol.for("react.lazy"),Z=Symbol.iterator;function te(y){return y===null||typeof y!="object"?null:(y=Z&&y[Z]||y["@@iterator"],typeof y=="function"?y:null)}var Me={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},pe=Object.assign,me={};function ye(y,k,se){this.props=y,this.context=k,this.refs=me,this.updater=se||Me}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 Qe(){}Qe.prototype=ye.prototype;function Xe(y,k,se){this.props=y,this.context=k,this.refs=me,this.updater=se||Me}var He=Xe.prototype=new Qe;He.constructor=Xe,pe(He,ye.prototype),He.isPureReactComponent=!0;var Ae=Array.isArray,b=Object.prototype.hasOwnProperty,le={current:null},Ee={key:!0,ref:!0,__self:!0,__source:!0};function be(y,k,se){var ue,de={},xe=null,we=null;if(k!=null)for(ue in k.ref!==void 0&&(we=k.ref),k.key!==void 0&&(xe=""+k.key),k)b.call(k,ue)&&!Ee.hasOwnProperty(ue)&&(de[ue]=k[ue]);var je=arguments.length-2;if(je===1)de.children=se;else if(1>>1,k=I[y];if(0>>1;yC(de,L))xeC(we,de)?(I[y]=we,I[xe]=L,y=xe):(I[y]=de,I[ue]=L,y=ue);else if(xeC(we,L))I[y]=we,I[xe]=L,y=xe;else break e}}return O}function C(I,O){var L=I.sortIndex-O.sortIndex;return L!==0?L:I.id-O.id}if(typeof performance=="object"&&typeof performance.now=="function"){var M=performance;a.unstable_now=function(){return M.now()}}else{var z=Date,ae=z.now();a.unstable_now=function(){return z.now()-ae}}var ne=[],F=[],X=1,Z=null,te=3,Me=!1,pe=!1,me=!1,ye=typeof setTimeout=="function"?setTimeout:null,Qe=typeof clearTimeout=="function"?clearTimeout:null,Xe=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function He(I){for(var O=p(F);O!==null;){if(O.callback===null)S(F);else if(O.startTime<=I)S(F),O.sortIndex=O.expirationTime,m(ne,O);else break;O=p(F)}}function Ae(I){if(me=!1,He(I),!pe)if(p(ne)!==null)pe=!0,re(b);else{var O=p(F);O!==null&&ee(Ae,O.startTime-I)}}function b(I,O){pe=!1,me&&(me=!1,Qe(be),be=-1),Me=!0;var L=te;try{for(He(O),Z=p(ne);Z!==null&&(!(Z.expirationTime>O)||I&&!Kt());){var y=Z.callback;if(typeof y=="function"){Z.callback=null,te=Z.priorityLevel;var k=y(Z.expirationTime<=O);O=a.unstable_now(),typeof k=="function"?Z.callback=k:Z===p(ne)&&S(ne),He(O)}else S(ne);Z=p(ne)}if(Z!==null)var se=!0;else{var ue=p(F);ue!==null&&ee(Ae,ue.startTime-O),se=!1}return se}finally{Z=null,te=L,Me=!1}}var le=!1,Ee=null,be=-1,St=5,mt=-1;function Kt(){return!(a.unstable_now()-mtI||125y?(I.sortIndex=L,m(F,I),p(ne)===null&&I===p(F)&&(me?(Qe(be),be=-1):me=!0,ee(Ae,L-y))):(I.sortIndex=k,m(ne,I),pe||Me||(pe=!0,re(b))),I},a.unstable_shouldYield=Kt,a.unstable_wrapCallback=function(I){var O=te;return function(){var L=te;te=O;try{return I.apply(this,arguments)}finally{te=L}}}})(Qi)),Qi}var rd;function Rf(){return rd||(rd=1,Bi.exports=Tf()),Bi.exports}var sd;function Mf(){if(sd)return qt;sd=1;var a=Zi(),m=Rf();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"),ne=Object.prototype.hasOwnProperty,F=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,X={},Z={};function te(e){return ne.call(Z,e)?!0:ne.call(X,e)?!1:F.test(e)?Z[e]=!0:(X[e]=!0,!1)}function Me(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 pe(e,t,n,r){if(t===null||typeof t>"u"||Me(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 me(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 me(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 me(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){ye[e]=new me(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ye[e]=new me(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 me(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){ye[e]=new me(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){ye[e]=new me(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){ye[e]=new me(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){ye[e]=new me(e,5,!1,e.toLowerCase(),null,!1,!1)});var Qe=/[\-:]([a-z])/g;function Xe(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(Qe,Xe);ye[t]=new me(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(Qe,Xe);ye[t]=new me(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(Qe,Xe);ye[t]=new me(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){ye[e]=new me(e,1,!1,e.toLowerCase(),null,!1,!1)}),ye.xlinkHref=new me("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){ye[e]=new me(e,1,!1,e.toLowerCase(),null,!0,!0)});function He(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{se=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?k(e):""}function de(e){switch(e.tag){case 5:return k(e.type);case 16:return k("Lazy");case 13:return k("Suspense");case 19:return k("SuspenseList");case 0:case 2:case 15:return e=ue(e.type,!1),e;case 11:return e=ue(e.type.render,!1),e;case 1:return e=ue(e.type,!0),e;default:return""}}function 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 le:return"Portal";case St:return"Profiler";case be:return"StrictMode";case B:return"Suspense";case Ie:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Kt:return(e.displayName||"Context")+".Consumer";case mt:return(e._context.displayName||"Context")+".Provider";case ht: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 re: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===be?"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 gt(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 sn(e){e._valueTracker||(e._valueTracker=gt(e))}function yr(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 Rn(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 vn(e,t){var n=t.checked;return L({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Se(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 Jt(e,t){t=t.checked,t!=null&&He(e,"checked",t,!1)}function Ve(e,t){Jt(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")?Tt(e,t.type,n):t.hasOwnProperty("defaultValue")&&Tt(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 Tt(e,t,n){(t!=="number"||Rn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yn=Array.isArray;function W(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=An.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Mt(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ze={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},ys=["Webkit","ms","Moz","O"];Object.keys(Ze).forEach(function(e){ys.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ze[t]=Ze[e]})});function st(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ze.hasOwnProperty(e)&&Ze[e]?(""+t).trim():t+"px"}function er(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=st(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var _r=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 on(e,t){if(t){if(_r[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 Ft=null;function xn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Yt=null,q=null,At=null;function tr(e){if(e=Eo(e)){if(typeof Yt!="function")throw Error(p(280));var t=e.stateNode;t&&(t=pl(t),Yt(e.stateNode,e.type,t))}}function Kr(e){q?At?At.push(e):At=[e]:q=e}function Jr(){if(q){var e=q,t=At;if(At=q=null,tr(e),t)for(e=0;e>>=0,e===0?32:31-(Ko(e)/Jo|0)|0}var Un=64,_s=4194304;function Zt(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 Ss(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=Zt(d):(l&=u,l!==0&&(r=Zt(l)))}else u=n&~s,u!==0?r=Zt(u):l!==0&&(r=Zt(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 Cr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Xt(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=Mr),po=" ",mo=!1;function ho(e,t){switch(e){case"keyup":return Kn.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function go(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ir=!1;function ya(e,t){switch(e){case"compositionend":return go(t);case"keypress":return t.which!==32?null:(mo=!0,po);case"textInput":return e=t.data,e===po&&mo?null:e;default:return null}}function ll(e,t){if(ir)return e==="compositionend"||!Rr&&ho(e,t)?(e=V(),Er=Es=ut=null,ir=!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=Rn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Rn(e.document)}return t}function wa(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 Md(e){var t=su(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ru(n.ownerDocument.documentElement,n)){if(r!==null&&wa(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,Ms=null,ja=null,wo=null,ka=!1;function ou(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ka||Ms==null||Ms!==Rn(r)||(r=Ms,"selectionStart"in r&&wa(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}),wo&&So(wo,r)||(wo=r,r=cl(ja,"onSelect"),0Os||(e.current=Oa[Os],Oa[Os]=null,Os--)}function De(e,t){Os++,Oa[Os]=e.current,e.current=t}var zr={},kt=$r(zr),Qt=$r(!1),as=zr;function $s(e,t){var n=e.type.contextTypes;if(!n)return zr;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 Ht(e){return e=e.childContextTypes,e!=null}function ml(){ze(Qt),ze(kt)}function _u(e,t,n){if(kt.current!==zr)throw Error(p(168));De(kt,t),De(Qt,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 hl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||zr,as=kt.current,De(kt,e),De(Qt,Qt.current),!0}function wu(e,t,n){var r=e.stateNode;if(!r)throw Error(p(169));n?(e=Su(e,t,as),r.__reactInternalMemoizedMergedChildContext=e,ze(Qt),ze(kt),De(kt,e)):ze(Qt),De(Qt,n)}var cr=null,gl=!1,$a=!1;function ju(e){cr===null?cr=[e]:cr.push(e)}function Qd(e){gl=!0,ju(e)}function Fr(){if(!$a&&cr!==null){$a=!0;var e=0,t=fe;try{var n=cr;for(fe=1;e>=u,s-=u,dr=1<<32-Xt(t)+s|n<oe?(pt=J,J=null):pt=J.sibling;var Ne=N(x,J,_[oe],R);if(Ne===null){J===null&&(J=pt);break}e&&J&&Ne.alternate===null&&t(x,J),v=l(Ne,v,oe),K===null?G=Ne:K.sibling=Ne,K=Ne,J=pt}if(oe===_.length)return n(x,J),Fe&&us(x,oe),G;if(J===null){for(;oe<_.length;oe++)J=T(x,_[oe],R),J!==null&&(v=l(J,v,oe),K===null?G=J:K.sibling=J,K=J);return Fe&&us(x,oe),G}for(J=r(x,J);oe<_.length;oe++)pt=D(J,x,oe,_[oe],R),pt!==null&&(e&&pt.alternate!==null&&J.delete(pt.key===null?oe:pt.key),v=l(pt,v,oe),K===null?G=pt:K.sibling=pt,K=pt);return e&&J.forEach(function(qr){return t(x,qr)}),Fe&&us(x,oe),G}function H(x,v,_,R){var G=O(_);if(typeof G!="function")throw Error(p(150));if(_=G.call(_),_==null)throw Error(p(151));for(var K=G=null,J=v,oe=v=0,pt=null,Ne=_.next();J!==null&&!Ne.done;oe++,Ne=_.next()){J.index>oe?(pt=J,J=null):pt=J.sibling;var qr=N(x,J,Ne.value,R);if(qr===null){J===null&&(J=pt);break}e&&J&&qr.alternate===null&&t(x,J),v=l(qr,v,oe),K===null?G=qr:K.sibling=qr,K=qr,J=pt}if(Ne.done)return n(x,J),Fe&&us(x,oe),G;if(J===null){for(;!Ne.done;oe++,Ne=_.next())Ne=T(x,Ne.value,R),Ne!==null&&(v=l(Ne,v,oe),K===null?G=Ne:K.sibling=Ne,K=Ne);return Fe&&us(x,oe),G}for(J=r(x,J);!Ne.done;oe++,Ne=_.next())Ne=D(J,x,oe,Ne.value,R),Ne!==null&&(e&&Ne.alternate!==null&&J.delete(Ne.key===null?oe:Ne.key),v=l(Ne,v,oe),K===null?G=Ne:K.sibling=Ne,K=Ne);return e&&J.forEach(function(kf){return t(x,kf)}),Fe&&us(x,oe),G}function Ye(x,v,_,R){if(typeof _=="object"&&_!==null&&_.type===Ee&&_.key===null&&(_=_.props.children),typeof _=="object"&&_!==null){switch(_.$$typeof){case b:e:{for(var G=_.key,K=v;K!==null;){if(K.key===G){if(G=_.type,G===Ee){if(K.tag===7){n(x,K.sibling),v=s(K,_.props.children),v.return=x,x=v;break e}}else if(K.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===re&&Tu(G)===K.type){n(x,K.sibling),v=s(K,_.props),v.ref=Po(x,K,_),v.return=x,x=v;break e}n(x,K);break}else t(x,K);K=K.sibling}_.type===Ee?(v=vs(_.props.children,x.mode,R,_.key),v.return=x,x=v):(R=Hl(_.type,_.key,_.props,null,x.mode,R),R.ref=Po(x,v,_),R.return=x,x=R)}return u(x);case le:e:{for(K=_.key;v!==null;){if(v.key===K)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=Li(_,x.mode,R),v.return=x,x=v}return u(x);case re:return K=_._init,Ye(x,v,K(_._payload),R)}if(yn(_))return U(x,v,_,R);if(O(_))return H(x,v,_,R);_l(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=Ii(_,x.mode,R),v.return=x,x=v),u(x)):n(x,v)}return Ye}var Us=Ru(!0),Mu=Ru(!1),Sl=$r(null),wl=null,Bs=null,Qa=null;function Ha(){Qa=Bs=wl=null}function Va(e){var t=Sl.current;ze(Sl),e._currentValue=t}function Ga(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 Qs(e,t){wl=e,Qa=Bs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Vt=!0),e.firstContext=null)}function fn(e){var t=e._currentValue;if(Qa!==e)if(e={context:e,memoizedValue:t,next:null},Bs===null){if(wl===null)throw Error(p(308));Bs=e,wl.dependencies={lanes:0,firstContext:e}}else Bs=Bs.next=e;return t}var cs=null;function Wa(e){cs===null?cs=[e]:cs.push(e)}function Au(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Wa(t)):(n.next=s.next,s.next=n),t.interleaved=n,pr(e,r)}function pr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var br=!1;function qa(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 mr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ur(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,pr(e,n)}return s=r.interleaved,s===null?(t.next=t,Wa(r)):(t.next=s.next,s.next=t),r.interleaved=t,pr(e,n)}function jl(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,es(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 kl(e,t,n,r){var s=e.updateQueue;br=!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 U=e,H=d;switch(N=t,D=n,H.tag){case 1:if(U=H.payload,typeof U=="function"){T=U.call(D,T,N);break e}T=U;break e;case 3:U.flags=U.flags&-65537|128;case 0:if(U=H.payload,N=typeof U=="function"?U.call(D,T,N):U,N==null)break e;T=L({},T,N);break e;case 2:br=!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);ps|=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=Za.transition;Za.transition={};try{e(!1),t()}finally{fe=n,Za.transition=r}}function ec(){return pn().memoizedState}function Wd(e,t,n){var r=Vr(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=$t();Tn(n,e,r,s),rc(n,t,r)}}function qd(e,t,n){var r=Vr(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,kn(d,u)){var h=t.interleaved;h===null?(s.next=s,Wa(t)):(s.next=h.next,h.next=s),t.interleaved=s;return}}catch{}n=Au(e,t,s,r),n!==null&&(s=$t(),Tn(n,e,r,s),rc(n,t,r))}}function tc(e){var t=e.alternate;return e===Be||t!==null&&t===Be}function nc(e,t){Ao=El=!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,es(e,n)}}var Rl={readContext:fn,useCallback:Ct,useContext:Ct,useEffect:Ct,useImperativeHandle:Ct,useInsertionEffect:Ct,useLayoutEffect:Ct,useMemo:Ct,useReducer:Ct,useRef:Ct,useState:Ct,useDebugValue:Ct,useDeferredValue:Ct,useTransition:Ct,useMutableSource:Ct,useSyncExternalStore:Ct,useId:Ct,unstable_isNewReconciler:!1},Kd={readContext:fn,useCallback:function(e,t){return Xn().memoizedState=[e,t===void 0?null:t],e},useContext:fn,useEffect:Gu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pl(4194308,4,Ku.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pl(4,2,e,t)},useMemo:function(e,t){var n=Xn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Xn();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=Wd.bind(null,Be,e),[r.memoizedState,e]},useRef:function(e){var t=Xn();return e={current:e},t.memoizedState=e},useState:Hu,useDebugValue:li,useDeferredValue:function(e){return Xn().memoizedState=e},useTransition:function(){var e=Hu(!1),t=e[0];return e=Gd.bind(null,e[1]),Xn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Be,s=Xn();if(Fe){if(n===void 0)throw Error(p(407));n=n()}else{if(n=t(),ft===null)throw Error(p(349));(fs&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,Do(9,bu.bind(null,r,l,n,t),void 0,null),n},useId:function(){var e=Xn(),t=ft.identifierPrefix;if(Fe){var n=fr,r=dr;n=(r&~(1<<32-Xt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Io++,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[Jn]=t,e[No]=r,jc(e,t,!1,!1),t.stateNode=e;e:{switch(u=In(n,r),n){case"dialog":$e("cancel",e),$e("close",e),s=r;break;case"iframe":case"object":case"embed":$e("load",e),s=r;break;case"video":case"audio":for(s=0;sqs&&(t.flags|=128,r=!0,Oo(l,!1),t.lanes=4194304)}else{if(!r)if(e=Cl(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Oo(l,!0),l.tail===null&&l.tailMode==="hidden"&&!u.alternate&&!Fe)return Nt(t),null}else 2*Oe()-l.renderingStartTime>qs&&n!==1073741824&&(t.flags|=128,r=!0,Oo(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=Oe(),t.sibling=null,n=Ue.current,De(Ue,r?n&1|2:n&1),t):(Nt(t),null);case 22:case 23:return Ri(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(rn&1073741824)!==0&&(Nt(t),t.subtreeFlags&6&&(t.flags|=8192)):Nt(t),null;case 24:return null;case 25:return null}throw Error(p(156,t.tag))}function rf(e,t){switch(Fa(t),t.tag){case 1:return Ht(t.type)&&ml(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Hs(),ze(Qt),ze(kt),Xa(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return Ja(t),null;case 13:if(ze(Ue),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(p(340));bs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ze(Ue),null;case 4:return Hs(),null;case 10:return Va(t.type._context),null;case 22:case 23:return Ri(),null;case 24:return null;default:return null}}var Ll=!1,Et=!1,sf=typeof WeakSet=="function"?WeakSet:Set,$=null;function Gs(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 yi(e,t,n){try{n()}catch(r){Ke(e,t,r)}}var Nc=!1;function of(e,t){if(Ra=an,e=su(),wa(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(Ma={focusedElem:e,selectionRange:n},an=!1,$=t;$!==null;)if(t=$,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,$=e;else for(;$!==null;){t=$;try{var U=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(U!==null){var H=U.memoizedProps,Ye=U.memoizedState,x=t.stateNode,v=x.getSnapshotBeforeUpdate(t.elementType===t.type?H:Nn(t.type,H),Ye);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,$=e;break}$=t.return}return U=Nc,Nc=!1,U}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&&yi(t,n,l)}s=s.next}while(s!==r)}}function Dl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function xi(e){var t=e.ref;if(t!==null){var n=e.stateNode;e.tag,e=n,typeof t=="function"?t(e):t.current=e}}function 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[Jn],delete t[No],delete t[Da],delete t[Ud],delete t[Bd])),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 _i(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fl));else if(r!==4&&(e=e.child,e!==null))for(_i(e,t,n),e=e.sibling;e!==null;)_i(e,t,n),e=e.sibling}function Si(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Si(e,t,n),e=e.sibling;e!==null;)Si(e,t,n),e=e.sibling}var xt=null,En=!1;function Br(e,t,n){for(n=n.child;n!==null;)Rc(e,t,n),n=n.sibling}function Rc(e,t,n){if(Ut&&typeof Ut.onCommitFiberUnmount=="function")try{Ut.onCommitFiberUnmount(jr,n)}catch{}switch(n.tag){case 5:Et||Gs(n,t);case 6:var r=xt,s=En;xt=null,Br(e,t,n),xt=r,En=s,xt!==null&&(En?(e=xt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):xt.removeChild(n.stateNode));break;case 18:xt!==null&&(En?(e=xt,n=n.stateNode,e.nodeType===8?La(e.parentNode,n):e.nodeType===1&&La(e,n),tt(e)):La(xt,n.stateNode));break;case 4:r=xt,s=En,xt=n.stateNode.containerInfo,En=!0,Br(e,t,n),xt=r,En=s;break;case 0:case 11:case 14:case 15:if(!Et&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var l=s,u=l.destroy;l=l.tag,u!==void 0&&((l&2)!==0||(l&4)!==0)&&yi(n,t,u),s=s.next}while(s!==r)}Br(e,t,n);break;case 1:if(!Et&&(Gs(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)}Br(e,t,n);break;case 21:Br(e,t,n);break;case 22:n.mode&1?(Et=(r=Et)||n.memoizedState!==null,Br(e,t,n),Et=r):Br(e,t,n);break;default:Br(e,t,n)}}function Mc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new sf),t.forEach(function(r){var s=hf.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Pn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~l}if(r=s,r=Oe()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*af(r/1960))-r,10e?16:e,Hr===null)var r=!1;else{if(e=Hr,Hr=null,bl=0,(ke&6)!==0)throw Error(p(331));var s=ke;for(ke|=4,$=e.current;$!==null;){var l=$,u=l.child;if(($.flags&16)!==0){var d=l.deletions;if(d!==null){for(var h=0;hOe()-ki?hs(e,0):ji|=n),Wt(e,t)}function Hc(e,t){t===0&&((e.mode&1)===0?t=1:(t=_s,_s<<=1,(_s&130023424)===0&&(_s=4194304)));var n=$t();e=pr(e,t),e!==null&&(Cr(e,t,n),Wt(e,n))}function mf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Hc(e,n)}function hf(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||Qt.current)Vt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Vt=!1,tf(e,t,n);Vt=(e.flags&131072)!==0}else Vt=!1,Fe&&(t.flags&1048576)!==0&&ku(t,yl,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Il(e,t),e=t.pendingProps;var s=$s(t,kt.current);Qs(t,n),s=ti(null,t,r,e,s,n);var l=ni();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ht(r)?(l=!0,hl(t)):l=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,qa(t),s.updater=Ml,t.stateNode=s,s._reactInternals=t,ii(t,r,e,n),t=fi(null,t,r,!0,l,n)):(t.tag=0,Fe&&l&&za(t),Ot(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Il(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=vf(r),e=Nn(r,e),s){case 0:t=di(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,Nn(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:Nn(r,s),di(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(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),kl(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=Vs(Error(p(423)),t),t=xc(e,t,r,n,s);break e}else if(r!==s){s=Vs(Error(p(424)),t),t=xc(e,t,r,n,s);break e}else for(nn=Or(t.stateNode.containerInfo.firstChild),tn=t,Fe=!0,Cn=null,n=Mu(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(bs(),r===s){t=hr(e,t,n);break e}Ot(e,t,r,n)}t=t.child}return t;case 5:return Ou(t),e===null&&Ua(t),r=t.type,s=t.pendingProps,l=e!==null?e.memoizedProps:null,u=s.children,Aa(r,s)?u=null:l!==null&&Aa(r,l)&&(t.flags|=32),gc(e,t),Ot(e,t,u,n),t.child;case 6:return e===null&&Ua(t),null;case 13:return _c(e,t,n);case 4:return Ka(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Us(t,null,r,n):Ot(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),fc(e,t,r,s,n);case 7:return Ot(e,t,t.pendingProps,n),t.child;case 8:return Ot(e,t,t.pendingProps.children,n),t.child;case 12:return Ot(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,De(Sl,r._currentValue),r._currentValue=u,l!==null)if(kn(l.value,u)){if(l.children===s.children&&!Qt.current){t=hr(e,t,n);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var d=l.dependencies;if(d!==null){u=l.child;for(var h=d.firstContext;h!==null;){if(h.context===r){if(l.tag===1){h=mr(-1,n&-n),h.tag=2;var j=l.updateQueue;if(j!==null){j=j.shared;var P=j.pending;P===null?h.next=h:(h.next=P.next,P.next=h),j.pending=h}}l.lanes|=n,h=l.alternate,h!==null&&(h.lanes|=n),Ga(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),Ga(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}Ot(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Qs(t,n),s=fn(s),r=r(s),t.flags|=1,Ot(e,t,r,n),t.child;case 14:return r=t.type,s=Nn(r,t.pendingProps),s=Nn(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:Nn(r,s),Il(e,t),t.tag=1,Ht(r)?(e=!0,hl(t)):e=!1,Qs(t,n),oc(t,r,s),ii(t,r,s,n),fi(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 qo(e,t)}function gf(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 hn(e,t,n,r){return new gf(e,t,n,r)}function Ai(e){return e=e.prototype,!(!e||!e.isReactComponent)}function vf(e){if(typeof e=="function")return Ai(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ht)return 11;if(e===Je)return 14}return 2}function Wr(e,t){var n=e.alternate;return n===null?(n=hn(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 Hl(e,t,n,r,s,l){var u=2;if(r=e,typeof e=="function")Ai(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Ee:return vs(n.children,s,l,t);case be:u=8,s|=8;break;case St:return e=hn(12,n,t,s|2),e.elementType=St,e.lanes=l,e;case B:return e=hn(13,n,t,s),e.elementType=B,e.lanes=l,e;case Ie:return e=hn(19,n,t,s),e.elementType=Ie,e.lanes=l,e;case ee:return Vl(n,s,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case mt:u=10;break e;case Kt:u=9;break e;case ht:u=11;break e;case Je:u=14;break e;case re:u=16,r=null;break e}throw Error(p(130,e==null?e:typeof e,""))}return t=hn(u,n,t,s),t.elementType=e,t.type=r,t.lanes=l,t}function vs(e,t,n,r){return e=hn(7,e,r,t),e.lanes=n,e}function Vl(e,t,n,r){return e=hn(22,e,r,t),e.elementType=ee,e.lanes=n,e.stateNode={isHidden:!1},e}function Ii(e,t,n){return e=hn(6,e,null,t),e.lanes=n,e}function Li(e,t,n){return t=hn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function yf(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=js(0),this.expirationTimes=js(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=js(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Di(e,t,n,r,s,l,u,d,h){return e=new yf(e,t,n,d,h),t===1?(t=1,l===!0&&(t|=8)):t=0,l=hn(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},qa(l),e}function xf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(m){console.error(m)}}return a(),Ui.exports=Mf(),Ui.exports}var ld;function If(){if(ld)return Xl;ld=1;var a=Af();return Xl.createRoot=a.createRoot,Xl.hydrateRoot=a.hydrateRoot,Xl}var Lf=If();const Df=kd(Lf),Of="/api";async function _e(a,m){const p=await fetch(`${Of}${a}`,{...m,headers:{"Content-Type":"application/json",...m?.headers??{}}}),S=await p.json();if(!p.ok){const C=S.error?.message??"Ошибка запроса";throw new Error(C)}return S}const Te={async loadSharedConnectionConfig(){return _e("/llm/shared-connection")},async saveSharedConnectionConfig(a){return _e("/llm/shared-connection",{method:"POST",body:JSON.stringify({llmProvider:a.llmProvider,model:a.model,baseUrl:a.baseUrl,temperature:a.temperature,maxOutputTokens:a.maxOutputTokens})})},async listModels(a){return _e("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:a.llmProvider,apiKey:a.apiKey,model:a.model,baseUrl:a.baseUrl})})},async testConnection(a){return _e("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:a.llmProvider,apiKey:a.apiKey,model:a.model,baseUrl:a.baseUrl})})},async normalize(a){return _e("/normalize",{method:"POST",body:JSON.stringify({llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion,systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples,userQuestion:a.query.userQuestion,context:{period_hint:a.query.periodHint??"",business_context:a.query.businessContext??"",expected_route:a.query.expectedRoute??""},saveAsTestCase:!!a.saveAsTestCase,useMock:!!a.useMock})})},async loadHistory(){return _e("/history")},async loadTrace(a){return _e(`/history/${a}`)},async loadPresets(){return _e("/presets")},async savePreset(a){return _e("/presets/save",{method:"POST",body:JSON.stringify(a)})},async runEval(a){return _e("/eval/run",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion,systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples},caseIds:a.caseIds,useMock:!!a.useMock,mode:a.mode??"standard",caseSetFile:a.caseSetFile,rawQuestions:a.rawQuestions,eval_target:a.evalTarget,compare_with_report_file:a.compareWithReportFile,analysis_date:a.analysisDate})})},async startEvalRunAsync(a){return _e("/eval/run-async/start",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion,systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples},caseIds:a.caseIds,useMock:!!a.useMock,mode:a.mode??"standard",caseSetFile:a.caseSetFile,rawQuestions:a.rawQuestions,eval_target:a.evalTarget,compare_with_report_file:a.compareWithReportFile,questions:a.questions,scenarioQuestions:a.scenarioQuestions,scenarioTitle:a.scenarioTitle,analysis_date:a.analysisDate})})},async loadEvalRunAsyncStatus(a){return _e(`/eval/run-async/${encodeURIComponent(a)}`)},async cancelEvalRunAsync(a){return _e(`/eval/run-async/${encodeURIComponent(a)}/cancel`,{method:"POST"})},async startRun(){return _e("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(a){return _e("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:a,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return _e("/accounting-agent/v1/runs")},async listResults(){return _e("/accounting-agent/v1/results")},async runTrace(a){return _e(`/accounting-agent/v1/trace/run/${a}`)},async sendAssistantMessage(a){return _e("/assistant/message",{method:"POST",body:JSON.stringify({session_id:a.sessionId??"",mode:"assistant",message:a.userMessage,user_message:a.userMessage,llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion??"address_query_runtime_v1",systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples,context:{period_hint:a.context?.periodHint??"",business_context:a.context?.businessContext??""},useMock:!!a.useMock})})},async loadAssistantSession(a){return _e(`/assistant/session/${a}`)},async saveAutoRunAssistantSession(a){return _e("/autoruns/autogen/save-assistant-session",{method:"POST",body:JSON.stringify(a)})},async loadAssistantAnnotations(a){const m=new URLSearchParams;a?.session_id&&m.set("session_id",a.session_id),typeof a?.limit=="number"&&m.set("limit",String(a.limit));const p=m.toString();return _e(`/assistant/annotations${p?`?${p}`:""}`)},async saveAssistantAnnotation(a){return _e("/assistant/annotations",{method:"POST",body:JSON.stringify(a)})},async loadAutoRunsHistory(a){const m=new URLSearchParams;a?.from&&m.set("from",a.from),a?.to&&m.set("to",a.to),a?.target&&m.set("target",a.target),a?.mode&&m.set("mode",a.mode),a?.use_mock&&m.set("use_mock",a.use_mock),a?.prompt_contains&&m.set("prompt_contains",a.prompt_contains),typeof a?.limit=="number"&&m.set("limit",String(a.limit)),typeof a?.scan_limit=="number"&&m.set("scan_limit",String(a.scan_limit));const p=m.toString();return _e(`/autoruns/history${p?`?${p}`:""}`)},async loadAutoRunDetail(a){return _e(`/autoruns/history/${encodeURIComponent(a)}`)},async loadAutoRunCaseDialog(a,m){return _e(`/autoruns/history/${encodeURIComponent(a)}/case/${encodeURIComponent(m)}/dialog`)},async loadAutoRunAnnotations(a){const m=new URLSearchParams;a?.run_id&&m.set("run_id",a.run_id),a?.case_id&&m.set("case_id",a.case_id),typeof a?.min_rating=="number"&&m.set("min_rating",String(a.min_rating)),a?.manual_case_decision&&m.set("manual_case_decision",a.manual_case_decision),typeof a?.limit=="number"&&m.set("limit",String(a.limit));const p=m.toString();return _e(`/autoruns/annotations${p?`?${p}`:""}`)},async saveAutoRunAnnotation(a){return _e("/autoruns/annotations",{method:"POST",body:JSON.stringify(a)})},async updateAutoRunAnnotation(a){return _e(`/autoruns/annotations/${encodeURIComponent(a.annotation_id)}`,{method:"PATCH",body:JSON.stringify({resolved:a.resolved,resolved_by:a.resolved_by})})},async loadAutoRunPostAnalysis(a){const m=new URLSearchParams;a?.run_id&&m.set("run_id",a.run_id),typeof a?.limit_per_queue=="number"&&m.set("limit_per_queue",String(a.limit_per_queue)),typeof a?.annotation_limit=="number"&&m.set("annotation_limit",String(a.annotation_limit)),typeof a?.scan_limit=="number"&&m.set("scan_limit",String(a.scan_limit)),a?.from&&m.set("from",a.from),a?.to&&m.set("to",a.to),a?.target&&m.set("target",a.target),a?.mode&&m.set("mode",a.mode),a?.use_mock&&m.set("use_mock",a.use_mock),a?.prompt_contains&&m.set("prompt_contains",a.prompt_contains);const p=m.toString();return _e(`/autoruns/post-analysis${p?`?${p}`:""}`)},async loadAutoRunAutogenHistory(a){const m=new URLSearchParams;a?.mode&&m.set("mode",a.mode),typeof a?.limit=="number"&&m.set("limit",String(a.limit));const p=m.toString();return _e(`/autoruns/autogen/history${p?`?${p}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return _e("/autoruns/autogen/personality-catalog")},async updateAutoRunAutogenQuestions(a){return _e(`/autoruns/autogen/history/${encodeURIComponent(a.generation_id)}/questions`,{method:"PATCH",body:JSON.stringify({questions:a.questions})})},async deleteAutoRunAutogenHistoryRecord(a){return _e(`/autoruns/autogen/history/${encodeURIComponent(a)}`,{method:"DELETE"})},async generateAutoRunQuestions(a){return _e("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(a)})}},$f=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,zf=[/\b(?:debug_payload_json|technical_breakdown_json)\b/i,/\b(?:route_summary|semantic_profile|domain_scope|relation_patterns|account_scope)\b/i,/\b(?:coverage_report|retrieval_status|problem_unit_state|candidate_evidence)\b/i,/\b(?:graph_domain_scope|graph_runtime|selection_reason|why_included)\b/i];function vr(a){try{return JSON.stringify(a,null,2)}catch{return String(a)}}function Ff(a){return a==="assistant"?"assistant":"user"}function Cd(a){const m=String(a??""),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(z=>z.trimEnd()).filter(z=>z.trim().length>0).filter(z=>!zf.some(ae=>ae.test(z))).join(` `).trim()}function bf(a,m,p="default"){const S=p==="technical",C=[];C.push("# Assistant conversation export"),C.push(`session_id: ${a||"n/a"}`),C.push(`export_mode: ${p}`),C.push(`exported_at: ${new Date().toISOString()}`),C.push("");for(let M=0;M0&&(S.push("### decomposition_json"),S.push("```json"),S.push(vr(a.decomposition)),S.push("```"),S.push("")),a.assistantMode&&(S.push("### assistant_mode_json"),S.push("```json"),S.push(vr(a.assistantMode)),S.push("```"),S.push("")),(a.annotations??[]).length>0&&(S.push("### annotations_json"),S.push("```json"),S.push(vr(a.annotations)),S.push("```"),S.push("")),a.runSummary&&(S.push("### run_summary_json"),S.push("```json"),S.push(vr(a.runSummary)),S.push("```"),S.push("")),a.coverage&&(S.push("### coverage_json"),S.push("```json"),S.push(vr(a.coverage)),S.push("```"),S.push("")),a.report&&(S.push("### run_report_json"),S.push("```json"),S.push(vr(a.report)),S.push("```"),S.push(""))),S.join(` `)}function Nd({value:a}){return o.jsx("pre",{className:"json-view",children:JSON.stringify(a??{},null,2)})}function aa({title:a,subtitle:m,actions:p,className:S,hideHeader:C,children:M}){return o.jsxs("section",{className:S?`panel-frame ${S}`:"panel-frame",children:[C?null:o.jsxs("header",{className:"panel-header",children:[o.jsxs("div",{children:[o.jsx("h2",{children:a}),m?o.jsx("p",{children:m}):null]}),p?o.jsx("div",{className:"panel-actions",children:p}):null]}),o.jsx("div",{className:"panel-body",children:M})]})}function Bf(a){return a==="assistant"?"Ассистент":"Вы"}function Qf(a){const m=new Date(a);return Number.isNaN(m.getTime())?a:m.toLocaleTimeString("ru-RU")}async function Hf(a){if(navigator.clipboard&&window.isSecureContext)try{return await navigator.clipboard.writeText(a),!0}catch{}const m=document.createElement("textarea");m.value=a,m.setAttribute("readonly","true"),m.style.position="fixed",m.style.opacity="0",m.style.pointerEvents="none",document.body.appendChild(m),m.select();let p=!1;try{p=document.execCommand("copy")}catch{p=!1}finally{document.body.removeChild(m)}return p}function Vf({commented:a}){const m=a?"comment-icon-svg commented":"comment-icon-svg";return o.jsx("svg",{className:m,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M5 6.5h14v9H11.5l-4.5 3v-3H5z"})})}function Gf(a){return a.replace(/\r\n?/g,` `).replace(/([^\n])\s+(Блок\s+\d+\.)/gi,`$1 $2`).replace(/([^\n])\s+(\d+\.\s)/g,`$1 $2`)}function Wf(a){const p=Gf(a).split(` `),S=[];let C=[];const M=()=>{C.length!==0&&(S.push(C.join(` `)),C=[])};for(const z of p){const ae=z.trimEnd(),ne=ae.trim();if(!ne){M();continue}const F=/^Блок\s+\d+\./i.test(ne),X=/^\d+\.\s/.test(ne);(F||X)&&C.length>0&&M(),C.push(ae)}return M(),S.length>0?S:[a]}function qf(a,m){const p=[],S=/\*\*(.+?)\*\*/g;let C=0,M=0,z;for(;(z=S.exec(a))!==null;)z.index>C&&(p.push(o.jsx("span",{children:a.slice(C,z.index)},`${m}-t-${M}`)),M+=1),p.push(o.jsx("strong",{children:z[1]},`${m}-b-${M}`)),M+=1,C=S.lastIndex;return C0?p:[o.jsx("span",{children:a},`${m}-raw`)]}function Kf(a){const m=a.trimStart();return/^Блок\s+\d+\./i.test(m)?"assistant-msg-line heading":/^\d+\.\s/.test(m)?"assistant-msg-line numbered":/^-\s/.test(m)?"assistant-msg-line bullet":"assistant-msg-line"}function Jf(a,m=40){const p=a.replace(/\s+/g," ").trim();if(p.length<=m)return p;const S=p.split(" ").slice(0,3).join(" ").trim();return S.length>=10&&S.length<=m?`${S}…`:`${p.slice(0,m-1).trimEnd()}…`}function Ed(a){return a.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Yf(a){const m=a.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 Xf(a){const m=a.replace(/\r\n?/g,` `).split(` `).map(S=>S.trim()).find(Boolean);return!m||!/^\d+\.\s/.test(m)?!1:Ed(m).includes("|")}function Zf(a,m){const p=m.replace(/\r\n?/g,` `).replace(/\*\*(.+?)\*\*/g,"$1").split(` `).map((C,M)=>{const z=C.trim();return M===0?z.replace(/^\d+\.\s*/,""):z}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!p)return null;const S=Yf(m)||p;return{message_id:a.message_id,source_text:p,anchor_text:S,preview_text:Jf(S)}}function ep(a,m,p,S){return Wf(a.text).map((M,z)=>{const ae=M.split(` `),ne=a.role==="assistant"&&Xf(M),F=ne?Zf(a,M):null,X=!!F&&m?.message_id===F?.message_id&&m?.source_text===F?.source_text,Z=ae.map((te,Me)=>o.jsx("p",{className:Kf(te),children:qf(te,`line-${z}-${Me}`)},`line-${z}-${Me}`));return!ne||!F?o.jsx("div",{className:"assistant-msg-block",children:Z},`block-${z}`):o.jsx("div",{className:X?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(X){S();return}p(F)},onKeyDown:te=>{if(!(te.key!=="Enter"&&te.key!==" ")){if(te.preventDefault(),X){S();return}p(F)}},children:Z},`block-${z}`)})}function tp({sessionId:a,conversation:m,inputValue:p,onInputChange:S,selectedContextChip:C,onSelectContextChip:M,onClearContextChip:z,useMock:ae,onUseMockChange:ne,onSend:F,onClear:X,onSaveSession:Z,busy:te,saveBusy:Me=!1,saveDisabled:pe=!1,statusText:me,errorMessage:ye,showSaveAction:Qe=!1,showCommentAction:Xe=!1,onCommentAssistantMessage:He,isAssistantMessageCommented:Ae,canCommentAssistantMessage:b}){const le=g.useRef(null),Ee=g.useRef(!0),be=g.useRef(null),[St,mt]=g.useState("idle"),[Kt,ht]=g.useState("чат");function B(re=!1){le.current&&(re&&(Ee.current=!0),le.current.scrollTop=le.current.scrollHeight)}g.useEffect(()=>{Ee.current&&B()},[m]),g.useEffect(()=>()=>{be.current!==null&&window.clearTimeout(be.current)},[]);async function Ie(re){if(m.length===0)return;const ee=bf(a,m,re),I=await Hf(ee);ht(re==="technical"?"тех":"чат"),mt(I?"success":"error"),be.current!==null&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>{mt("idle")},2200)}function Je(){if(!le.current)return;const re=le.current,ee=re.scrollHeight-re.scrollTop-re.clientHeight;Ee.current=ee<16}return o.jsx(aa,{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:"Скопировать техчат"}),Qe?o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>Z?.(),disabled:Me||pe,children:Me?"Сохраняю...":"Сохранить"}):null,o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>X(),disabled:te&&m.length===0,children:"Сбросить сессию"})]}),o.jsxs("div",{className:"assistant-toolbar-meta",children:[a?o.jsx("span",{className:"status-chip",children:`session: ${a}`}):null,o.jsxs("div",{className:"assistant-toolbar-meta-right",children:[me?o.jsx("span",{className:"assistant-live-status",children:me}):null,St==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Kt,")"]}):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:le,className:"assistant-chat-list",onScroll:Je,children:m.map((re,ee)=>{const I=re.role==="assistant"&&Xe&&typeof He=="function"&&(typeof b=="function"?b(re,ee):!0),O=re.role==="assistant"&&typeof Ae=="function"?Ae(re,ee):!1;return o.jsxs("article",{className:`assistant-msg ${re.role}`,children:[o.jsxs("header",{className:"assistant-msg-head",children:[o.jsxs("div",{className:"assistant-msg-head-main",children:[o.jsx("strong",{children:Bf(re.role)}),o.jsx("span",{children:Qf(re.created_at)})]}),re.role==="assistant"&&Xe?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:()=>He?.(re,ee),disabled:!I,title:I?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":I?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:o.jsx(Vf,{commented:O})})}):null]}),o.jsx("div",{className:"assistant-msg-body",children:ep(re,C,M,z)}),re.role==="assistant"&&re.debug?o.jsxs("details",{className:"assistant-debug",children:[o.jsx("summary",{children:"Показать технический разбор"}),o.jsx(Nd,{value:re.debug})]}):null]},re.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:z,"aria-label":"Убрать выбранный объект",title:"Убрать выбранный объект",children:"×"})]})]}):null,o.jsxs("label",{className:"full-width",children:["Сообщение",o.jsx("textarea",{className:"assistant-input-textarea",value:p,onChange:re=>S(re.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:ae,onChange:re=>ne(re.target.checked)}),"Mock-режим"]}),o.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{B(!0),F()},disabled:te||!p.trim(),children:te?"Выполняю...":"Отправить"})]})]})]})})}const Zl="http://127.0.0.1:1234/v1",ad="https://api.openai.com/v1",oa="qwen2.5-14b-instruct-1m",eu="unsloth/qwen3-30b-a3b-instruct-2507",np=[{value:oa,label:"Qwen2.5 14B Instruct 1M"},{value:eu,label:"Qwen3 30B A3B Instruct 2507"}];function rp(a){return a.llmProvider!=="local"?"openai":a.model===eu?"local_qwen3":a.model===oa?"local_qwen25":"local_custom"}function sp(a,m){const p=new Map;if(m)for(const S of np)p.set(S.value,S);for(const S of a)p.has(S)||p.set(S,{value:S,label:S});return Array.from(p.values())}function op({value:a,modelOptions:m,modelsBusy:p,onChange:S,onReloadModels:C,onTestConnection:M,onSaveLocalConfig:z,lastStatus:ae,busy:ne,embedded:F=!1}){const X=a.llmProvider==="local",Z=rp(a),te=sp(m,X),Me=te.some(b=>b.value===a.model),[pe,me]=g.useState(String(a.temperature)),[ye,Qe]=g.useState(String(a.maxOutputTokens));g.useEffect(()=>{me(String(a.temperature))},[a.temperature]),g.useEffect(()=>{Qe(String(a.maxOutputTokens))},[a.maxOutputTokens]);const Xe=b=>{const le=b.replace(",",".").trim();if(!le){me(String(a.temperature));return}const Ee=Number(le);if(!Number.isFinite(Ee)){me(String(a.temperature));return}S({...a,temperature:Ee}),me(String(Ee))},He=b=>{const le=b.trim();if(!le){Qe(String(a.maxOutputTokens));return}const Ee=Number.parseInt(le,10);if(!Number.isFinite(Ee)||Ee<=0){Qe(String(a.maxOutputTokens));return}S({...a,maxOutputTokens:Ee}),Qe(String(Ee))},Ae=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{children:["Provider",o.jsxs("select",{value:Z,onChange:b=>{const le=b.target.value;if(le==="openai"){S({...a,llmProvider:"openai",baseUrl:ad});return}if(le==="local_qwen25"){S({...a,llmProvider:"local",model:oa,baseUrl:Zl});return}if(le==="local_qwen3"){S({...a,llmProvider:"local",model:eu,baseUrl:Zl});return}S({...a,llmProvider:"local",model:a.llmProvider==="local"?a.model:oa,baseUrl:Zl})},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:Me?a.model:"__manual__",onChange:b=>{const le=b.target.value;le!=="__manual__"&&S({...a,model:le})},children:[o.jsx("option",{value:"__manual__",children:"Manual input"}),te.map(b=>o.jsx("option",{value:b.value,children:b.label},b.value))]})]}),o.jsxs("label",{children:["Model ID (manual / current)",o.jsx("input",{value:a.model,onChange:b=>S({...a,model:b.target.value}),placeholder:"qwen2.5-14b-instruct-1m or unsloth/qwen3-30b-a3b-instruct-2507"})]}),X?null:o.jsxs("label",{className:"full-width",children:["OpenAI API Key",o.jsx("input",{type:"password",value:a.apiKey,onChange:b=>S({...a,apiKey:b.target.value}),placeholder:"sk-..."})]}),o.jsxs("label",{className:X?"full-width":void 0,children:[X?"Local server base URL":"Base URL",o.jsx("input",{value:a.baseUrl,onChange:b=>S({...a,baseUrl:b.target.value}),placeholder:X?Zl:ad})]}),o.jsxs("label",{children:["Temperature",o.jsx("input",{type:"number",step:"0.1",value:pe,onChange:b=>me(b.target.value),onBlur:b=>Xe(b.target.value),onKeyDown:b=>{b.key==="Enter"&&Xe(b.target.value)}})]}),o.jsxs("label",{children:["Max output tokens",o.jsx("input",{type:"number",value:ye,onChange:b=>Qe(b.target.value),onBlur:b=>He(b.target.value),onKeyDown:b=>{b.key==="Enter"&&He(b.target.value)}})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>z(),children:"Save local config"}),o.jsx("button",{type:"button",onClick:()=>C(),disabled:ne||p,children:p?"Loading models...":"Load model list"}),o.jsx("button",{type:"button",onClick:()=>M(),disabled:ne,children:ne?"Checking...":"Test connection"})]})]});return F?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsxs("div",{className:"embedded-panel-section-header",children:[o.jsxs("div",{children:[o.jsx("h4",{children:"LLM Connector"}),o.jsx("p",{children:"Switch between OpenAI cloud and local OpenAI-compatible server."})]}),o.jsx("span",{className:"status-chip",children:ae||"Status: not checked"})]}),Ae]}):o.jsx(aa,{title:"LLM Connector",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:o.jsx("span",{className:"status-chip",children:ae||"Status: not checked"}),children:Ae})}function lp({value:a,onChange:m,presets:p,selectedPresetId:S,onSelectPreset:C,onLoadPreset:M,onSavePreset:z,onResetDefaults:ae,onDiffPrevious:ne,presetName:F,onPresetNameChange:X,diffSummary:Z,embedded:te=!1}){const Me=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"prompt-manager-grid",children:[o.jsxs("label",{children:["Системный prompt",o.jsx("textarea",{value:a.systemPrompt,onChange:pe=>m({...a,systemPrompt:pe.target.value}),rows:6})]}),o.jsxs("label",{children:["Developer / Instruction prompt",o.jsx("textarea",{value:a.developerPrompt,onChange:pe=>m({...a,developerPrompt:pe.target.value}),rows:6})]}),o.jsxs("label",{children:["Domain prompt",o.jsx("textarea",{value:a.domainPrompt,onChange:pe=>m({...a,domainPrompt:pe.target.value}),rows:6})]}),o.jsxs("label",{children:["Schema notes",o.jsx("textarea",{value:a.schemaNotes,onChange:pe=>m({...a,schemaNotes:pe.target.value}),rows:6})]}),o.jsxs("label",{className:"full-width",children:["Few-shot examples",o.jsx("textarea",{value:a.fewShotExamples,onChange:pe=>m({...a,fewShotExamples:pe.target.value}),rows:8})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("select",{value:S,onChange:pe=>C(pe.target.value),children:[o.jsx("option",{value:"",children:"Выберите preset..."}),p.map(pe=>o.jsx("option",{value:pe.id,children:pe.name},pe.id))]}),o.jsx("button",{type:"button",onClick:()=>M(),children:"Загрузить preset"}),o.jsx("input",{value:F,onChange:pe=>X(pe.target.value),placeholder:"Имя для сохранения"}),o.jsx("button",{type:"button",onClick:()=>z(),children:"Сохранить preset"}),o.jsx("button",{type:"button",onClick:()=>ne(),children:"Diff с предыдущим"}),o.jsx("button",{type:"button",onClick:()=>ae(),children:"Сбросить к default"})]}),Z?o.jsx("p",{className:"diff-summary",children:Z}):null]});return te?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsx("div",{className:"embedded-panel-section-header",children:o.jsxs("div",{children:[o.jsx("h4",{children:"Prompt Manager"}),o.jsx("p",{children:"Системный, developer и domain уровни управляются отдельно."})]})}),Me]}):o.jsx(aa,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:Me})}const Hi={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},ea="needs_dialog_policy_fix",Pt="__all__",la="__live__:",id="ndc_autoruns_ui_config_v1",ud="ndc-autoruns-save",Vi=["Анализ запроса","Получение данных","Подготовка ответа"];function ap(a,m){const p=a.trim();if(!p)return"";if(!m)return p;const S=p.toLowerCase(),C=m.anchor_text.trim(),M=C.toLowerCase();return M&&S.includes(M)?p:`По выбранному объекту "${C}": ${p}`}const Xi=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function ip(a=Xi){return a.reduce((m,p)=>(m[p.id]=p.defaultPrompt,m),{})}const cd={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:ip(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function Gi(a){const m=String(a??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(m)?m:""}function dd(a){const m=typeof a=="number"&&Number.isFinite(a)?Math.trunc(a):160;return Math.max(110,Math.min(520,m))}function up(a){const m=a.getFullYear(),p=String(a.getMonth()+1).padStart(2,"0"),S=String(a.getDate()).padStart(2,"0"),C=String(a.getHours()).padStart(2,"0"),M=String(a.getMinutes()).padStart(2,"0");return`${m}-${p}-${S}T${C}:${M}`}function fd(){const a=new Date;return a.setDate(a.getDate()-14),up(a)}function ta(a){if(!a.trim())return;const m=Date.parse(a);if(Number.isFinite(m))return new Date(m).toISOString()}function gn(a){if(!a)return"нет данных";const m=Date.parse(a);return Number.isFinite(m)?new Date(m).toLocaleString("ru-RU"):a}function pd(a){const m=typeof a.case_message_index=="number"?a.case_message_index:typeof a.message_index=="number"?a.message_index:null;if(m===null||m<0)return null;const p=Math.floor(m/2)+1,S=String(p).padStart(3,"0"),C=a.role==="assistant"?"ответ":"вопрос";return`${S} ${C}`}function Wi(a){return a==="saved_user_sessions"?"Пользовательские сессии":a}function Pd(a){return a?a.context?.agent_run===!0||a.context?.saved_case_set_kind==="agent_semantic_scenario"?!0:typeof a.title=="string"&&a.title.trim().toUpperCase().startsWith("AGENT"):!1}function qi(a){const m=a.title??gn(a.created_at);return Pd(a)&&!m.trim().toUpperCase().startsWith("AGENT")?`AGENT | ${m}`:m}function cp(a){const m=a[a.length-1];return`Ручная сессия ${gn(m?.created_at??new Date().toISOString())}`}function dp(a,m){return m<=0?0:Math.max(0,Math.min(100,Number((a/m*100).toFixed(1))))}function na(a){return typeof a!="number"?"нет данных":`${a.toFixed(1)}%`}function fp(a){return a==="assistant_stage1"?"assistant/s1":a==="assistant_stage2"?"assistant/s2":a==="assistant_p0"?"assistant/p0":a}function md(a){return a==="up"?"Рост":a==="down"?"Регресс":"Без изменений"}function Ki(a){const m=Math.max(1,Math.min(5,Math.round(a)));return`${"●".repeat(m)}${"○".repeat(5-m)}`}function hd(a){return a.length===0?o.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):o.jsx("div",{className:"autoruns-coverage-list",children:a.map(m=>{const p=dp(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 sa(a){return`${la}${a}`}function Js(a){return a.startsWith(la)}function gd(a){return a.startsWith(la)?a.slice(la.length):""}function Td(a){const m=a.report_summary?.run_timestamp??a.created_at,p=Math.max(0,a.total_cases-a.completed_cases);return{run_id:sa(a.job_id),eval_target:a.eval_target,run_timestamp:m,mode:"single-pass-strict",llm_provider:null,model:null,use_mock:null,analysis_date:a.report_summary?.analysis_date??a.analysis_date??null,prompt_version:null,schema_version:null,suite_id:a.case_set_file,cases_total:a.total_cases,requests_total:null,report_path:`async_job:${a.job_id}`,score_index:a.report_summary?.score_index??null,blocking_failures:0,quality_failures:0,closed_cases:a.completed_cases,open_cases:p,domain_coverage:[{domain:"runtime",total_cases:a.total_cases,closed_cases:a.completed_cases}]}}function Qo(a,m){const p=Td(a),S=a.cases.map(X=>({case_id:X.case_id,domain:null,query_class:null,status:X.status==="completed"?"closed":X.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${a.run_id}-${X.case_id}`,dialog_available:X.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),M=m!==Pt&&S.some(X=>X.case_id===m)?m:S.length>0?Pt:"",z={ok:!0,run:p,coverage:{closed_cases:a.completed_cases,open_cases:Math.max(0,a.total_cases-a.completed_cases),domain_coverage:[{domain:"runtime",total_cases:a.total_cases,closed_cases:a.completed_cases}]},cases:S,annotations_summary:{total:0},report:a.report_summary?{run_id:a.report_summary.run_id,run_timestamp:a.report_summary.run_timestamp,score_index:a.report_summary.score_index,cases_total:a.report_summary.cases_total,analysis_date:a.report_summary.analysis_date??a.analysis_date??null}:{}},ae=[];let ne=0;if(M===Pt)for(const X of a.cases)for(let Z=0;ZZ.case_id===M)??null;for(let Z=0;Z<(X?.messages.length??0);Z+=1){const te=X?.messages[Z];te&&ae.push({...te,message_index:Z,case_id:M,case_message_index:Z,commented:!1,annotation:null})}}const F={ok:!0,run_id:p.run_id,case_id:M,source:"assistant_session",session_id:M===Pt?`${a.run_id}::__all__`:`${a.run_id}-${M}`,messages:ae,decomposition:[],assistant_mode:{status:a.status,completed_cases:a.completed_cases,total_cases:a.total_cases},annotations:[]};return{detail:z,dialog:F,caseId:M}}function pp({commented:a}){const m=a?"comment-icon-svg commented":"comment-icon-svg";return o.jsx("svg",{className:m,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M5 6.5h14v9H11.5l-4.5 3v-3H5z"})})}function vd({resolved:a}){return o.jsxs("svg",{className:a?"resolve-icon-svg resolved":"resolve-icon-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[o.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),a?o.jsx("path",{d:"M5.1 8.2 7.2 10.3 11 6.5"}):null]})}function 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 mp({expanded:a}){return o.jsx("svg",{className:a?"autoruns-card-chevron-svg expanded":"autoruns-card-chevron-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M3.5 6.2 8 10.4l4.5-4.2"})})}function hp(){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 gp(){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(a){if(navigator.clipboard&&window.isSecureContext)try{return await navigator.clipboard.writeText(a),!0}catch{}const m=document.createElement("textarea");m.value=a,m.setAttribute("readonly","true"),m.style.position="fixed",m.style.opacity="0",m.style.pointerEvents="none",document.body.appendChild(m),m.select();let p=!1;try{p=document.execCommand("copy")}catch{p=!1}finally{document.body.removeChild(m)}return p}function ra({expanded:a}){return o.jsx("svg",{className:a?"autoruns-group-chevron-svg expanded":"autoruns-group-chevron-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M3.5 6.2 8 10.4l4.5-4.2"})})}function vp({connection:a,modelOptions:m,modelsBusy:p,connectionStatus:S,connectionBusy:C,onConnectionChange:M,onReloadModels:z,onSaveLocalConfig:ae,onTestConnection:ne,prompts:F,onPromptsChange:X,promptPresets:Z,selectedPresetId:te,onSelectPreset:Me,onLoadPreset:pe,onSavePreset:me,onResetDefaults:ye,onDiffPrevious:Qe,presetName:Xe,onPresetNameChange:He,diffSummary:Ae,assistantPromptVersion:b,decompositionPromptVersion:le,showSettingsMode:Ee,showAutoRunsMode:be,showAssistantMode:St,showProgressMode:mt,showCommentsMode:Kt,onLog:ht}){const[B,Ie]=g.useState({...Hi,fromLocal:fd()}),[Je,re]=g.useState(""),[ee,I]=g.useState(null),[O,L]=g.useState(null),[y,k]=g.useState(null),[se,ue]=g.useState([]),[de,xe]=g.useState("all"),[we,je]=g.useState(!1),[Ce,gt]=g.useState(null),[sn,yr]=g.useState([]),[Rn,vn]=g.useState(""),[Se,Jt]=g.useState(""),[Ve,wt]=g.useState(""),[Tt,yn]=g.useState(Xi),[W,vt]=g.useState(cd),[xr,Mn]=g.useState([]),[Ge,Rt]=g.useState(""),[zt,An]=g.useState(""),[ve,Mt]=g.useState([]),[Ze,ys]=g.useState(!1),[st,er]=g.useState(null),[_r,on]=g.useState(""),[In,Ft]=g.useState(null),[xn,Yt]=g.useState(null),[q,At]=g.useState(null),[tr,Kr]=g.useState(null),[Jr,Yr]=g.useState(!1),[Ln,bt]=g.useState(!1),[Dn,On]=g.useState(!1),[$n,zn]=g.useState(!1),[E,Y]=g.useState(!1),[Q,Pe]=g.useState(!1),[et,Ho]=g.useState(!1),[Xr,Vo]=g.useState(!1),[Fn,Ys]=g.useState(""),Sr=g.useRef(null),[Go,Xs]=g.useState("idle"),[Wo,qo]=g.useState("чат"),[Zs,We]=g.useState(""),[it,Oe]=g.useState(""),[ln,Zr]=g.useState([]),[wr,bn]=g.useState([]),[eo,xs]=g.useState(""),[jr,Ut]=g.useState(null),[to,Xt]=g.useState(!1),[Ko,Jo]=g.useState(!1),[ia,Un]=g.useState(""),[_s,Zt]=g.useState(""),[Ss,kr]=g.useState(String(Hi.limit)),[ua,Bn]=g.useState(String(cd.count)),[ws,js]=g.useState(160),[Cr,Qn]=g.useState(""),[es,fe]=g.useState(!1),[nr,no]=g.useState(!0),[Hn,ro]=g.useState(!0),[rr,so]=g.useState(!0),[Vn,ts]=g.useState(!0),[ce,ot]=g.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:ea,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[he,It]=g.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),[yt,jt]=g.useState({open:!1,title:"",saving:!1,error:""}),[en,Nr]=g.useState({open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""}),[Lt,ks]=g.useState({open:!1,generationId:"",title:"",saving:!1,error:""}),Cs=g.useRef(!1),sr=g.useRef(null),ns=g.useRef(null),qe=W.mode==="saved_user_sessions",Gn=g.useMemo(()=>Tt.find(i=>i.id===W.personalityId)??Tt[0]??Xi[0],[W.personalityId,Tt]),tt=g.useMemo(()=>xr.filter(i=>i.mode===W.mode),[xr,W.mode]),Re=g.useMemo(()=>tt.find(i=>i.generation_id===Ge)??tt[0]??null,[Ge,tt]),an=g.useMemo(()=>we?se.filter(i=>!i.resolved):se,[se,we]),Le=an.find(i=>i.annotation_id===Rn)??null,Yo=y?.messages.find(i=>i.message_index===ce.messageIndex)??null,oo=g.useMemo(()=>{if(!y||ce.messageIndex<0)return null;for(let i=ce.messageIndex-1;i>=0;i-=1){const c=y.messages[i];if(c?.role==="user")return c}return null},[ce.messageIndex,y]),or=g.useMemo(()=>{const i=new Map;for(const c of wr)c.message_id&&i.set(c.message_id,c);return i},[wr]),Ns=he.messageIndex>=0?ln[he.messageIndex]??null:null,lo=g.useMemo(()=>{if(he.messageIndex<0)return null;for(let i=he.messageIndex-1;i>=0;i-=1){const c=ln[i];if(c?.role==="user")return c}return null},[he.messageIndex,ln]),ut=g.useMemo(()=>{const i=an.map(f=>({source:"autorun",key:`autorun:${f.annotation_id}`,updated_at:f.updated_at,rating:f.rating,autorun:f,assistant:null})),c=wr.map(f=>({source:"assistant_live",key:`assistant:${f.annotation_id}`,updated_at:f.updated_at,rating:f.rating,autorun:null,assistant:f}));return[...i,...c].sort((f,w)=>Date.parse(w.updated_at)-Date.parse(f.updated_at))},[wr,an]),Es=g.useMemo(()=>{if(ut.length===0)return null;const i=ut.reduce((c,f)=>c+f.rating,0)/ut.length;return Number(i.toFixed(2))},[ut]),Er=g.useMemo(()=>{const i=[...ee?.items??[]];return q&&i.unshift(Td(q)),Se&&!i.some(c=>c.run_id===Se)&&O?.run&&i.unshift(O.run),i},[q,ee?.items,O?.run,Se]),V=g.useCallback(i=>{ht?.(`[autoruns] ${i}`)},[ht]),lr=g.useCallback(async i=>{const c=String(i??"").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);V(`Assistant live annotations load error: ${w}`)}},[V]),_n=g.useCallback(i=>{It(c=>c.saving&&!i?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),rs=g.useCallback(i=>{jt(c=>c.saving&&!i?.force?c:{open:!1,title:"",saving:!1,error:""})},[]),ct=g.useCallback(i=>{Nr(c=>c.saving&&!i?.force?c:{open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""})},[]),Sn=g.useCallback(i=>{ks(c=>c.saving&&!i?.force?c:{open:!1,generationId:"",title:"",saving:!1,error:""})},[]);g.useEffect(()=>()=>{Sr.current!==null&&window.clearTimeout(Sr.current)},[]);const Pr=g.useCallback(async(i,c,f)=>{i.stopPropagation(),i.preventDefault();const w=String(c??"").trim();if(w)try{await _d(w),V(`${f} copied: ${w}`)}catch(A){const ie=A instanceof Error?A.message:String(A);We(`Копирование ${f}: ${ie}`),V(`copy ${f} error: ${ie}`)}},[V]),Tr=g.useCallback(async i=>{if(!y||y.messages.length===0||!Se)return;const c=Uf({runId:Se,caseId:Ve||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},i),f=await _d(c);qo(i==="technical"?"тех":"чат"),Xs(f?"success":"error"),Sr.current!==null&&window.clearTimeout(Sr.current),Sr.current=window.setTimeout(()=>{Xs("idle")},2200),V(f?`Dialog ${i==="technical"?"technical":"chat"} copied: run=${Se} case=${Ve||y.case_id}`:`Dialog copy failed: run=${Se} case=${Ve||y.case_id}`)},[y,V,O,Ve,Se]);function ca(){let i=0;Un(Vi[0]);const c=window.setInterval(()=>{i=Math.min(i+1,Vi.length-1),Un(Vi[i])},650);return()=>window.clearInterval(c)}const ao=g.useCallback(()=>{Oe(""),Zr([]),bn([]),xs(""),Ut(null),Un(""),Zt(""),_n({force:!0}),V("Live-чат ассистента в истории автопрогонов сброшен.")},[_n,V]),io=g.useCallback(async()=>{const i=ap(eo,jr);if(!i)return;Jo(!0),Zt(""),xs(""),Zr(f=>[...f,{message_id:`autoruns-live-${Date.now()}`,session_id:it||"pending",role:"user",text:i,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=ca();try{const f=await Te.sendAssistantMessage({connection:a,prompts:F,userMessage:i,sessionId:it||void 0,promptVersion:b,useMock:to});Oe(f.session_id),Zr(f.conversation),await lr(f.session_id),Un("Ответ готов"),V(`Live-ответ ассистента получен: trace=${f.debug.trace_id}`)}catch(f){const w=f instanceof Error?f.message:String(f);Zt(w),Un("Ошибка ассистента"),V(`Live-чат ассистента: ошибка отправки сообщения: ${w}`)}finally{c(),Jo(!1)}},[eo,jr,it,to,b,a,lr,V,F]),ss=g.useCallback(()=>{if(!it.trim()||ln.length===0){Zt("Сначала получите хотя бы один ответ в живой сессии ассистента.");return}Zt(""),jt({open:!0,title:cp(ln),saving:!1,error:""})},[ln,it]),Ps=g.useCallback(async()=>{const i=it.trim(),c=yt.title.trim();if(!i){jt(f=>({...f,error:"Активная сессия ассистента не найдена."}));return}if(!c){jt(f=>({...f,error:"Укажите название сессии."}));return}jt(f=>({...f,saving:!0,error:""}));try{const f=[F.systemPrompt,F.developerPrompt,F.domainPrompt,F.schemaNotes,F.fewShotExamples].join("||"),w=await Te.saveAutoRunAssistantSession({session_id:i,title:c,generated_by:W.generatedBy.trim()||void 0,context:{llm_provider:a.llmProvider,model:a.model,assistant_prompt_version:b,decomposition_prompt_version:le,prompt_fingerprint:f}});Mn(A=>[w.generation,...A.filter(ie=>ie.generation_id!==w.generation.generation_id)]),vt(A=>({...A,mode:"saved_user_sessions"})),Rt(w.generation.generation_id),rs({force:!0}),V(`Живая сессия сохранена в автопрогоны: ${w.generation.generation_id}`)}catch(f){const w=f instanceof Error?f.message:String(f);jt(A=>({...A,saving:!1,error:w})),V(`Assistant live save error: ${w}`)}},[yt.title,it,b,W.generatedBy,rs,a.llmProvider,a.model,le,V,F.developerPrompt,F.domainPrompt,F.fewShotExamples,F.schemaNotes,F.systemPrompt]),uo=g.useCallback(i=>{const c=i.trim();if(!c){kr(String(B.limit));return}if(!/^\d+$/.test(c)){kr(String(B.limit));return}const f=Number.parseInt(c,10);if(!Number.isFinite(f)){kr(String(B.limit));return}const w=Math.max(1,Math.min(500,f));w!==B.limit&&Ie(A=>({...A,limit:w})),kr(String(w))},[B.limit]),Xo=g.useCallback(i=>{const c=i.trim();if(!c){Bn(String(W.count));return}if(!/^\d+$/.test(c)){Bn(String(W.count));return}const f=Number.parseInt(c,10);if(!Number.isFinite(f)){Bn(String(W.count));return}const w=Math.max(1,Math.min(200,f));w!==W.count&&vt(A=>({...A,count:w})),Bn(String(w))},[W.count]),Zo=g.useCallback(i=>{js(dd(i))},[]),el=g.useCallback(i=>{const c=i.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&Zo(c)},[Zo]),ar=g.useCallback(async()=>{Vo(!0);try{const i=await Te.loadAutoRunAnnotations({limit:800,manual_case_decision:de});ue(i.items),gt(i.manual_case_decision_schema??null),yr(i.available_manual_case_decisions??[]),vn(c=>i.items.length===0?"":i.items.some(f=>f.annotation_id===c)?c:i.items[0].annotation_id)}catch(i){V(`Annotations load error: ${i instanceof Error?i.message:String(i)}`)}finally{Vo(!1)}},[de,V]),un=g.useCallback(async()=>{zn(!0);try{const i=await Te.loadAutoRunAutogenHistory({limit:180});Mn(i.items)}catch(i){V(`Autogen history load error: ${i instanceof Error?i.message:String(i)}`)}finally{zn(!1)}},[V]),tl=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;yn(c.map(f=>({id:f.id,label:f.label,domain:f.domain||"",defaultPrompt:f.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(i){V(`Autogen personality catalog load error: ${i instanceof Error?i.message:String(i)}`)}},[V]),wn=g.useCallback(async()=>{On(!0);try{const i=await Te.loadAutoRunPostAnalysis({run_id:Se&&!Js(Se)?Se:void 0,limit_per_queue:30,annotation_limit:1500,from:ta(B.fromLocal),to:ta(B.toLocal),target:B.target,mode:B.mode,use_mock:B.useMock,prompt_contains:B.promptContains.trim()||void 0});Kr(i)}catch(i){V(`Post-analysis load error: ${i instanceof Error?i.message:String(i)}`),Kr(null)}finally{On(!1)}},[B.fromLocal,B.mode,B.promptContains,B.target,B.toLocal,B.useMock,V,Se]),da=g.useCallback(async()=>{Yr(!0),We("");try{if(W.mode==="saved_user_sessions")throw new Error("Пользовательские сессии сохраняются из живого чата, а не генерируются автоматически.");const i=W.personalityPrompts[W.personalityId]??"",c=[F.systemPrompt,F.developerPrompt,F.domainPrompt,F.schemaNotes,F.fewShotExamples].join(` `).slice(0,900),f=await Te.generateAutoRunQuestions({mode:W.mode,count:W.count,domain:Gn.domain||void 0,persist_to_eval_cases:W.persistToEvalCases,generated_by:W.generatedBy.trim()||void 0,llm:{llm_provider:a.llmProvider,api_key:a.apiKey,model:a.model,base_url:a.baseUrl,temperature:a.temperature,max_output_tokens:a.maxOutputTokens},context:{llm_provider:a.llmProvider,model:a.model,assistant_prompt_version:b,decomposition_prompt_version:le,prompt_fingerprint:c,autogen_personality_id:Gn.id,autogen_personality_prompt:i.trim()||void 0}});V(`Generated ${f.generation.count} questions (${f.generation.mode}) id=${f.generation.generation_id}`+(f.generation.saved_case_set_file?` saved=${f.generation.saved_case_set_file}`:"")),Rt(f.generation.generation_id),Mt([...f.generation.questions??[]]),await un()}catch(i){const c=i instanceof Error?i.message:String(i);We(`Автогенерация: ${c}`),V(`Autogen generate error: ${c}`)}finally{Yr(!1)}},[b,W.count,W.generatedBy,W.mode,W.personalityId,W.personalityPrompts,W.persistToEvalCases,a.apiKey,a.baseUrl,a.llmProvider,a.maxOutputTokens,a.model,a.temperature,le,un,V,F.developerPrompt,F.domainPrompt,F.fewShotExamples,F.schemaNotes,F.systemPrompt,Gn.domain,Gn.id]),os=g.useCallback(async(i,c)=>{if(Js(i)){const f=gd(i);if(q&&q.job_id===f){const w=Qo(q,c);Jt(i),wt(w.caseId),k(w.dialog);return}k(null);return}Ho(!0);try{const f=await Te.loadAutoRunCaseDialog(i,c);k(f)}catch(f){const w=f instanceof Error?f.message:String(f);We(`Диалог кейса: ${w}`),k(null),V(`Dialog load error for ${i}/${c}: ${w}`)}finally{Ho(!1)}},[q,V]),jn=g.useCallback(async(i,c)=>{if(Js(i)){const f=gd(i);if(q&&q.job_id===f){const w=Qo(q,c??Pt);Jt(i),wt(w.caseId),L(w.detail),k(w.dialog);return}Jt(i),wt(""),L(null),k(null);return}Pe(!0);try{const f=await Te.loadAutoRunDetail(i);L(f);const w=(c&&(c===Pt||f.cases.some(A=>A.case_id===c))?c:"")||(f.cases.length>0?Pt:"")||"";Jt(i),wt(w),w?await os(i,w):k(null)}catch(f){const w=f instanceof Error?f.message:String(f);We(`Детализация прогона: ${w}`),L(null),k(null),V(`Run detail load error for ${i}: ${w}`)}finally{Pe(!1)}},[q,os,V]),Wn=g.useCallback(async i=>{Y(!0),We("");try{const c=await Te.loadAutoRunsHistory({from:ta(B.fromLocal),to:ta(B.toLocal),target:B.target,mode:B.mode,use_mock:B.useMock,prompt_contains:B.promptContains.trim()||void 0,limit:B.limit});if(I(c),c.items.length===0){Jt(""),wt(""),L(null),k(null);return}const f=i?.keepSelection??!0,w=i?.preferredRunId??"",A=i?.preferredCaseId??"",ie=f&&w&&c.items.some(nt=>nt.run_id===w)?w:c.items[0].run_id;await jn(ie,f?A:void 0),wn()}catch(c){const f=c instanceof Error?c.message:String(c);We(`История прогонов: ${f}`),V(`History load error: ${f}`)}finally{Y(!1)}},[B.fromLocal,B.limit,B.mode,B.promptContains,B.target,B.toLocal,B.useMock,wn,jn,V]),Dt=g.useCallback(()=>{sr.current!==null&&(window.clearTimeout(sr.current),sr.current=null)},[]),co=g.useCallback(async i=>{try{const c=await Te.loadEvalRunAsyncStatus(i);At(c.job);const f=sa(i);if(Se===f){const w=Qo(c.job,Ve||Pt);L(w.detail),k(w.dialog),wt(w.caseId)}if(c.job.status==="completed"){Dt(),bt(!1),fe(!1),Qn("");const w=c.job.report_summary?.run_id??c.job.run_id;await Wn({keepSelection:!0,preferredRunId:w||Se,preferredCaseId:Pt}),await un(),At(null);return}if(c.job.status==="failed"){Dt(),bt(!1),fe(!1),Qn(""),We(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),V(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}if(c.job.status==="canceled"){Dt(),bt(!1),fe(!1),Qn(""),At(null),await Wn({keepSelection:!1}),await un(),V(`Autogen async run canceled: job=${c.job.job_id}`);return}Dt(),sr.current=window.setTimeout(()=>{co(i)},500)}catch(c){Dt(),bt(!1),fe(!1),Qn("");const f=c instanceof Error?c.message:String(c);We(`Запуск прогонов: ${f}`),V(`Autogen async status error: ${f}`)}},[un,Wn,V,Ve,Se,Dt]),nl=g.useCallback(async(i,c)=>{Dt(),bt(!0),We("");try{const f=i??Re;if(!f)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const A=(c??(Re?.generation_id===f.generation_id?ve:f.questions)).map(_o=>_o.trim()).filter(_o=>_o.length>0);if(A.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const ie=B.useMock==="true",nt=Gi(Je),Bt=f.mode==="saved_user_sessions",Lr=(await Te.startEvalRunAsync({connection:a,prompts:F,promptVersion:b,mode:"single-pass-strict",caseSetFile:Bt?void 0:f.saved_case_set_file??void 0,useMock:ie,evalTarget:"assistant_stage1",questions:Bt?void 0:A,scenarioQuestions:Bt?A:void 0,scenarioTitle:Bt?f.title??void 0:void 0,analysisDate:Bt?void 0:nt||void 0})).job;Qn(f.generation_id),fe(!1),At(Lr);const Sa=sa(Lr.job_id),xo=Qo(Lr,Pt);Jt(Sa),wt(xo.caseId),L(xo.detail),k(xo.dialog),V(`Запущен async-прогон job=${Lr.job_id}, run_id=${Lr.run_id}, вопросов=${A.length}`+(f.saved_case_set_file?`, base_case_set=${f.saved_case_set_file}`:"")+(Bt?", replay_mode=saved_user_session_scenario":nt?`, analysis_date=${nt}`:", analysis_date=current_state")),co(Lr.job_id)}catch(f){const w=f instanceof Error?f.message:String(f);We(`Запуск прогонов: ${w}`),V(`Autogen run error: ${w}`),bt(!1),fe(!1),Qn("")}},[Je,b,a,ve,B.useMock,V,co,F,Re,Dt]),Ts=g.useCallback(async()=>{const i=q?.job_id??"";if(!i){bt(!1),fe(!1),Qn(""),At(null),Dt();return}fe(!0),We("");try{const c=await Te.cancelEvalRunAsync(i);Dt(),At(null),bt(!1),fe(!1),Qn(""),await Wn({keepSelection:!1}),await un(),V(`Autogen async run stopped: job=${c.job.job_id}`)}catch(c){const f=c instanceof Error?c.message:String(c);fe(!1),We(`Остановка прогона: ${f}`),V(`Autogen stop error: ${f}`)}},[q,un,Wn,V,Dt]),fa=g.useCallback(i=>{if(i.role!=="assistant")return;const c=i.case_id??Ve,f=i.case_message_index??i.message_index;ot({open:!0,caseId:c,caseMessageIndex:f,messageIndex:i.message_index,rating:i.annotation?.rating??3,comment:i.annotation?.comment??"",manualCaseDecision:i.annotation?.manual_case_decision??ea,annotationAuthor:i.annotation?.annotation_author??W.generatedBy,saving:!1,error:""})},[W.generatedBy,Ve]),Rs=g.useCallback(i=>{ot(c=>c.saving&&!i?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:ea,annotationAuthor:W.generatedBy,saving:!1,error:""})},[W.generatedBy]),pa=g.useCallback(async()=>{const i=Se,c=ce.caseId,f=ce.caseMessageIndex;if(!(!i||!c||f<0)){if(Js(i)){ot(w=>({...w,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ce.comment.trim()){ot(w=>({...w,error:"Добавьте комментарий."}));return}ot(w=>({...w,saving:!0,error:""}));try{await Te.saveAutoRunAnnotation({run_id:i,case_id:c,message_index:f,rating:ce.rating,comment:ce.comment.trim(),manual_case_decision:ce.manualCaseDecision,annotation_author:ce.annotationAuthor.trim()||void 0}),Rs({force:!0}),Promise.all([jn(i,Ve),ar(),wn()]).catch(w=>{const A=w instanceof Error?w.message:String(w);We(`Обновление после комментария: ${A}`),V(`Comment refresh error: ${A}`)})}catch(w){ot(A=>({...A,saving:!1,error:w instanceof Error?w.message:String(w)}))}}},[Rs,ce.annotationAuthor,ce.caseId,ce.caseMessageIndex,ce.comment,ce.manualCaseDecision,ce.rating,ar,wn,jn,V,Ve,Se]),rl=g.useCallback(i=>i.role==="assistant",[]),ma=g.useCallback(i=>i.role==="assistant"&&or.has(i.message_id),[or]),ha=g.useCallback((i,c)=>{if(i.role!=="assistant")return;const f=it.trim(),w=String(i.session_id??"").trim();if(!(f||w)){Zt("Сначала получите ответ ассистента в активной сессии.");return}!f&&w&&Oe(w);const ie=or.get(i.message_id)??null;Zt(""),It({open:!0,messageIndex:c,rating:ie?.rating??3,comment:ie?.comment??"",annotationAuthor:ie?.annotation_author??"manual_reviewer",saving:!1,error:""})},[or,it]),ga=g.useCallback(async()=>{if(he.messageIndex<0)return;if(!he.comment.trim()){It(f=>({...f,error:"Добавьте комментарий."}));return}const i=ln[he.messageIndex]??null,c=it.trim()||(i?.role==="assistant"?String(i.session_id??"").trim():"");if(!c){It(f=>({...f,error:"Сессия ассистента не найдена."}));return}It(f=>({...f,saving:!0,error:""}));try{const f=await Te.saveAssistantAnnotation({session_id:c,message_index:he.messageIndex,rating:he.rating,comment:he.comment.trim(),annotation_author:he.annotationAuthor.trim()||void 0});bn(w=>{const A=[...w],ie=A.findIndex(nt=>nt.annotation_id===f.annotation.annotation_id);return ie>=0?A[ie]=f.annotation:A.unshift(f.annotation),A.sort((nt,Bt)=>Date.parse(Bt.updated_at)-Date.parse(nt.updated_at))}),_n({force:!0})}catch(f){const w=f instanceof Error?f.message:String(f);It(A=>({...A,saving:!1,error:w}))}},[he.annotationAuthor,he.comment,he.messageIndex,he.rating,ln,it,_n]);g.useCallback(i=>{if(!Re||Re.mode!=="saved_user_sessions")return;const c=ve[i]??"";Nr({open:!0,generationId:Re.generation_id,questionIndex:i,questionText:c,saving:!1,error:""})},[ve,Re]);const va=g.useCallback(async()=>{const i=en.generationId,c=en.questionIndex;if(!i||c<0)return;const f=ve.filter((w,A)=>A!==c);if(f.length===0){Nr(w=>({...w,error:"Нельзя удалить последний вопрос из сохраненной сессии."}));return}Nr(w=>({...w,saving:!0,error:""}));try{const w=await Te.updateAutoRunAutogenQuestions({generation_id:i,questions:f});Mn(A=>A.map(ie=>ie.generation_id===i?w.generation:ie)),Mt(w.generation.questions),ct({force:!0}),V(`Обновлена сохраненная сессия: ${i}`)}catch(w){const A=w instanceof Error?w.message:String(w);Nr(ie=>({...ie,saving:!1,error:A})),V(`Saved session question delete error: ${A}`)}},[ct,ve,V,en.generationId,en.questionIndex]),qn=g.useCallback(async(i,c)=>{const f=Re?.generation_id??"",w=c?.revertQuestions??ve;if(Mt(i),!f)return!0;ys(!0);try{const A=await Te.updateAutoRunAutogenQuestions({generation_id:f,questions:i});return Mn(ie=>ie.map(nt=>nt.generation_id===f?A.generation:nt)),Mt([...A.generation.questions??[]]),c?.successLog&&V(c.successLog),!0}catch(A){const ie=A instanceof Error?A.message:String(A);return Mt(w),We(`Вопросы к запуску: ${ie}`),V(`Autogen questions update error: ${ie}`),!1}finally{ys(!1)}},[ve,V,Re]),sl=g.useCallback(i=>{er(i),on(ve[i]??"")},[ve]),Kn=g.useCallback(()=>{er(null),on("")},[]),Rr=g.useCallback(async i=>{if(i===null)return;const c=ve[i]??"",f=_r.trim();if(!f||f===c){Kn();return}const w=ve.map((ie,nt)=>nt===i?f:ie);await qn(w,{successLog:`Список вопросов обновлен: ${Re?.generation_id??"local"}`,revertQuestions:ve})&&Kn()},[ve,_r,Re,Kn,qn]),Mr=g.useCallback(()=>{Rr(st)},[Rr,st]),ol=g.useCallback(i=>{if(i.key==="Enter"){i.preventDefault(),Rr(st);return}i.key==="Escape"&&(i.preventDefault(),Kn())},[Rr,st,Kn]),fo=g.useCallback(async()=>{const i=[...ve,"Новый вопрос"],c=i.length-1;await qn(i,{successLog:`В список добавлен вопрос: ${Re?.generation_id??"local"}`,revertQuestions:ve})&&(er(c),on(i[c]))},[ve,Re,qn]),po=g.useCallback(async i=>{if(ve.length<=1){We("В списке должен остаться хотя бы один вопрос.");return}const c=ve.filter((w,A)=>A!==i);await qn(c,{successLog:`Из списка удален вопрос: ${Re?.generation_id??"local"}`,revertQuestions:ve})&&(er(w=>w===null?w:w===i?null:w>i?w-1:w),on(""))},[ve,Re,qn]),mo=g.useCallback((i,c)=>{if(Ze){i.preventDefault();return}Ft(c),Yt(c),i.dataTransfer.effectAllowed="move",i.dataTransfer.setData("text/plain",String(c))},[Ze]),ho=g.useCallback((i,c)=>{i.preventDefault(),xn!==c&&Yt(c),i.dataTransfer.dropEffect="move"},[xn]),go=g.useCallback(async(i,c)=>{i.preventDefault();const f=In;if(Yt(null),Ft(null),f===null||f===c)return;const w=[...ve],[A]=w.splice(f,1);w.splice(c,0,A),await qn(w,{successLog:`Порядок вопросов обновлен: ${Re?.generation_id??"local"}`,revertQuestions:ve})},[In,ve,Re,qn]),ir=g.useCallback(()=>{Ft(null),Yt(null)},[]),ya=g.useCallback(i=>{Rt(i),An(c=>c===i?"":i)},[]),ll=g.useCallback(i=>{ks({open:!0,generationId:i.generation_id,title:i.title??`${Wi(i.mode)} ${gn(i.created_at)}`,saving:!1,error:""})},[]),xa=g.useCallback(async()=>{const i=Lt.generationId.trim();if(i){ks(c=>({...c,saving:!0,error:""}));try{const c=await Te.deleteAutoRunAutogenHistoryRecord(i);Mn(f=>f.filter(w=>w.generation_id!==c.generation_id)),Sn({force:!0}),V(`Удален набор автопрогона: ${c.generation_id}`+(c.deleted_files.length>0?`, files=${c.deleted_files.length}`:""))}catch(c){const f=c instanceof Error?c.message:String(c);ks(w=>({...w,saving:!1,error:f})),V(`Autogen record delete error: ${f}`)}}},[Lt.generationId,Sn,V]),vo=g.useCallback(i=>{ue(c=>c.map(f=>f.annotation_id===i.annotation_id?{...f,...i}:f)),k(c=>c&&{...c,annotations:c.annotations.map(f=>f.annotation_id===i.annotation_id?i:f),messages:c.messages.map(f=>!f.annotation||f.annotation.annotation_id!==i.annotation_id?f:{...f,commented:!0,annotation:i})})},[]),yo=g.useCallback(async(i,c)=>{if(i.annotation_id){if(Js(i.run_id)){We("Статус выполнения можно менять только для завершённых прогонов.");return}Ys(i.annotation_id);try{const f=await Te.updateAutoRunAnnotation({annotation_id:i.annotation_id,resolved:c,resolved_by:W.generatedBy||void 0});vo(f.annotation),wn()}catch(f){const w=f instanceof Error?f.message:String(f);We(`Смена статуса кейса: ${w}`),V(`Annotation resolve toggle error: ${w}`)}finally{Ys("")}}},[vo,W.generatedBy,wn,V]),Ar=g.useCallback(async i=>{vn(i.annotation_id),await jn(i.run_id,i.case_id),ee?.items.some(c=>c.run_id===i.run_id)||We("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[ee?.items,jn]);g.useEffect(()=>{Cs.current||(Cs.current=!0,Wn({keepSelection:!1}),un(),tl(),wn())},[un,tl,Wn,wn]),g.useEffect(()=>{Cs.current&&ar()},[de,ar]),g.useEffect(()=>{vn(i=>an.length===0?"":an.some(c=>c.annotation_id===i)?i:an[0].annotation_id)},[an]),g.useEffect(()=>{Rt(i=>tt.length===0?"":i&&tt.some(c=>c.generation_id===i)?i:tt[0].generation_id)},[tt]),g.useEffect(()=>{if(!Re){Mt([]),Kn(),Ft(null),Yt(null);return}Mt([...Re.questions]),Kn(),Ft(null),Yt(null)},[Re,Kn]),g.useEffect(()=>{if(st===null)return;const i=window.setTimeout(()=>{ns.current?.focus(),ns.current?.select()},0);return()=>window.clearTimeout(i)},[st]),g.useEffect(()=>{if(!qe){An("");return}zt&&!tt.some(i=>i.generation_id===zt)&&An("")},[zt,qe,tt]),g.useEffect(()=>{kr(String(B.limit))},[B.limit]),g.useEffect(()=>{Bn(String(W.count))},[W.count]),g.useEffect(()=>{if(!it.trim()){bn([]);return}lr(it)},[it,lr]),g.useEffect(()=>{if(!q)return;const i=sa(q.job_id);if(Se!==i)return;const c=Qo(q,Ve||Pt);L(c.detail),k(c.dialog),wt(c.caseId)},[q,Ve,Se]),g.useEffect(()=>()=>{Dt()},[Dt]),g.useEffect(()=>{Tt.length!==0&&vt(i=>{let c=!1;const f={...i.personalityPrompts};for(const A of Tt)(typeof f[A.id]!="string"||f[A.id].trim().length===0)&&(f[A.id]=A.defaultPrompt,c=!0);let w=i.personalityId;return Tt.some(A=>A.id===i.personalityId)||(w=Tt[0].id,c=!0),c?{...i,personalityId:w,personalityPrompts:f}:i})},[Tt]),g.useEffect(()=>{const i=localStorage.getItem(id);if(i)try{const c=JSON.parse(i);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"&&re(Gi(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&js(dd(c.autogenPersonalityPromptHeight)),c.groupsExpanded&&(typeof c.groupsExpanded.filters=="boolean"&&no(c.groupsExpanded.filters),typeof c.groupsExpanded.generationContext=="boolean"&&ro(c.groupsExpanded.generationContext),typeof c.groupsExpanded.autogen=="boolean"&&so(c.groupsExpanded.autogen),typeof c.groupsExpanded.savedSessions=="boolean"&&ts(c.groupsExpanded.savedSessions)),c.autoGenSettings&&vt(f=>{const w={...f.personalityPrompts},A=c.autoGenSettings?.personalityPrompts??{};for(const[nt,Bt]of Object.entries(A))typeof Bt=="string"&&nt.trim().length>0&&(w[nt.trim()]=Bt);const ie=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():f.personalityId;return{...f,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"||c.autoGenSettings?.mode==="saved_user_sessions"?c.autoGenSettings.mode:f.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):f.count,personalityId:ie,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 Ir=g.useCallback(()=>{const i={filters:B,analysisDate:Je,autogenPersonalityPromptHeight:ws,groupsExpanded:{filters:nr,generationContext:Hn,autogen:rr,savedSessions:Vn},autoGenSettings:{mode:W.mode,count:W.count,personalityId:W.personalityId,personalityPrompts:W.personalityPrompts,persistToEvalCases:W.persistToEvalCases,generatedBy:W.generatedBy},annotationDecisionFilter:de,hideResolvedAnnotations:we};localStorage.setItem(id,JSON.stringify(i))},[Je,de,W,rr,ws,B,nr,Hn,we,Vn]);return g.useEffect(()=>{const i=()=>{Ir(),V("Сохранены настройки панели автопрогонов.")};return window.addEventListener(ud,i),()=>{window.removeEventListener(ud,i)}},[V,Ir]),o.jsxs(aa,{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(op,{embedded:!0,value:a,modelOptions:m,modelsBusy:p,onChange:M,onReloadModels:z,onSaveLocalConfig:ae,onTestConnection:ne,lastStatus:S,busy:C}),o.jsx(lp,{embedded:!0,value:F,onChange:X,presets:Z,selectedPresetId:te,onSelectPreset:Me,onLoadPreset:pe,onSavePreset:me,onResetDefaults:ye,onDiffPrevious:Qe,presetName:Xe,onPresetNameChange:He,diffSummary:Ae})]})]}):null,be?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:()=>no(i=>!i),"aria-label":nr?"Скрыть группу настройки выборки":"Показать группу настройки выборки",title:nr?"Скрыть группу":"Показать группу",children:o.jsx(ra,{expanded:nr})})]}),nr?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:i=>Ie(c=>({...c,fromLocal:i.target.value}))})]}),o.jsxs("label",{children:["Дата по",o.jsx("input",{type:"datetime-local",value:B.toLocal,onChange:i=>Ie(c=>({...c,toLocal:i.target.value}))})]}),o.jsxs("label",{children:["Целевой контур",o.jsxs("select",{value:B.target,onChange:i=>Ie(c=>({...c,target:i.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(ee?.available.targets??[]).map(i=>o.jsx("option",{value:i,children:i},i))]})]}),o.jsxs("label",{children:["Режим",o.jsxs("select",{value:B.mode,onChange:i=>Ie(c=>({...c,mode:i.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(ee?.available.modes??[]).map(i=>o.jsx("option",{value:i,children:i},i))]})]}),o.jsxs("label",{children:["Использовать mock",o.jsxs("select",{value:B.useMock,onChange:i=>Ie(c=>({...c,useMock:i.target.value})),children:[o.jsx("option",{value:"any",children:"любой"}),o.jsx("option",{value:"true",children:"да"}),o.jsx("option",{value:"false",children:"нет"})]})]}),o.jsxs("label",{children:["Лимит",o.jsx("input",{type:"number",min:1,max:500,value:Ss,onChange:i=>{const c=i.target.value;(c===""||/^\d+$/.test(c))&&kr(c)},onBlur:i=>uo(i.target.value),onKeyDown:i=>{i.key==="Enter"&&uo(i.target.value)}})]}),o.jsxs("label",{className:"full-width",children:["Версия промпта содержит",o.jsx("input",{value:B.promptContains,onChange:i=>Ie(c=>({...c,promptContains:i.target.value})),placeholder:"normalizer_v2_0_2 / address_query_runtime_v1",list:"autoruns-prompt-versions"})]})]}),o.jsx("datalist",{id:"autoruns-prompt-versions",children:(ee?.available.prompt_versions??[]).map(i=>o.jsx("option",{value:i},i))}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:E,onClick:()=>{Wn({keepSelection:!1})},children:E?"Обновляю...":"Применить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{Ie({...Hi,fromLocal:fd()}),We("")},children:"Сбросить фильтры"})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Контур генерации"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>ro(i=>!i),"aria-label":Hn?"Скрыть группу контура генерации":"Показать группу контура генерации",title:Hn?"Скрыть группу":"Показать группу",children:o.jsx(ra,{expanded:Hn})})]}),Hn?o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Провайдер:"}),o.jsx("strong",{children:a.llmProvider})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Модель:"}),o.jsx("strong",{children:a.model||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт ассистента:"}),o.jsx("strong",{children:b})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт декомпозиции:"}),o.jsx("strong",{children:le})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Автопрогоны"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>so(i=>!i),"aria-label":rr?"Скрыть группу автопрогонов":"Показать группу автопрогонов",title:rr?"Скрыть группу":"Показать группу",children:o.jsx(ra,{expanded:rr})})]}),rr?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Режимы",o.jsxs("select",{value:W.mode,onChange:i=>vt(c=>({...c,mode:i.target.value})),children:[o.jsx("option",{value:"codex_creative",children:"codex_creative"}),o.jsx("option",{value:"qwen_seed",children:"qwen_seed"}),o.jsx("option",{value:"saved_user_sessions",children:"Пользовательские сессии"})]})]}),qe?null:o.jsxs(o.Fragment,{children:[o.jsxs("label",{children:["Кол-во",o.jsx("input",{type:"number",min:1,max:200,value:ua,onChange:i=>{const c=i.target.value;(c===""||/^\d+$/.test(c))&&Bn(c)},onBlur:i=>Xo(i.target.value),onKeyDown:i=>{i.key==="Enter"&&Xo(i.target.value)}})]}),o.jsxs("label",{children:["Личность автогенерации",o.jsx("select",{value:W.personalityId,onChange:i=>vt(c=>({...c,personalityId:i.target.value})),children:Tt.map(i=>o.jsx("option",{value:i.id,children:i.label},i.id))})]}),o.jsxs("label",{children:["Кто генерирует",o.jsx("input",{value:W.generatedBy,onChange:i=>vt(c=>({...c,generatedBy:i.target.value})),placeholder:"manual_reviewer"})]}),o.jsxs("label",{className:"full-width",children:["Промпт личности",o.jsx("textarea",{className:"autoruns-personality-prompt",value:W.personalityPrompts[W.personalityId]??"",onChange:i=>vt(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:i.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${ws}px`},onMouseUp:el,onTouchEnd:el})]}),o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:W.persistToEvalCases,onChange:i=>vt(c=>({...c,persistToEvalCases:i.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]})]}),qe?null:o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата анализа (срез)",o.jsx("input",{type:"date",value:Je,onChange:i=>re(Gi(i.target.value))})]}),o.jsx("div",{className:"button-row",children:o.jsx("button",{type:"button",className:"tab",disabled:!Je,onClick:()=>re(""),children:"Сбросить дату среза"})})]}),o.jsxs("div",{className:"button-row",children:[qe?null:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:Jr,onClick:()=>{da()},children:Jr?"Генерирую...":"Сгенерировать пачку"}),o.jsx("button",{type:"button",className:"tab",disabled:$n,onClick:()=>{un()},children:$n?"Обновляю...":"Обновить историю"})]}),o.jsx("button",{type:"button",className:"autoruns-run-launch-btn",style:qe?{display:"none"}:void 0,disabled:es||!Ln&&(ve.length===0||!Re),onClick:()=>{Ln?Ts():nl()},children:Ln?es?"Останавливаю...":"Остановить прогон":"Запустить прогон"})]}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{className:"full-width",children:[qe?"Сохраненная сессия":"Кейс-сет для запуска",o.jsxs("select",{value:Ge,onChange:i=>Rt(i.target.value),disabled:tt.length===0,children:[tt.length===0?o.jsx("option",{value:"",children:qe?"нет сохраненных сессий":"нет генераций"}):null,tt.map(i=>o.jsxs("option",{value:i.generation_id,children:[gn(i.created_at)," | ",qi(i)??Wi(i.mode)," | ",i.count]},i.generation_id))]})]})}),o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-generated-questions",style:qe?{display:"none"}:void 0,children:[o.jsx("div",{className:"autoruns-generated-questions-head",children:o.jsxs("strong",{children:["Вопросы к запуску: ",ve.length]})}),ve.length===0?o.jsx("p",{className:"muted",children:qe?"Список вопросов пуст. Сначала сохраните живую пользовательскую сессию.":"Список вопросов пуст. Сгенерируйте пачку или добавьте вопрос вручную."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:ve.map((i,c)=>o.jsxs("div",{className:["autoruns-generated-question-item",xn===c?"drag-over":"",In===c?"dragging":"",st===c?"editing":""].filter(Boolean).join(" "),onDragOver:f=>ho(f,c),onDrop:f=>{go(f,c)},children:[o.jsx("button",{type:"button",className:"autoruns-question-grip-btn",draggable:!Ze&&st!==c,disabled:Ze||st===c,onDragStart:f=>mo(f,c),onDragEnd:ir,title:"Перетащить вопрос","aria-label":`Перетащить вопрос ${c+1}`,children:o.jsx(xd,{})}),st===c?o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:ns,className:"autoruns-generated-question-input",value:_r,onChange:f=>on(f.target.value),onBlur:Mr,onKeyDown:ol,placeholder:"Текст вопроса",disabled:Ze}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onMouseDown:f=>f.preventDefault(),onClick:()=>{po(c)},title:"Удалить вопрос","aria-label":`Удалить вопрос ${c+1}`,disabled:Ze,children:"×"})]}):o.jsxs("button",{type:"button",className:"autoruns-generated-question-text",onDoubleClick:()=>sl(c),title:"Двойной клик для редактирования",children:[c+1,". ",i]})]},`${c}-${i.slice(0,24)}`))}),o.jsx("button",{type:"button",className:"autoruns-add-question-btn",onClick:()=>{fo()},disabled:!Re||Ze,children:"+"})]}),qe?null:o.jsx("p",{className:"muted",children:"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:qe?"Сохраненные пользовательские сессии":"История автогенераций"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>ts(i=>!i),"aria-label":Vn?qe?"Скрыть группу сохраненных пользовательских сессий":"Скрыть группу истории автогенераций":qe?"Показать группу сохраненных пользовательских сессий":"Показать группу истории автогенераций",title:Vn?"Скрыть группу":"Показать группу",children:o.jsx(ra,{expanded:Vn})})]}),Vn?o.jsxs("div",{className:"autoruns-autogen-list",children:[$n?o.jsx("p",{className:"muted",children:qe?"Загружаю сохраненные пользовательские сессии...":"Загружаю историю автогенераций..."}):null,!$n&&tt.length===0?o.jsx("p",{className:"muted",children:qe?"Сохраненные пользовательские сессии пока пусты.":"История автогенераций пока пустая."}):null,tt.slice(0,30).map(i=>{const c=Ln&&Cr===i.generation_id,f=Ln&&Cr!==i.generation_id;return o.jsxs("article",{className:["autoruns-autogen-item",Ge===i.generation_id?"selected":"",zt===i.generation_id?"expanded":"",qe?"saved-session":""].filter(Boolean).join(" "),onClick:qe?void 0:()=>Rt(i.generation_id),children:[qe?o.jsxs("div",{className:"autoruns-saved-session-topbar",children:[o.jsx("button",{type:"button",className:"autoruns-saved-session-icon-btn",disabled:es||f,onClick:w=>{if(w.preventDefault(),w.stopPropagation(),c){Ts();return}Rt(i.generation_id),nl(i,Ge===i.generation_id?ve:i.questions)},title:c?"Остановить прогон":"Запустить прогон","aria-label":`${c?"Остановить прогон":"Запустить прогон"} для ${qi(i)}`,children:c?o.jsx(gp,{}):o.jsx(hp,{})}),o.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),ll(i)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${i.generation_id}`,children:"×"})]}):null,o.jsxs("header",{children:[o.jsx("strong",{children:qi(i)}),o.jsx("div",{className:"autoruns-autogen-card-actions",children:o.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),ll(i)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${i.generation_id}`,children:"×"})})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Дата и время"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",gn(i.created_at)]})]}),o.jsxs("div",{className:"autoruns-saved-session-meta autoruns-saved-session-meta-id",children:[o.jsxs("div",{className:"autoruns-saved-session-meta-id-main",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"ID"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",i.generation_id]})]}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:w=>{Pr(w,i.generation_id,"set id")},onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),Pr(w,i.generation_id,"set id"))},title:"Скопировать id набора","aria-label":`Скопировать id набора ${i.generation_id}`,children:o.jsx(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:["| ",Wi(i.mode)]})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Тип"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",Pd(i)?"АГЕНТНЫЙ ПРОГОН":"АВТОПРОГОН"]})]}),qe?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Количество вопросов"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",i.questions.length]})]}),o.jsx("div",{className:"autoruns-saved-session-footer",children:o.jsx("button",{type:"button",className:"autoruns-saved-session-icon-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),ya(i.generation_id)},title:zt===i.generation_id?"Скрыть вопросы":"Показать вопросы","aria-label":zt===i.generation_id?"Скрыть вопросы":"Показать вопросы",children:o.jsx(mp,{expanded:zt===i.generation_id})})}),o.jsx("div",{className:zt===i.generation_id?"autoruns-saved-session-questions expanded":"autoruns-saved-session-questions",children:o.jsxs("div",{className:"autoruns-generated-questions autoruns-generated-questions-embedded",children:[o.jsx("div",{className:"autoruns-generated-questions-head",children:o.jsxs("strong",{children:["Вопросы к запуску:"," ",Ge===i.generation_id?ve.length:i.questions.length]})}),(Ge===i.generation_id?ve:i.questions).length===0?o.jsx("p",{className:"muted",children:"Список вопросов пуст."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:(Ge===i.generation_id?ve:i.questions).map((w,A)=>o.jsxs("div",{className:["autoruns-generated-question-item",xn===A&&Ge===i.generation_id?"drag-over":"",In===A&&Ge===i.generation_id?"dragging":"",st===A&&Ge===i.generation_id?"editing":""].filter(Boolean).join(" "),onDragOver:ie=>Ge===i.generation_id?ho(ie,A):void 0,onDrop:ie=>Ge===i.generation_id?void go(ie,A):void 0,children:[o.jsx("button",{type:"button",className:"autoruns-question-grip-btn",draggable:Ge===i.generation_id&&!Ze&&st!==A,disabled:Ge!==i.generation_id||Ze||st===A,onDragStart:ie=>{Rt(i.generation_id),mo(ie,A)},onDragEnd:ir,title:"Перетащить вопрос","aria-label":`Перетащить вопрос ${A+1}`,children:o.jsx(xd,{})}),Ge===i.generation_id&&st===A?o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:ns,className:"autoruns-generated-question-input",value:_r,onChange:ie=>on(ie.target.value),onBlur:Mr,onKeyDown:ol,placeholder:"Текст вопроса",disabled:Ze}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onMouseDown:ie=>ie.preventDefault(),onClick:()=>{po(A)},title:"Удалить вопрос","aria-label":`Удалить вопрос ${A+1}`,disabled:Ze,children:"×"})]}):o.jsxs("button",{type:"button",className:"autoruns-generated-question-text",onDoubleClick:()=>{Rt(i.generation_id),sl(A)},title:"Двойной клик для редактирования",children:[A+1,". ",w]})]},`${i.generation_id}-${A}-${w.slice(0,24)}`))}),o.jsx("button",{type:"button",className:"autoruns-add-question-btn",onClick:()=>{Rt(i.generation_id),fo()},disabled:Ge!==i.generation_id||Ze,children:"+"})]})})]}):null]},i.generation_id)})]}):null,o.jsxs("details",{className:"autoruns-prompt-details",children:[o.jsx("summary",{children:"Копия активного промпта (только чтение)"}),o.jsxs("label",{children:["Системный",o.jsx("textarea",{readOnly:!0,value:F.systemPrompt})]}),o.jsxs("label",{children:["Разработчика",o.jsx("textarea",{readOnly:!0,value:F.developerPrompt})]}),o.jsxs("label",{children:["Доменный",o.jsx("textarea",{readOnly:!0,value:F.domainPrompt})]}),o.jsxs("label",{children:["Заметки по схеме",o.jsx("textarea",{readOnly:!0,value:F.schemaNotes})]}),o.jsxs("label",{children:["Примеры few-shot",o.jsx("textarea",{readOnly:!0,value:F.fewShotExamples})]})]}),Zs?o.jsx("p",{className:"error-text",children:Zs}):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:(ee?.stats.runs_total??0)+(q?1:0)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний score"}),o.jsx("strong",{children:na(ee?.stats.avg_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:ee?md(ee.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Блокеры"}),o.jsx("strong",{children:ee?.stats.blocking_runs??0})]})]}),o.jsxs("div",{className:"autoruns-run-list",children:[Er.map(i=>o.jsxs("button",{type:"button",className:Se===i.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{jn(i.run_id)},children:[o.jsxs("div",{className:"autoruns-run-head",children:[o.jsx("strong",{children:gn(i.run_timestamp)}),o.jsx("span",{children:fp(i.eval_target)})]}),o.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[o.jsx("span",{children:i.run_id}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{Pr(c,i.run_id,"run id")},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Pr(c,i.run_id,"run id"))},title:"Скопировать run id","aria-label":`Скопировать run id ${i.run_id}`,children:o.jsx(yd,{})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["режим=",i.mode??"нет данных"," | mock=",String(i.use_mock)]}),o.jsxs("div",{className:"autoruns-run-meta",children:["analysis_date=",i.analysis_date??"current_state"]}),i.llm_provider||i.model?o.jsxs("div",{className:"autoruns-run-meta",children:["llm=",i.llm_provider??"нет данных"," | модель=",i.model??"нет данных"]}):null,o.jsxs("div",{className:"autoruns-run-meta",children:["промпт=",i.prompt_version??"нет данных"]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["оценка: ",na(i.score_index)]}),o.jsxs("span",{children:["закрыто/открыто: ",i.closed_cases,"/",i.open_cases]})]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["блокеры: ",i.blocking_failures]}),o.jsxs("span",{children:["качество: ",i.quality_failures]})]})]},i.run_id)),Er.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:Se,onChange:i=>{const c=i.target.value;jn(c)},children:Er.map(i=>o.jsxs("option",{value:i.run_id,children:[gn(i.run_timestamp)," | ",i.run_id]},i.run_id))})]}),o.jsxs("label",{children:["Кейс",o.jsxs("select",{value:Ve,onChange:i=>{const c=i.target.value;wt(c),Se&&c&&os(Se,c)},children:[(O?.cases.length??0)>0?o.jsx("option",{value:Pt,children:"ВСЕ кейсы подряд"}):null,(O?.cases??[]).map(i=>o.jsxs("option",{value:i.case_id,children:[i.case_id," | ",i.status]},i.case_id))]})]}),o.jsxs("div",{className:"autoruns-dialog-copy-actions",children:[o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Tr("default")},disabled:et||Q||(y?.messages.length??0)===0,title:"Скопировать question-answer диалог текущего прогона",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Tr("technical")},disabled:et||Q||(y?.messages.length??0)===0,title:"Скопировать диалог вместе с debug JSON и метаданными прогона",children:"Скопировать техчат"}),o.jsxs("div",{className:"autoruns-dialog-copy-status",children:[Go==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Wo,")"]}):null,Go==="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:Ve===Pt?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{wt(Pt),Se&&os(Se,Pt)},children:[o.jsx("span",{children:"ВСЕ кейсы подряд"}),o.jsx("span",{children:O?.cases.length})]},Pt):null,(O?.cases??[]).map(i=>o.jsxs("button",{type:"button",className:Ve===i.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{wt(i.case_id),Se&&os(Se,i.case_id)},children:[o.jsx("span",{children:i.case_id}),o.jsxs("span",{children:[i.status,i.commented_count>0?` | комм=${i.commented_count}`:""]})]},i.case_id))]}),o.jsxs("div",{className:"autoruns-dialog-view",children:[et||Q?o.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!et&&!Q&&(y?.messages.length??0)===0?o.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(y?.messages??[]).map((i,c)=>{const f=i.role==="assistant"?"assistant":"user";return o.jsxs("article",{className:`autoruns-msg ${f}`,children:[o.jsxs("header",{children:[o.jsx("strong",{children:f==="assistant"?"Система":"Модель/вопрос"}),o.jsxs("div",{className:"autoruns-msg-head-actions",children:[i.case_id?o.jsx("span",{className:"autoruns-msg-case-tag",children:i.case_id}):null,pd(i)?o.jsx("span",{className:"autoruns-msg-case-tag",children:pd(i)}):null,o.jsx("span",{children:i.created_at?gn(i.created_at):"нет данных"}),f==="assistant"&&!Js(Se)?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:i.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>fa(i),title:"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b","aria-label":"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b",children:o.jsx(pp,{commented:i.commented})}),i.annotation?o.jsx("button",{type:"button",className:i.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{yo(i.annotation,!i.annotation.resolved)},disabled:Fn===i.annotation.annotation_id,title:i.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":i.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(vd,{resolved:i.annotation.resolved})}):null]}):null]})]}),o.jsx("p",{children:i.text}),f==="assistant"&&i.annotation?o.jsxs("div",{className:"autoruns-msg-annotation",children:[o.jsx("strong",{children:Ki(i.annotation.rating)}),o.jsx("span",{children:i.annotation.comment}),o.jsxs("span",{className:"muted",children:[i.annotation.manual_case_decision,i.annotation.annotation_author?` | ${i.annotation.annotation_author}`:""]})]}):null,(i.trace_id||i.reply_type)&&o.jsxs("footer",{children:[i.trace_id?o.jsxs("span",{children:["trace=",i.trace_id]}):null,i.reply_type?o.jsxs("span",{children:["reply_type=",i.reply_type]}):null]})]},i.message_id??`${f}-${c}`)})]})]}),St?o.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:o.jsx(tp,{sessionId:it,conversation:ln,inputValue:eo,onInputChange:xs,selectedContextChip:jr,onSelectContextChip:Ut,onClearContextChip:()=>Ut(null),useMock:to,onUseMockChange:Xt,onSend:io,onClear:ao,onSaveSession:ss,busy:Ko,saveBusy:yt.saving,saveDisabled:!it.trim()||ln.length===0||Ko,statusText:ia,errorMessage:_s,showSaveAction:!0,showCommentAction:!0,onCommentAssistantMessage:ha,isAssistantMessageCommented:ma,canCommentAssistantMessage:rl})}):null,mt?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:na(ee?.stats.latest_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Предыдущий"}),o.jsx("strong",{children:na(ee?.stats.previous_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:ee?md(ee.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Пробелы качества"}),o.jsx("strong",{children:ee?.stats.quality_gap_runs??0})]})]}),o.jsx("h4",{children:"Покрытие доменов (история)"}),hd(ee?.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(tr?.post_analysis.stats.by_queue??{}).map(([i,c])=>o.jsxs("div",{children:[o.jsx("span",{children:i}),o.jsx("strong",{children:c})]},i))}),o.jsxs("div",{className:"autoruns-autogen-list",children:[(tr?.post_analysis.recommended_regression_candidates??[]).slice(0,12).map(i=>o.jsxs("article",{className:"autoruns-autogen-item",children:[o.jsxs("header",{children:[o.jsx("strong",{children:i.manual_case_decision}),o.jsxs("span",{children:[i.rating,"/5"]})]}),o.jsxs("div",{className:"autoruns-run-meta",children:[i.domain??"неизвестно"," / ",i.query_class??"неизвестно"]}),o.jsx("p",{children:i.comment})]},i.annotation_id)),!Dn&&(tr?.post_analysis.recommended_regression_candidates.length??0)===0?o.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Kt?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Комментарии"})}),o.jsx("h4",{children:"Размеченные ответы"}),o.jsxs("div",{className:"autoruns-comment-filter-row",children:[o.jsxs("label",{children:["Фильтр решений",o.jsxs("select",{value:de,onChange:i=>xe(i.target.value),children:[o.jsx("option",{value:"all",children:"все"}),(sn.length>0?sn:Ce?.enum??[]).map(i=>o.jsx("option",{value:i,children:String(Ce?.labels?.[i]??i)},i))]})]}),o.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>je(i=>!i),children:we?"Показать выполненные":"Скрыть выполненные"})]}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Комментариев"}),o.jsx("strong",{children:ut.length})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний рейтинг"}),o.jsx("strong",{children:Es===null?"нет данных":`${Es.toFixed(2)} / 5`})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Последний"}),o.jsx("strong",{children:ut.length>0?gn(ut[0].updated_at):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Статус"}),o.jsx("strong",{children:Xr?"обновляю":"готово"})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Xr,onClick:()=>{ar()},children:Xr?"Обновляю...":"Обновить список"}),o.jsx("button",{type:"button",className:"tab",disabled:Dn,onClick:()=>{wn()},children:Dn?"Идет пост-анализ...":"Обновить пост-анализ"})]}),o.jsxs("div",{className:"autoruns-comments-list",children:[Xr?o.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!Xr&&ut.length===0?o.jsx("p",{className:"muted",children:se.length===0&&wr.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,ut.map(i=>{if(i.source==="assistant_live"){const f=i.assistant;return o.jsxs("article",{className:"autoruns-comment-item",children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Ki(f.rating)}),o.jsx("div",{className:"autoruns-comment-head-actions",children:o.jsx("span",{children:gn(f.updated_at)})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",f.session_id]}),o.jsxs("div",{className:"autoruns-run-meta",children:["msg=",f.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",f.annotation_author?` | author=${f.annotation_author}`:""]}),f.context.question_text?o.jsxs("p",{children:["Q: ",f.context.question_text]}):null,f.context.answer_text?o.jsxs("p",{children:["A: ",f.context.answer_text]}):null,o.jsx("p",{children:f.comment})]},i.key)}const c=i.autorun;return o.jsxs("article",{className:Rn===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{Ar(c)},role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),Ar(c))},children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Ki(c.rating)}),o.jsxs("div",{className:"autoruns-comment-head-actions",children:[o.jsx("span",{children:gn(c.updated_at)}),o.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:f=>{f.preventDefault(),f.stopPropagation(),yo(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:["выполнено",": ",gn(c.resolved_at),c.resolved_by?` | by=${c.resolved_by}`:""]}):null,c.context.question_text?o.jsxs("p",{children:["Q: ",c.context.question_text]}):null,c.context.answer_text?o.jsxs("p",{children:["A: ",c.context.answer_text]}):null,o.jsx("p",{children:c.comment})]},i.key)})]}),Le?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:Le.technical_context.trace_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"reply_type:"}),o.jsx("strong",{children:Le.technical_context.reply_type??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"domain:"}),o.jsx("strong",{children:Le.technical_context.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"query_class:"}),o.jsx("strong",{children:Le.technical_context.query_class??"нет данных"})]})]}),o.jsx("h4",{children:"JSON разбор"}),o.jsx(Nd,{value:{annotation_id:Le.annotation_id,run_id:Le.run_id,case_id:Le.case_id,message_index:Le.message_index,rating:Le.rating,comment:Le.comment,manual_case_decision:Le.manual_case_decision,annotation_author:Le.annotation_author,resolved:Le.resolved,resolved_at:Le.resolved_at,resolved_by:Le.resolved_by,context:Le.context,technical_context:Le.technical_context,case_summary:Le.case_summary?{case_id:Le.case_summary.case_id,domain:Le.case_summary.domain,query_class:Le.case_summary.query_class,checks:Le.case_summary.checks,metric_subscores:Le.case_summary.metric_subscores}:null}})]}):null]}):null]}),yt.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&rs()},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:i=>jt(c=>({...c,title:i.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:()=>{Ps()},disabled:yt.saving,children:yt.saving?"Сохраняю...":"Сохранить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>rs(),disabled:yt.saving,children:"Отмена"})]})]})}):null,en.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&ct()},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:en.questionText}),en.error?o.jsx("p",{className:"error-text",children:en.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{va()},disabled:en.saving,children:en.saving?"Удаляю...":"Да"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>ct(),disabled:en.saving,children:"Нет"})]})]})}):null,Lt.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&Sn()},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:Lt.title}),Lt.error?o.jsx("p",{className:"error-text",children:Lt.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{xa()},disabled:Lt.saving,children:Lt.saving?"Удаляю...":"Да"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Sn(),disabled:Lt.saving,children:"Нет"})]})]})}):null,he.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&_n()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),lo?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:lo.text})]}):null,Ns?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:Ns.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа ассистента",children:[1,2,3,4,5].map(i=>o.jsx("button",{type:"button",className:he.rating>=i?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>It(c=>({...c,rating:i})),disabled:he.saving,"aria-label":`Оценка ${i}`,children:he.rating>=i?"●":"○"},i))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:he.annotationAuthor,onChange:i=>It(c=>({...c,annotationAuthor:i.target.value})),placeholder:"manual_reviewer",disabled:he.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:he.comment,onChange:i=>It(c=>({...c,comment:i.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:he.saving})]}),he.error?o.jsx("p",{className:"error-text",children:he.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ga()},disabled:he.saving,children:he.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>_n(),disabled:he.saving,children:"Отмена"})]})]})}):null,ce.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&Rs()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу системы"}),o.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),Yo?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:oo?.text??"Вопрос в диалоге не найден."})]}),o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ системы"}),o.jsx("p",{className:"autoruns-comment-quote",children:Yo.text})]})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(i=>o.jsx("button",{type:"button",className:ce.rating>=i?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>ot(c=>({...c,rating:i})),disabled:ce.saving,"aria-label":`Оценка ${i}`,children:ce.rating>=i?"●":"○"},i))}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Решение по кейсу",o.jsx("select",{value:ce.manualCaseDecision,onChange:i=>ot(c=>({...c,manualCaseDecision:i.target.value})),disabled:ce.saving,children:(sn.length>0?sn:Ce?.enum??[ea]).map(i=>o.jsx("option",{value:i,children:String(Ce?.labels?.[i]??i)},i))})]}),o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ce.annotationAuthor,onChange:i=>ot(c=>({...c,annotationAuthor:i.target.value})),placeholder:"manual_reviewer",disabled:ce.saving})]})]}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ce.comment,onChange:i=>ot(c=>({...c,comment:i.target.value})),placeholder:"Почему ответ бракованный, что именно пошло не так, какие технические детали проверить.",rows:4,disabled:ce.saving})]}),ce.error?o.jsx("p",{className:"error-text",children:ce.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{pa()},disabled:ce.saving,children:ce.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Rs(),disabled:ce.saving,children:"Отмена"})]})]})}):null]})}const yp={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."},xp={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},Ji={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",_p="ndc-autoruns-save",Sp="autoruns",Yi="normalizer_v2_0_2",wp="address_query_runtime_v1",jp=["normalized","fragments","scope","flags","route","raw","validation","logs"];function kp(a){return`[${new Date().toLocaleTimeString("ru-RU")}] ${a}`}function Cp(a,m){if(!m)return"Previous preset is not selected.";const S=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(C=>a[C]!==m[C]).map(C=>`${C}: ${Math.abs(a[C].length-m[C].length)} chars delta`);return S.length===0?"No changes against previous preset.":`Changed fields: ${S.length}. ${S.join(" | ")}`}function Np(){const[a,m]=g.useState(yp),[p,S]=g.useState(Sd),[C,M]=g.useState(xp),[z,ae]=g.useState(null),[ne,F]=g.useState([]),[X,Z]=g.useState([]),[te,Me]=g.useState("normalized"),[pe,me]=g.useState(!1),[ye,Qe]=g.useState(!1),[Xe,He]=g.useState([]),[Ae,b]=g.useState(""),[le,Ee]=g.useState([]),[be,St]=g.useState(""),[mt,Kt]=g.useState("NDC custom preset"),[ht,B]=g.useState(null),[Ie,Je]=g.useState(""),[re,ee]=g.useState(!1),[I,O]=g.useState([]),[L,y]=g.useState(""),[k,se]=g.useState([]),[ue,de]=g.useState(!1),[xe,we]=g.useState(null),[je,Ce]=g.useState(""),[gt,sn]=g.useState(Sp),[yr,Rn]=g.useState(!0),[vn,Se]=g.useState(!0),[Jt,Ve]=g.useState(!0),[wt,Tt]=g.useState(!0),[yn,W]=g.useState(!0),[vt,xr]=g.useState(!0),[Mn,Ge]=g.useState(!0),[Rt,zt]=g.useState(!0),[An,ve]=g.useState(!0),[Mt,Ze]=g.useState(!0),[ys,st]=g.useState(!0),[er,_r]=g.useState(!0),[on,In]=g.useState(!0),Ft=g.useRef(!1),xn=g.useRef(!1),Yt=g.useRef(!1);g.useEffect(()=>{const E=document.documentElement,{colors:Y}=Ji;E.style.setProperty("--rgb-background",Y.backgroundRgb),E.style.setProperty("--rgb-surface-main",Y.mainSurfaceRgb),E.style.setProperty("--rgb-surface-horizontal",Y.horizontalSurfaceRgb),E.style.setProperty("--rgb-surface-focus",Y.focusSurfaceRgb),E.style.setProperty("--rgb-assistant-chip",Y.assistantChipRgb),E.style.setProperty("--rgb-assistant-chip-hover",Y.assistantChipHoverRgb),E.style.setProperty("--rgb-assistant-chip-selected",Y.assistantChipSelectedRgb),E.style.setProperty("--rgb-assistant-chip-selected-text",Y.assistantChipSelectedTextRgb),E.style.setProperty("--rgb-active",Y.activeRgb),E.style.setProperty("--rgb-active-text",Y.activeTextRgb),E.style.setProperty("--rgb-text-main",Y.textMainRgb),E.style.setProperty("--rgb-text-muted",Y.textMutedRgb),E.style.setProperty("--rgb-danger",Y.dangerRgb),E.style.setProperty("--rgb-scrollbar-track",Y.scrollbarTrackRgb),E.style.setProperty("--rgb-scrollbar-thumb",Y.scrollbarThumbRgb),E.style.setProperty("--rgb-scrollbar-thumb-hover",Y.scrollbarThumbHoverRgb),E.style.setProperty("--mode-column-width",`${Ji.layout.modeColumnWidthPx}px`),E.style.setProperty("--mode-toggle-width",`${Ji.layout.modeToggleWidthPx}px`)},[]);const q=E=>{Z(Y=>[kp(E),...Y].slice(0,300))};g.useEffect(()=>{(async()=>{const Q=localStorage.getItem(wd);if(Q)try{const Pe=JSON.parse(Q);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})),q(`Shared local LLM config loaded: ${Pe.connection.model}`))}catch(Pe){q(`Shared local config load error: ${Pe instanceof Error?Pe.message:String(Pe)}`)}finally{Yt.current=!0}})();const Y=localStorage.getItem(jd);if(Y)try{const Q=JSON.parse(Y);(Q.uiMode==="assistant"||Q.uiMode==="autoruns"||Q.uiMode==="decomposition")&&sn("autoruns"),Q.activeTab&&jp.includes(Q.activeTab)&&Me(Q.activeTab),typeof Q.showAutorunsSettingsMode=="boolean"&&Rn(Q.showAutorunsSettingsMode),typeof Q.showAutorunsAutoRunsMode=="boolean"&&Se(Q.showAutorunsAutoRunsMode),typeof Q.showAutorunsAssistantMode=="boolean"&&Ve(Q.showAutorunsAssistantMode),typeof Q.showAutorunsDecompositionMode=="boolean"&&Tt(Q.showAutorunsDecompositionMode),typeof Q.showAutorunsProgressMode=="boolean"&&W(Q.showAutorunsProgressMode),typeof Q.showAutorunsCommentsMode=="boolean"&&xr(Q.showAutorunsCommentsMode),typeof Q.showDecompositionConnectionMode=="boolean"&&Ge(Q.showDecompositionConnectionMode),typeof Q.showDecompositionPromptMode=="boolean"&&zt(Q.showDecompositionPromptMode),typeof Q.showDecompositionQueryMode=="boolean"&&ve(Q.showDecompositionQueryMode),typeof Q.showDecompositionOutputMode=="boolean"&&Ze(Q.showDecompositionOutputMode),typeof Q.showDecompositionMetricsMode=="boolean"&&st(Q.showDecompositionMetricsMode),typeof Q.showDecompositionHistoryMode=="boolean"&&_r(Q.showDecompositionHistoryMode),typeof Q.showDecompositionRuntimeMode=="boolean"&&In(Q.showDecompositionRuntimeMode),Q.prompts&&(S(Pe=>({...Pe,...Q.prompts})),xn.current=!0)}catch{}At(),tr(),Kr()},[]),g.useEffect(()=>{if(!Yt.current||a.llmProvider!=="local")return;const E=window.setTimeout(()=>{Te.saveSharedConnectionConfig(a).catch(Y=>q(`Shared local config sync error: ${Y instanceof Error?Y.message:String(Y)}`))},250);return()=>window.clearTimeout(E)},[a.baseUrl,a.llmProvider,a.maxOutputTokens,a.model,a.temperature]);async function At(){try{const E=await Te.loadHistory();F(E.items??[])}catch(E){q(`History load error: ${E instanceof Error?E.message:String(E)}`)}}async function tr(){try{const Y=(await Te.loadPresets()).presets??[];if(Ee(Y),xn.current){Ft.current=!0;return}if(Ft.current)return;const Q=Y.find(Pe=>Pe.prompt_version===Yi)??Y.find(Pe=>Pe.id==="default-normalizer-v2_0_2");if(!Q){Ft.current=!0,q(`Preset autoload skipped: ${Yi} not found.`);return}St(Q.id),B(p),S({systemPrompt:Q.systemPrompt,developerPrompt:Q.developerPrompt,domainPrompt:Q.domainPrompt,schemaNotes:Q.schemaNotes??"",fewShotExamples:Q.fewShotExamples??""}),Ft.current=!0,q(`Preset autoloaded: ${Q.name} (${Q.prompt_version}).`)}catch(E){q(`Presets load error: ${E instanceof Error?E.message:String(E)}`)}}async function Kr(){try{const E=await Te.listRuns();O(E.items??[])}catch(E){q(`Runs load error: ${E instanceof Error?E.message:String(E)}`)}}function Jr(){if(localStorage.setItem(wd,JSON.stringify({model:a.model,llmProvider:a.llmProvider,baseUrl:a.baseUrl,temperature:a.temperature,maxOutputTokens:a.maxOutputTokens})),a.llmProvider==="local"){Te.saveSharedConnectionConfig(a).then(()=>{q("Local config saved and synced to shared agent config (without API key).")}).catch(E=>{q(`Local config saved, but shared sync failed: ${E instanceof Error?E.message:String(E)}`)});return}q("Local config saved (without API key).")}function Yr(){localStorage.setItem(jd,JSON.stringify({uiMode:gt,activeTab:te,showAutorunsSettingsMode:yr,showAutorunsAutoRunsMode:vn,showAutorunsAssistantMode:Jt,showAutorunsDecompositionMode:wt,showAutorunsProgressMode:yn,showAutorunsCommentsMode:vt,showDecompositionConnectionMode:Mn,showDecompositionPromptMode:Rt,showDecompositionQueryMode:An,showDecompositionOutputMode:Mt,showDecompositionMetricsMode:ys,showDecompositionHistoryMode:er,showDecompositionRuntimeMode:on,prompts:p})),window.dispatchEvent(new CustomEvent(_p)),q("UI layout and prompts saved.")}async function Ln(){me(!0),Ce("");try{const E=await Te.testConnection(a);E.provider==="local"?E.model_found===!0?(b(`LOCAL OK - ${E.model}`),q(`Local model is available: ${E.model} (catalog size=${E.models_count??"n/a"}).`)):E.model_found===!1?(b(`LOCAL OK, model not loaded - ${E.model}`),q(`Local server is reachable, but model '${E.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(b(`LOCAL OK (model list unavailable) - ${E.model}`),q("Local server is reachable, but model catalog could not be verified.")):(b(`OPENAI OK - ${E.model}`),q(`OpenAI connection ok: ${E.model}`))}catch(E){const Y=E instanceof Error?E.message:String(E);b("Connection error"),Ce(`Test connection: ${Y}`),q(`Test connection error: ${Y}`)}finally{me(!1)}}async function bt(){Qe(!0);try{const Y=(await Te.listModels(a)).models??[];He(Y),Y.length>0&&m(Q=>Q.model&&Y.includes(Q.model)?Q:{...Q,model:Y[0]}),q(`Model catalog loaded (${a.llmProvider}): ${Y.length} items.`)}catch(E){const Y=E instanceof Error?E.message:String(E);q(`Load model list error: ${Y}`)}finally{Qe(!1)}}g.useEffect(()=>{He([])},[a.llmProvider,a.baseUrl]);function Dn(){const E=le.find(Y=>Y.id===be);if(!E){q("Preset is not selected.");return}B(p),S({systemPrompt:E.systemPrompt,developerPrompt:E.developerPrompt,domainPrompt:E.domainPrompt,schemaNotes:E.schemaNotes??"",fewShotExamples:E.fewShotExamples??""}),q(`Preset loaded: ${E.name}`)}async function On(){try{await Te.savePreset({name:mt||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:p.systemPrompt,developerPrompt:p.developerPrompt,domainPrompt:p.domainPrompt,schemaNotes:p.schemaNotes,fewShotExamples:p.fewShotExamples}),q("Preset saved."),await tr()}catch(E){q(`Preset save error: ${E instanceof Error?E.message:String(E)}`)}}function $n(){S(Sd),q("Prompt panel reset to defaults.")}function zn(){const E=Cp(p,ht);Je(E),q(E)}return g.useEffect(()=>{if(!L){se([]);return}Te.runTrace(L).then(E=>se(E.items)).catch(E=>q(`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:()=>sn("autoruns"),children:"Управление ассистентом"}),o.jsx("button",{type:"button",className:"tab",onClick:Yr,children:"Сохранить"})]}),o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:yr?"tab active":"tab",onClick:()=>Rn(E=>!E),children:"Настройки"}),o.jsx("button",{type:"button",className:vn?"tab active":"tab",onClick:()=>Se(E=>!E),children:"Автопрогоны"}),o.jsx("button",{type:"button",className:Jt?"tab active":"tab",onClick:()=>Ve(E=>!E),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:yn?"tab active":"tab",onClick:()=>W(E=>!E),children:"Прогресс/регресс"}),o.jsx("button",{type:"button",className:vt?"tab active":"tab",onClick:()=>xr(E=>!E),children:"Комментарии"})]})]}),o.jsx("div",{className:"layout-grid layout-grid-autoruns",children:o.jsx(vp,{connection:a,modelOptions:Xe,modelsBusy:ye,connectionStatus:Ae,connectionBusy:pe,onConnectionChange:m,onReloadModels:bt,onSaveLocalConfig:Jr,onTestConnection:Ln,prompts:p,onPromptsChange:S,promptPresets:le,selectedPresetId:be,onSelectPreset:St,onLoadPreset:Dn,onSavePreset:On,onResetDefaults:$n,onDiffPrevious:zn,presetName:mt,onPresetNameChange:Kt,diffSummary:Ie,assistantPromptVersion:wp,decompositionPromptVersion:Yi,showSettingsMode:yr,showAutoRunsMode:vn,showAssistantMode:Jt,showProgressMode:yn,showCommentsMode:vt,onLog:q})})]})}Df.createRoot(document.getElementById("root")).render(o.jsx(Pf.StrictMode,{children:o.jsx(Np,{})}));