(function(){const p=document.createElement("link").relList;if(p&&p.supports&&p.supports("modulepreload"))return;for(const j of document.querySelectorAll('link[rel="modulepreload"]'))R(j);new MutationObserver(j=>{for(const T of j)if(T.type==="childList")for(const $ of T.addedNodes)$.tagName==="LINK"&&$.rel==="modulepreload"&&R($)}).observe(document,{childList:!0,subtree:!0});function m(j){const T={};return j.integrity&&(T.integrity=j.integrity),j.referrerPolicy&&(T.referrerPolicy=j.referrerPolicy),j.crossOrigin==="use-credentials"?T.credentials="include":j.crossOrigin==="anonymous"?T.credentials="omit":T.credentials="same-origin",T}function R(j){if(j.ep)return;j.ep=!0;const T=m(j);fetch(j.href,T)}})();function Oc(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Oi={exports:{}},to={},$i={exports:{}},he={};var mc;function yf(){if(mc)return he;mc=1;var i=Symbol.for("react.element"),p=Symbol.for("react.portal"),m=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),j=Symbol.for("react.profiler"),T=Symbol.for("react.provider"),$=Symbol.for("react.context"),Y=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),I=Symbol.for("react.memo"),W=Symbol.for("react.lazy"),z=Symbol.iterator;function U(h){return h===null||typeof h!="object"?null:(h=z&&h[z]||h["@@iterator"],typeof h=="function"?h:null)}var oe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Me=Object.assign,te={};function se(h,C,G){this.props=h,this.context=C,this.refs=te,this.updater=G||oe}se.prototype.isReactComponent={},se.prototype.setState=function(h,C){if(typeof h!="object"&&typeof h!="function"&&h!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,h,C,"setState")},se.prototype.forceUpdate=function(h){this.updater.enqueueForceUpdate(this,h,"forceUpdate")};function q(){}q.prototype=se.prototype;function re(h,C,G){this.props=h,this.context=C,this.refs=te,this.updater=G||oe}var Se=re.prototype=new q;Se.constructor=re,Me(Se,se.prototype),Se.isPureReactComponent=!0;var Pe=Array.isArray,Ae=Object.prototype.hasOwnProperty,De={current:null},$e={key:!0,ref:!0,__self:!0,__source:!0};function We(h,C,G){var ae,ce={},de=null,xe=null;if(C!=null)for(ae in C.ref!==void 0&&(xe=C.ref),C.key!==void 0&&(de=""+C.key),C)Ae.call(C,ae)&&!$e.hasOwnProperty(ae)&&(ce[ae]=C[ae]);var ge=arguments.length-2;if(ge===1)ce.children=G;else if(1>>1,C=D[h];if(0>>1;hj(ce,O))dej(xe,ce)?(D[h]=xe,D[de]=O,h=de):(D[h]=ce,D[ae]=O,h=ae);else if(dej(xe,O))D[h]=xe,D[de]=O,h=de;else break e}}return Q}function j(D,Q){var O=D.sortIndex-Q.sortIndex;return O!==0?O:D.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var T=performance;i.unstable_now=function(){return T.now()}}else{var $=Date,Y=$.now();i.unstable_now=function(){return $.now()-Y}}var F=[],I=[],W=1,z=null,U=3,oe=!1,Me=!1,te=!1,se=typeof setTimeout=="function"?setTimeout:null,q=typeof clearTimeout=="function"?clearTimeout:null,re=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function Se(D){for(var Q=m(I);Q!==null;){if(Q.callback===null)R(I);else if(Q.startTime<=D)R(I),Q.sortIndex=Q.expirationTime,p(F,Q);else break;Q=m(I)}}function Pe(D){if(te=!1,Se(D),!Me)if(m(F)!==null)Me=!0,Re(Ae);else{var Q=m(I);Q!==null&&me(Pe,Q.startTime-D)}}function Ae(D,Q){Me=!1,te&&(te=!1,q(We),We=-1),oe=!0;var O=U;try{for(Se(Q),z=m(F);z!==null&&(!(z.expirationTime>Q)||D&&!rt());){var h=z.callback;if(typeof h=="function"){z.callback=null,U=z.priorityLevel;var C=h(z.expirationTime<=Q);Q=i.unstable_now(),typeof C=="function"?z.callback=C:z===m(F)&&R(F),Se(Q)}else R(F);z=m(F)}if(z!==null)var G=!0;else{var ae=m(I);ae!==null&&me(Pe,ae.startTime-Q),G=!1}return G}finally{z=null,U=O,oe=!1}}var De=!1,$e=null,We=-1,Ge=5,Ze=-1;function rt(){return!(i.unstable_now()-ZeD||125h?(D.sortIndex=O,p(I,D),m(F)===null&&D===m(I)&&(te?(q(We),We=-1):te=!0,me(Pe,O-h))):(D.sortIndex=C,p(F,D),Me||oe||(Me=!0,Re(Ae))),D},i.unstable_shouldYield=rt,i.unstable_wrapCallback=function(D){var Q=U;return function(){var O=U;U=Q;try{return D.apply(this,arguments)}finally{U=O}}}})(Bi)),Bi}var yc;function jf(){return yc||(yc=1,Ui.exports=wf()),Ui.exports}var xc;function kf(){if(xc)return $t;xc=1;var i=Yi(),p=jf();function m(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),F=Object.prototype.hasOwnProperty,I=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,W={},z={};function U(e){return F.call(z,e)?!0:F.call(W,e)?!1:I.test(e)?z[e]=!0:(W[e]=!0,!1)}function oe(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Me(e,t,n,r){if(t===null||typeof t>"u"||oe(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function te(e,t,n,r,s,l,u){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=u}var se={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){se[e]=new te(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];se[t]=new te(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){se[e]=new te(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){se[e]=new te(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){se[e]=new te(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){se[e]=new te(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){se[e]=new te(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){se[e]=new te(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){se[e]=new te(e,5,!1,e.toLowerCase(),null,!1,!1)});var q=/[\-:]([a-z])/g;function re(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(q,re);se[t]=new te(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(q,re);se[t]=new te(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(q,re);se[t]=new te(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){se[e]=new te(e,1,!1,e.toLowerCase(),null,!1,!1)}),se.xlinkHref=new te("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){se[e]=new te(e,1,!1,e.toLowerCase(),null,!0,!0)});function Se(e,t,n,r){var s=se.hasOwnProperty(t)?se[t]:null;(s!==null?s.type!==0:r||!(2f||s[u]!==l[f]){var g=` `+s[u].replace(" at new "," at ");return e.displayName&&g.includes("")&&(g=g.replace("",e.displayName)),g}while(1<=u&&0<=f);break}}}finally{G=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?C(e):""}function ce(e){switch(e.tag){case 5:return C(e.type);case 16:return C("Lazy");case 13:return C("Suspense");case 19:return C("SuspenseList");case 0:case 2:case 15:return e=ae(e.type,!1),e;case 11:return e=ae(e.type.render,!1),e;case 1:return e=ae(e.type,!0),e;default:return""}}function de(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case $e:return"Fragment";case De:return"Portal";case Ge:return"Profiler";case We:return"StrictMode";case Te:return"Suspense";case Fe:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case rt:return(e.displayName||"Context")+".Consumer";case Ze:return(e._context.displayName||"Context")+".Provider";case ie:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case fe:return t=e.displayName||null,t!==null?t:de(e.type)||"Memo";case Re:t=e._payload,e=e._init;try{return de(e(t))}catch{}}return null}function xe(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return de(t);case 8:return t===We?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ge(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ee(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ke(e){var t=ee(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,l=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(u){r=""+u,l.call(this,u)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(u){r=""+u},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ft(e){e._valueTracker||(e._valueTracker=ke(e))}function qn(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ee(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function An(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Tn(e,t){var n=t.checked;return O({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function dr(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ge(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Jt(e,t){t=t.checked,t!=null&&Se(e,"checked",t,!1)}function Yt(e,t){Jt(e,t);var n=ge(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?mn(e,t.type,n):t.hasOwnProperty("defaultValue")&&mn(e,t.type,ge(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Gn(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function mn(e,t,n){(t!=="number"||An(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Ut=Array.isArray;function Xt(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=en.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Bt(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var hn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Be=["Webkit","ms","Moz","O"];Object.keys(hn).forEach(function(e){Be.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),hn[t]=hn[e]})});function st(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||hn.hasOwnProperty(e)&&hn[e]?(""+t).trim():t+"px"}function gn(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=st(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var vn=O({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function tn(e,t){if(t){if(vn[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(m(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(m(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(m(61))}if(t.style!=null&&typeof t.style!="object")throw Error(m(62))}}function nn(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ct=null;function Dn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var rn=null,bt=null,vt=null;function Jn(e){if(e=Us(e)){if(typeof rn!="function")throw Error(m(280));var t=e.stateNode;t&&(t=yo(t),rn(e.stateNode,e.type,t))}}function Ke(e){bt?vt?vt.push(e):vt=[e]:bt=e}function hr(){if(bt){var e=bt,t=vt;if(vt=bt=null,Jn(e),t)for(e=0;e>>=0,e===0?32:31-(Cs(e)/Zr|0)|0}var Xn=64,Bn=4194304;function At(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function wt(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,l=e.pingedLanes,u=n&268435455;if(u!==0){var f=u&~s;f!==0?r=At(f):(l&=u,l!==0&&(r=At(l)))}else u=n&~s,u!==0?r=At(u):l!==0&&(r=At(l));if(r===0)return 0;if(t!==0&&t!==r&&(t&s)===0&&(s=r&-r,l=t&-t,s>=l||s===16&&(l&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ht(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-St(t),e[t]=n}function Vt(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=As),la=" ",ia=!1;function aa(e,t){switch(e){case"keyup":return fd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ua(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var rs=!1;function pd(e,t){switch(e){case"compositionend":return ua(t);case"keypress":return t.which!==32?null:(ia=!0,la);case"textInput":return e=t.data,e===la&&ia?null:e;default:return null}}function hd(e,t){if(rs)return e==="compositionend"||!vl&&aa(e,t)?(e=ea(),lo=dl=Sr=null,rs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=ga(n)}}function ya(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ya(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xa(){for(var e=window,t=An();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=An(e.document)}return t}function _l(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function kd(e){var t=xa(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ya(n.ownerDocument.documentElement,n)){if(r!==null&&_l(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,l=Math.min(r.start,s);r=r.end===void 0?l:Math.min(r.end,s),!e.extend&&l>r&&(s=r,r=l,l=s),s=va(n,l);var u=va(n,r);s&&u&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),l>r?(e.addRange(t),e.extend(u.node,u.offset)):(t.setEnd(u.node,u.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ss=null,Sl=null,Ds=null,wl=!1;function _a(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;wl||ss==null||ss!==An(r)||(r=ss,"selectionStart"in r&&_l(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ds&&Ls(Ds,r)||(Ds=r,r=ho(Sl,"onSelect"),0us||(e.current=Ll[us],Ll[us]=null,us--)}function Le(e,t){us++,Ll[us]=e.current,e.current=t}var Cr={},ft=kr(Cr),It=kr(!1),Fr=Cr;function cs(e,t){var n=e.type.contextTypes;if(!n)return Cr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},l;for(l in n)s[l]=t[l];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Lt(e){return e=e.childContextTypes,e!=null}function xo(){Oe(It),Oe(ft)}function Da(e,t,n){if(ft.current!==Cr)throw Error(m(168));Le(ft,t),Le(It,n)}function za(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(m(108,xe(e)||"Unknown",s));return O({},n,r)}function _o(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cr,Fr=ft.current,Le(ft,e),Le(It,It.current),!0}function Oa(e,t,n){var r=e.stateNode;if(!r)throw Error(m(169));n?(e=za(e,t,Fr),r.__reactInternalMemoizedMergedChildContext=e,Oe(It),Oe(ft),Le(ft,e)):Oe(It),Le(It,n)}var nr=null,So=!1,Dl=!1;function $a(e){nr===null?nr=[e]:nr.push(e)}function zd(e){So=!0,$a(e)}function Nr(){if(!Dl&&nr!==null){Dl=!0;var e=0,t=d;try{var n=nr;for(d=1;e>=u,s-=u,rr=1<<32-St(t)+s|n<ne?(nt=Z,Z=null):nt=Z.sibling;var je=N(_,Z,S[ne],L);if(je===null){Z===null&&(Z=nt);break}e&&Z&&je.alternate===null&&t(_,Z),v=l(je,v,ne),X===null?K=je:X.sibling=je,X=je,Z=nt}if(ne===S.length)return n(_,Z),Ue&&Br(_,ne),K;if(Z===null){for(;nene?(nt=Z,Z=null):nt=Z.sibling;var Dr=N(_,Z,je.value,L);if(Dr===null){Z===null&&(Z=nt);break}e&&Z&&Dr.alternate===null&&t(_,Z),v=l(Dr,v,ne),X===null?K=Dr:X.sibling=Dr,X=Dr,Z=nt}if(je.done)return n(_,Z),Ue&&Br(_,ne),K;if(Z===null){for(;!je.done;ne++,je=S.next())je=M(_,je.value,L),je!==null&&(v=l(je,v,ne),X===null?K=je:X.sibling=je,X=je);return Ue&&Br(_,ne),K}for(Z=r(_,Z);!je.done;ne++,je=S.next())je=B(Z,_,ne,je.value,L),je!==null&&(e&&je.alternate!==null&&Z.delete(je.key===null?ne:je.key),v=l(je,v,ne),X===null?K=je:X.sibling=je,X=je);return e&&Z.forEach(function(vf){return t(_,vf)}),Ue&&Br(_,ne),K}function qe(_,v,S,L){if(typeof S=="object"&&S!==null&&S.type===$e&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case Ae:e:{for(var K=S.key,X=v;X!==null;){if(X.key===K){if(K=S.type,K===$e){if(X.tag===7){n(_,X.sibling),v=s(X,S.props.children),v.return=_,_=v;break e}}else if(X.elementType===K||typeof K=="object"&&K!==null&&K.$$typeof===Re&&Va(K)===X.type){n(_,X.sibling),v=s(X,S.props),v.ref=Bs(_,X,S),v.return=_,_=v;break e}n(_,X);break}else t(_,X);X=X.sibling}S.type===$e?(v=Gr(S.props.children,_.mode,L,S.key),v.return=_,_=v):(L=Go(S.type,S.key,S.props,null,_.mode,L),L.ref=Bs(_,v,S),L.return=_,_=L)}return u(_);case De:e:{for(X=S.key;v!==null;){if(v.key===X)if(v.tag===4&&v.stateNode.containerInfo===S.containerInfo&&v.stateNode.implementation===S.implementation){n(_,v.sibling),v=s(v,S.children||[]),v.return=_,_=v;break e}else{n(_,v);break}else t(_,v);v=v.sibling}v=Ti(S,_.mode,L),v.return=_,_=v}return u(_);case Re:return X=S._init,qe(_,v,X(S._payload),L)}if(Ut(S))return H(_,v,S,L);if(Q(S))return V(_,v,S,L);Co(_,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,v!==null&&v.tag===6?(n(_,v.sibling),v=s(v,S),v.return=_,_=v):(n(_,v),v=Ai(S,_.mode,L),v.return=_,_=v),u(_)):n(_,v)}return qe}var ps=Qa(!0),Wa=Qa(!1),No=kr(null),Eo=null,hs=null,Bl=null;function bl(){Bl=hs=Eo=null}function Hl(e){var t=No.current;Oe(No),e._currentValue=t}function Vl(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function gs(e,t){Eo=e,Bl=hs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Dt=!0),e.firstContext=null)}function un(e){var t=e._currentValue;if(Bl!==e)if(e={context:e,memoizedValue:t,next:null},hs===null){if(Eo===null)throw Error(m(308));hs=e,Eo.dependencies={lanes:0,firstContext:e}}else hs=hs.next=e;return t}var br=null;function Ql(e){br===null?br=[e]:br.push(e)}function Ka(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Ql(t)):(n.next=s.next,s.next=n),t.interleaved=n,or(e,r)}function or(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Er=!1;function Wl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function qa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function lr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Pr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(_e&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,or(e,n)}return s=r.interleaved,s===null?(t.next=t,Ql(r)):(t.next=s.next,s.next=t),r.interleaved=t,or(e,n)}function Po(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zn(e,n)}}function Ga(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,l=null;if(n=n.firstBaseUpdate,n!==null){do{var u={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};l===null?s=l=u:l=l.next=u,n=n.next}while(n!==null);l===null?s=l=t:l=l.next=t}else s=l=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:l,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ro(e,t,n,r){var s=e.updateQueue;Er=!1;var l=s.firstBaseUpdate,u=s.lastBaseUpdate,f=s.shared.pending;if(f!==null){s.shared.pending=null;var g=f,w=g.next;g.next=null,u===null?l=w:u.next=w,u=g;var E=e.alternate;E!==null&&(E=E.updateQueue,f=E.lastBaseUpdate,f!==u&&(f===null?E.firstBaseUpdate=w:f.next=w,E.lastBaseUpdate=g))}if(l!==null){var M=s.baseState;u=0,E=w=g=null,f=l;do{var N=f.lane,B=f.eventTime;if((r&N)===N){E!==null&&(E=E.next={eventTime:B,lane:0,tag:f.tag,payload:f.payload,callback:f.callback,next:null});e:{var H=e,V=f;switch(N=t,B=n,V.tag){case 1:if(H=V.payload,typeof H=="function"){M=H.call(B,M,N);break e}M=H;break e;case 3:H.flags=H.flags&-65537|128;case 0:if(H=V.payload,N=typeof H=="function"?H.call(B,M,N):H,N==null)break e;M=O({},M,N);break e;case 2:Er=!0}}f.callback!==null&&f.lane!==0&&(e.flags|=64,N=s.effects,N===null?s.effects=[f]:N.push(f))}else B={eventTime:B,lane:N,tag:f.tag,payload:f.payload,callback:f.callback,next:null},E===null?(w=E=B,g=M):E=E.next=B,u|=N;if(f=f.next,f===null){if(f=s.shared.pending,f===null)break;N=f,f=N.next,N.next=null,s.lastBaseUpdate=N,s.shared.pending=null}}while(!0);if(E===null&&(g=M),s.baseState=g,s.firstBaseUpdate=w,s.lastBaseUpdate=E,t=s.shared.interleaved,t!==null){s=t;do u|=s.lane,s=s.next;while(s!==t)}else l===null&&(s.shared.lanes=0);Qr|=u,e.lanes=u,e.memoizedState=M}}function Ja(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Yl.transition;Yl.transition={};try{e(!1),t()}finally{d=n,Yl.transition=r}}function hu(){return cn().memoizedState}function Ud(e,t,n){var r=Tr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},gu(e))vu(t,n);else if(n=Ka(e,t,n,r),n!==null){var s=kt();Rn(n,e,r,s),yu(n,t,r)}}function Bd(e,t,n){var r=Tr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(gu(e))vu(t,s);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var u=t.lastRenderedState,f=l(u,n);if(s.hasEagerState=!0,s.eagerState=f,kn(f,u)){var g=t.interleaved;g===null?(s.next=s,Ql(t)):(s.next=g.next,g.next=s),t.interleaved=s;return}}catch{}n=Ka(e,t,s,r),n!==null&&(s=kt(),Rn(n,e,r,s),yu(n,t,r))}}function gu(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function vu(e,t){Qs=To=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function yu(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zn(e,n)}}var Do={readContext:un,useCallback:mt,useContext:mt,useEffect:mt,useImperativeHandle:mt,useInsertionEffect:mt,useLayoutEffect:mt,useMemo:mt,useReducer:mt,useRef:mt,useState:mt,useDebugValue:mt,useDeferredValue:mt,useTransition:mt,useMutableSource:mt,useSyncExternalStore:mt,useId:mt,unstable_isNewReconciler:!1},bd={readContext:un,useCallback:function(e,t){return Wn().memoizedState=[e,t===void 0?null:t],e},useContext:un,useEffect:iu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Io(4194308,4,cu.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Io(4194308,4,e,t)},useInsertionEffect:function(e,t){return Io(4,2,e,t)},useMemo:function(e,t){var n=Wn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Wn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Ud.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=Wn();return e={current:e},t.memoizedState=e},useState:ou,useDebugValue:si,useDeferredValue:function(e){return Wn().memoizedState=e},useTransition:function(){var e=ou(!1),t=e[0];return e=Fd.bind(null,e[1]),Wn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,s=Wn();if(Ue){if(n===void 0)throw Error(m(407));n=n()}else{if(n=t(),tt===null)throw Error(m(349));(Vr&30)!==0||eu(r,t,n)}s.memoizedState=n;var l={value:n,getSnapshot:t};return s.queue=l,iu(nu.bind(null,r,l,e),[e]),r.flags|=2048,qs(9,tu.bind(null,r,l,n,t),void 0,null),n},useId:function(){var e=Wn(),t=tt.identifierPrefix;if(Ue){var n=sr,r=rr;n=(r&~(1<<32-St(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ws++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=u.createElement(n,{is:r.is}):(e=u.createElement(n),n==="select"&&(u=e,r.multiple?u.multiple=!0:r.size&&(u.size=r.size))):e=u.createElementNS(e,n),e[Vn]=t,e[Fs]=r,$u(e,t,!1,!1),t.stateNode=e;e:{switch(u=nn(n,r),n){case"dialog":ze("cancel",e),ze("close",e),s=r;break;case"iframe":case"object":case"embed":ze("load",e),s=r;break;case"video":case"audio":for(s=0;sSs&&(t.flags|=128,r=!0,Gs(l,!1),t.lanes=4194304)}else{if(!r)if(e=Mo(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Gs(l,!0),l.tail===null&&l.tailMode==="hidden"&&!u.alternate&&!Ue)return pt(t),null}else 2*Ie()-l.renderingStartTime>Ss&&n!==1073741824&&(t.flags|=128,r=!0,Gs(l,!1),t.lanes=4194304);l.isBackwards?(u.sibling=t.child,t.child=u):(n=l.last,n!==null?n.sibling=u:t.child=u,l.last=u)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=Ie(),t.sibling=null,n=He.current,Le(He,r?n&1|2:n&1),t):(pt(t),null);case 22:case 23:return Pi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(qt&1073741824)!==0&&(pt(t),t.subtreeFlags&6&&(t.flags|=8192)):pt(t),null;case 24:return null;case 25:return null}throw Error(m(156,t.tag))}function Jd(e,t){switch(Ol(t),t.tag){case 1:return Lt(t.type)&&xo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return vs(),Oe(It),Oe(ft),Jl(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return ql(t),null;case 13:if(Oe(He),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(m(340));ms()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Oe(He),null;case 4:return vs(),null;case 10:return Hl(t.type._context),null;case 22:case 23:return Pi(),null;case 24:return null;default:return null}}var Fo=!1,ht=!1,Yd=typeof WeakSet=="function"?WeakSet:Set,b=null;function xs(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Qe(e,t,r)}else n.current=null}function gi(e,t,n){try{n()}catch(r){Qe(e,t,r)}}var Bu=!1;function Xd(e,t){if(Pl=so,e=xa(),_l(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,l=r.focusNode;r=r.focusOffset;try{n.nodeType,l.nodeType}catch{n=null;break e}var u=0,f=-1,g=-1,w=0,E=0,M=e,N=null;t:for(;;){for(var B;M!==n||s!==0&&M.nodeType!==3||(f=u+s),M!==l||r!==0&&M.nodeType!==3||(g=u+r),M.nodeType===3&&(u+=M.nodeValue.length),(B=M.firstChild)!==null;)N=M,M=B;for(;;){if(M===e)break t;if(N===n&&++w===s&&(f=u),N===l&&++E===r&&(g=u),(B=M.nextSibling)!==null)break;M=N,N=M.parentNode}M=B}n=f===-1||g===-1?null:{start:f,end:g}}else n=null}n=n||{start:0,end:0}}else n=null;for(Rl={focusedElem:e,selectionRange:n},so=!1,b=t;b!==null;)if(t=b,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,b=e;else for(;b!==null;){t=b;try{var H=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(H!==null){var V=H.memoizedProps,qe=H.memoizedState,_=t.stateNode,v=_.getSnapshotBeforeUpdate(t.elementType===t.type?V:Nn(t.type,V),qe);_.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var S=t.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(m(163))}}catch(L){Qe(t,t.return,L)}if(e=t.sibling,e!==null){e.return=t.return,b=e;break}b=t.return}return H=Bu,Bu=!1,H}function Js(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var l=s.destroy;s.destroy=void 0,l!==void 0&&gi(t,n,l)}s=s.next}while(s!==r)}}function Uo(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function vi(e){var t=e.ref;if(t!==null){var n=e.stateNode;e.tag,e=n,typeof t=="function"?t(e):t.current=e}}function bu(e){var t=e.alternate;t!==null&&(e.alternate=null,bu(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Vn],delete t[Fs],delete t[Il],delete t[Ld],delete t[Dd])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Hu(e){return e.tag===5||e.tag===3||e.tag===4}function Vu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Hu(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function yi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=vo));else if(r!==4&&(e=e.child,e!==null))for(yi(e,t,n),e=e.sibling;e!==null;)yi(e,t,n),e=e.sibling}function xi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(xi(e,t,n),e=e.sibling;e!==null;)xi(e,t,n),e=e.sibling}var it=null,En=!1;function Rr(e,t,n){for(n=n.child;n!==null;)Qu(e,t,n),n=n.sibling}function Qu(e,t,n){if(ct&&typeof ct.onCommitFiberUnmount=="function")try{ct.onCommitFiberUnmount(Mt,n)}catch{}switch(n.tag){case 5:ht||xs(n,t);case 6:var r=it,s=En;it=null,Rr(e,t,n),it=r,En=s,it!==null&&(En?(e=it,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):it.removeChild(n.stateNode));break;case 18:it!==null&&(En?(e=it,n=n.stateNode,e.nodeType===8?Tl(e.parentNode,n):e.nodeType===1&&Tl(e,n),Ps(e)):Tl(it,n.stateNode));break;case 4:r=it,s=En,it=n.stateNode.containerInfo,En=!0,Rr(e,t,n),it=r,En=s;break;case 0:case 11:case 14:case 15:if(!ht&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var l=s,u=l.destroy;l=l.tag,u!==void 0&&((l&2)!==0||(l&4)!==0)&&gi(n,t,u),s=s.next}while(s!==r)}Rr(e,t,n);break;case 1:if(!ht&&(xs(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(f){Qe(n,t,f)}Rr(e,t,n);break;case 21:Rr(e,t,n);break;case 22:n.mode&1?(ht=(r=ht)||n.memoizedState!==null,Rr(e,t,n),ht=r):Rr(e,t,n);break;default:Rr(e,t,n)}}function Wu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Yd),t.forEach(function(r){var s=af.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Pn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~l}if(r=s,r=Ie()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*ef(r/1960))-r,10e?16:e,Ar===null)var r=!1;else{if(e=Ar,Ar=null,Qo=0,(_e&6)!==0)throw Error(m(331));var s=_e;for(_e|=4,b=e.current;b!==null;){var l=b,u=l.child;if((b.flags&16)!==0){var f=l.deletions;if(f!==null){for(var g=0;gIe()-wi?Kr(e,0):Si|=n),Ot(e,t)}function oc(e,t){t===0&&((e.mode&1)===0?t=1:(t=Bn,Bn<<=1,(Bn&130023424)===0&&(Bn=4194304)));var n=kt();e=or(e,t),e!==null&&(Ht(e,t,n),Ot(e,n))}function lf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),oc(e,n)}function af(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(m(314))}r!==null&&r.delete(t),oc(e,n)}var lc;lc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||It.current)Dt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Dt=!1,qd(e,t,n);Dt=(e.flags&131072)!==0}else Dt=!1,Ue&&(t.flags&1048576)!==0&&Fa(t,jo,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;$o(e,t),e=t.pendingProps;var s=cs(t,ft.current);gs(t,n),s=Zl(null,t,r,e,s,n);var l=ei();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Lt(r)?(l=!0,_o(t)):l=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Wl(t),s.updater=zo,t.stateNode=s,s._reactInternals=t,li(t,r,e,n),t=ci(null,t,r,!0,l,n)):(t.tag=0,Ue&&l&&zl(t),jt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch($o(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=cf(r),e=Nn(r,e),s){case 0:t=ui(null,t,r,e,n);break e;case 1:t=Tu(null,t,r,e,n);break e;case 11:t=Eu(null,t,r,e,n);break e;case 14:t=Pu(null,t,r,Nn(r.type,e),n);break e}throw Error(m(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),ui(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),Tu(e,t,r,s,n);case 3:e:{if(Iu(t),e===null)throw Error(m(387));r=t.pendingProps,l=t.memoizedState,s=l.element,qa(e,t),Ro(t,r,null,n);var u=t.memoizedState;if(r=u.element,l.isDehydrated)if(l={element:r,isDehydrated:!1,cache:u.cache,pendingSuspenseBoundaries:u.pendingSuspenseBoundaries,transitions:u.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){s=ys(Error(m(423)),t),t=Lu(e,t,r,n,s);break e}else if(r!==s){s=ys(Error(m(424)),t),t=Lu(e,t,r,n,s);break e}else for(Kt=jr(t.stateNode.containerInfo.firstChild),Wt=t,Ue=!0,Cn=null,n=Wa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ms(),r===s){t=ir(e,t,n);break e}jt(e,t,r,n)}t=t.child}return t;case 5:return Ya(t),e===null&&Fl(t),r=t.type,s=t.pendingProps,l=e!==null?e.memoizedProps:null,u=s.children,Ml(r,s)?u=null:l!==null&&Ml(r,l)&&(t.flags|=32),Au(e,t),jt(e,t,u,n),t.child;case 6:return e===null&&Fl(t),null;case 13:return Du(e,t,n);case 4:return Kl(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ps(t,null,r,n):jt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),Eu(e,t,r,s,n);case 7:return jt(e,t,t.pendingProps,n),t.child;case 8:return jt(e,t,t.pendingProps.children,n),t.child;case 12:return jt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,l=t.memoizedProps,u=s.value,Le(No,r._currentValue),r._currentValue=u,l!==null)if(kn(l.value,u)){if(l.children===s.children&&!It.current){t=ir(e,t,n);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var f=l.dependencies;if(f!==null){u=l.child;for(var g=f.firstContext;g!==null;){if(g.context===r){if(l.tag===1){g=lr(-1,n&-n),g.tag=2;var w=l.updateQueue;if(w!==null){w=w.shared;var E=w.pending;E===null?g.next=g:(g.next=E.next,E.next=g),w.pending=g}}l.lanes|=n,g=l.alternate,g!==null&&(g.lanes|=n),Vl(l.return,n,t),f.lanes|=n;break}g=g.next}}else if(l.tag===10)u=l.type===t.type?null:l.child;else if(l.tag===18){if(u=l.return,u===null)throw Error(m(341));u.lanes|=n,f=u.alternate,f!==null&&(f.lanes|=n),Vl(u,n,t),u=l.sibling}else u=l.child;if(u!==null)u.return=l;else for(u=l;u!==null;){if(u===t){u=null;break}if(l=u.sibling,l!==null){l.return=u.return,u=l;break}u=u.return}l=u}jt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,gs(t,n),s=un(s),r=r(s),t.flags|=1,jt(e,t,r,n),t.child;case 14:return r=t.type,s=Nn(r,t.pendingProps),s=Nn(r.type,s),Pu(e,t,r,s,n);case 15:return Ru(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),$o(e,t),t.tag=1,Lt(r)?(e=!0,_o(t)):e=!1,gs(t,n),_u(t,r,s),li(t,r,s,n),ci(null,t,r,!0,e,n);case 19:return Ou(e,t,n);case 22:return Mu(e,t,n)}throw Error(m(156,t.tag))};function ic(e,t){return Ne(e,t)}function uf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function fn(e,t,n,r){return new uf(e,t,n,r)}function Mi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function cf(e){if(typeof e=="function")return Mi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ie)return 11;if(e===fe)return 14}return 2}function Lr(e,t){var n=e.alternate;return n===null?(n=fn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Go(e,t,n,r,s,l){var u=2;if(r=e,typeof e=="function")Mi(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case $e:return Gr(n.children,s,l,t);case We:u=8,s|=8;break;case Ge:return e=fn(12,n,t,s|2),e.elementType=Ge,e.lanes=l,e;case Te:return e=fn(13,n,t,s),e.elementType=Te,e.lanes=l,e;case Fe:return e=fn(19,n,t,s),e.elementType=Fe,e.lanes=l,e;case me:return Jo(n,s,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Ze:u=10;break e;case rt:u=9;break e;case ie:u=11;break e;case fe:u=14;break e;case Re:u=16,r=null;break e}throw Error(m(130,e==null?e:typeof e,""))}return t=fn(u,n,t,s),t.elementType=e,t.type=r,t.lanes=l,t}function Gr(e,t,n,r){return e=fn(7,e,r,t),e.lanes=n,e}function Jo(e,t,n,r){return e=fn(22,e,r,t),e.elementType=me,e.lanes=n,e.stateNode={isHidden:!1},e}function Ai(e,t,n){return e=fn(6,e,null,t),e.lanes=n,e}function Ti(e,t,n){return t=fn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function df(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Tt(0),this.expirationTimes=Tt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Tt(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Ii(e,t,n,r,s,l,u,f,g){return e=new df(e,t,n,f,g),t===1?(t=1,l===!0&&(t|=8)):t=0,l=fn(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Wl(l),e}function ff(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(p){console.error(p)}}return i(),Fi.exports=kf(),Fi.exports}var Sc;function Nf(){if(Sc)return rl;Sc=1;var i=Cf();return rl.createRoot=i.createRoot,rl.hydrateRoot=i.hydrateRoot,rl}var Ef=Nf();const Pf=Oc(Ef),Rf="/api";async function Ee(i,p){const m=await fetch(`${Rf}${i}`,{...p,headers:{"Content-Type":"application/json",...p?.headers??{}}}),R=await m.json();if(!m.ok){const j=R.error?.message??"Ошибка запроса";throw new Error(j)}return R}const Ce={async listModels(i){return Ee("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async testConnection(i){return Ee("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async normalize(i){return Ee("/normalize",{method:"POST",body:JSON.stringify({llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,userQuestion:i.query.userQuestion,context:{period_hint:i.query.periodHint??"",business_context:i.query.businessContext??"",expected_route:i.query.expectedRoute??""},saveAsTestCase:!!i.saveAsTestCase,useMock:!!i.useMock})})},async loadHistory(){return Ee("/history")},async loadTrace(i){return Ee(`/history/${i}`)},async loadPresets(){return Ee("/presets")},async savePreset(i){return Ee("/presets/save",{method:"POST",body:JSON.stringify(i)})},async runEval(i){return Ee("/eval/run",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,analysis_date:i.analysisDate})})},async startEvalRunAsync(i){return Ee("/eval/run-async/start",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,questions:i.questions,analysis_date:i.analysisDate})})},async loadEvalRunAsyncStatus(i){return Ee(`/eval/run-async/${encodeURIComponent(i)}`)},async startRun(){return Ee("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(i){return Ee("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:i,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return Ee("/accounting-agent/v1/runs")},async listResults(){return Ee("/accounting-agent/v1/results")},async runTrace(i){return Ee(`/accounting-agent/v1/trace/run/${i}`)},async sendAssistantMessage(i){return Ee("/assistant/message",{method:"POST",body:JSON.stringify({session_id:i.sessionId??"",mode:"assistant",message:i.userMessage,user_message:i.userMessage,llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion??"address_query_runtime_v1",systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,context:{period_hint:i.context?.periodHint??"",business_context:i.context?.businessContext??""},useMock:!!i.useMock})})},async loadAssistantSession(i){return Ee(`/assistant/session/${i}`)},async loadAssistantAnnotations(i){const p=new URLSearchParams;i?.session_id&&p.set("session_id",i.session_id),typeof i?.limit=="number"&&p.set("limit",String(i.limit));const m=p.toString();return Ee(`/assistant/annotations${m?`?${m}`:""}`)},async saveAssistantAnnotation(i){return Ee("/assistant/annotations",{method:"POST",body:JSON.stringify(i)})},async loadAutoRunsHistory(i){const p=new URLSearchParams;i?.from&&p.set("from",i.from),i?.to&&p.set("to",i.to),i?.target&&p.set("target",i.target),i?.mode&&p.set("mode",i.mode),i?.use_mock&&p.set("use_mock",i.use_mock),i?.prompt_contains&&p.set("prompt_contains",i.prompt_contains),typeof i?.limit=="number"&&p.set("limit",String(i.limit)),typeof i?.scan_limit=="number"&&p.set("scan_limit",String(i.scan_limit));const m=p.toString();return Ee(`/autoruns/history${m?`?${m}`:""}`)},async loadAutoRunDetail(i){return Ee(`/autoruns/history/${encodeURIComponent(i)}`)},async loadAutoRunCaseDialog(i,p){return Ee(`/autoruns/history/${encodeURIComponent(i)}/case/${encodeURIComponent(p)}/dialog`)},async loadAutoRunAnnotations(i){const p=new URLSearchParams;i?.run_id&&p.set("run_id",i.run_id),i?.case_id&&p.set("case_id",i.case_id),typeof i?.min_rating=="number"&&p.set("min_rating",String(i.min_rating)),i?.manual_case_decision&&p.set("manual_case_decision",i.manual_case_decision),typeof i?.limit=="number"&&p.set("limit",String(i.limit));const m=p.toString();return Ee(`/autoruns/annotations${m?`?${m}`:""}`)},async saveAutoRunAnnotation(i){return Ee("/autoruns/annotations",{method:"POST",body:JSON.stringify(i)})},async updateAutoRunAnnotation(i){return Ee(`/autoruns/annotations/${encodeURIComponent(i.annotation_id)}`,{method:"PATCH",body:JSON.stringify({resolved:i.resolved,resolved_by:i.resolved_by})})},async loadAutoRunPostAnalysis(i){const p=new URLSearchParams;i?.run_id&&p.set("run_id",i.run_id),typeof i?.limit_per_queue=="number"&&p.set("limit_per_queue",String(i.limit_per_queue)),typeof i?.annotation_limit=="number"&&p.set("annotation_limit",String(i.annotation_limit)),typeof i?.scan_limit=="number"&&p.set("scan_limit",String(i.scan_limit)),i?.from&&p.set("from",i.from),i?.to&&p.set("to",i.to),i?.target&&p.set("target",i.target),i?.mode&&p.set("mode",i.mode),i?.use_mock&&p.set("use_mock",i.use_mock),i?.prompt_contains&&p.set("prompt_contains",i.prompt_contains);const m=p.toString();return Ee(`/autoruns/post-analysis${m?`?${m}`:""}`)},async loadAutoRunAutogenHistory(i){const p=new URLSearchParams;i?.mode&&p.set("mode",i.mode),typeof i?.limit=="number"&&p.set("limit",String(i.limit));const m=p.toString();return Ee(`/autoruns/autogen/history${m?`?${m}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return Ee("/autoruns/autogen/personality-catalog")},async generateAutoRunQuestions(i){return Ee("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(i)})}};function Gt({value:i}){return o.jsx("pre",{className:"json-view",children:JSON.stringify(i??{},null,2)})}function Mn({title:i,subtitle:p,actions:m,className:R,hideHeader:j,children:T}){return o.jsxs("section",{className:R?`panel-frame ${R}`:"panel-frame",children:[j?null:o.jsxs("header",{className:"panel-header",children:[o.jsxs("div",{children:[o.jsx("h2",{children:i}),p?o.jsx("p",{children:p}):null]}),m?o.jsx("div",{className:"panel-actions",children:m}):null]}),o.jsx("div",{className:"panel-body",children:T})]})}function Mf(i){const p=new Date(i);return Number.isNaN(p.getTime())?i:p.toLocaleString("ru-RU")}function Af({sessionId:i,conversation:p,statusText:m,errorMessage:R,useMock:j,appLogs:T}){const $=p.filter(I=>I.role==="assistant").length,Y=p.filter(I=>I.role==="user").length,F=p.length>0?p[p.length-1]:null;return o.jsxs(Mn,{title:"SAM",subtitle:"System Assistant Monitor: срез по текущей сессии и логам.",children:[o.jsxs("div",{className:"metrics-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"session_id"}),o.jsx("strong",{children:i||"новая сессия"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"mock_mode"}),o.jsx("strong",{children:j?"on":"off"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"сообщений пользователя"}),o.jsx("strong",{children:Y})]}),o.jsxs("div",{children:[o.jsx("span",{children:"ответов ассистента"}),o.jsx("strong",{children:$})]}),o.jsxs("div",{children:[o.jsx("span",{children:"статус"}),o.jsx("strong",{children:m||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"ошибка"}),o.jsx("strong",{children:R||"нет"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"последнее сообщение"}),o.jsx("strong",{children:F?.created_at?Mf(F.created_at):"нет данных"})]})]}),o.jsx("h3",{style:{marginTop:12},children:"Последние системные логи"}),o.jsx(Gt,{value:T.slice(0,120)})]})}const Tf=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,If=[/\b(?:debug_payload_json|technical_breakdown_json)\b/i,/\b(?:route_summary|semantic_profile|domain_scope|relation_patterns|account_scope)\b/i,/\b(?:coverage_report|retrieval_status|problem_unit_state|candidate_evidence)\b/i,/\b(?:graph_domain_scope|graph_runtime|selection_reason|why_included)\b/i];function Lf(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function Df(i){const p=String(i??""),m=p.match(Tf);return(m?p.slice(0,m.index):p).replace(/###\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)[\s\S]*?(?:```[\s\S]*?```|$)/gi,"").replace(/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)\b[\s\S]*$/gi,"").split(/\r?\n/g).map($=>$.trimEnd()).filter($=>$.trim().length>0).filter($=>!If.some(Y=>Y.test($))).join(` `).trim()}function zf(i,p,m="default"){const R=m==="technical",j=[];j.push("# Assistant conversation export"),j.push(`session_id: ${i||"n/a"}`),j.push(`export_mode: ${m}`),j.push(`exported_at: ${new Date().toISOString()}`),j.push("");for(let T=0;T{j.length!==0&&(R.push(j.join(` `)),j=[])};for(const $ of m){const Y=$.trimEnd(),F=Y.trim();if(!F){T();continue}const I=/^Блок\s+\d+\./i.test(F),W=/^\d+\.\s/.test(F);(I||W)&&j.length>0&&T(),j.push(Y)}return T(),R.length>0?R:[i]}function Hf(i,p){const m=[],R=/\*\*(.+?)\*\*/g;let j=0,T=0,$;for(;($=R.exec(i))!==null;)$.index>j&&(m.push(o.jsx("span",{children:i.slice(j,$.index)},`${p}-t-${T}`)),T+=1),m.push(o.jsx("strong",{children:$[1]},`${p}-b-${T}`)),T+=1,j=R.lastIndex;return j0?m:[o.jsx("span",{children:i},`${p}-raw`)]}function Vf(i){const p=i.trimStart();return/^Блок\s+\d+\./i.test(p)?"assistant-msg-line heading":/^\d+\.\s/.test(p)?"assistant-msg-line numbered":/^-\s/.test(p)?"assistant-msg-line bullet":"assistant-msg-line"}function Qf(i,p=40){const m=i.replace(/\s+/g," ").trim();if(m.length<=p)return m;const R=m.split(" ").slice(0,3).join(" ").trim();return R.length>=10&&R.length<=p?`${R}…`:`${m.slice(0,p-1).trimEnd()}…`}function $c(i){return i.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Wf(i){const p=i.replace(/\r\n?/g,` `).split(` `).map(j=>j.trim()).find(Boolean),m=$c(p??"");return(m.split("|")[0]?.trim()??m).replace(/\s+/g," ").trim()}function Kf(i){const p=i.replace(/\r\n?/g,` `).split(` `).map(R=>R.trim()).find(Boolean);return!p||!/^\d+\.\s/.test(p)?!1:$c(p).includes("|")}function qf(i,p){const m=p.replace(/\r\n?/g,` `).replace(/\*\*(.+?)\*\*/g,"$1").split(` `).map((j,T)=>{const $=j.trim();return T===0?$.replace(/^\d+\.\s*/,""):$}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!m)return null;const R=Wf(p)||m;return{message_id:i.message_id,source_text:m,anchor_text:R,preview_text:Qf(R)}}function Gf(i,p,m,R){return bf(i.text).map((T,$)=>{const Y=T.split(` `),F=i.role==="assistant"&&Kf(T),I=F?qf(i,T):null,W=!!I&&p?.message_id===I?.message_id&&p?.source_text===I?.source_text,z=Y.map((U,oe)=>o.jsx("p",{className:Vf(U),children:Hf(U,`line-${$}-${oe}`)},`line-${$}-${oe}`));return!F||!I?o.jsx("div",{className:"assistant-msg-block",children:z},`block-${$}`):o.jsx("div",{className:W?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(W){R();return}m(I)},onKeyDown:U=>{if(!(U.key!=="Enter"&&U.key!==" ")){if(U.preventDefault(),W){R();return}m(I)}},children:z},`block-${$}`)})}function Fc({sessionId:i,conversation:p,inputValue:m,onInputChange:R,selectedContextChip:j,onSelectContextChip:T,onClearContextChip:$,useMock:Y,onUseMockChange:F,onSend:I,onClear:W,busy:z,statusText:U,errorMessage:oe,showCommentAction:Me=!1,onCommentAssistantMessage:te,isAssistantMessageCommented:se,canCommentAssistantMessage:q}){const re=x.useRef(null),Se=x.useRef(!0),Pe=x.useRef(null),[Ae,De]=x.useState("idle"),[$e,We]=x.useState("чат");function Ge(ie=!1){re.current&&(ie&&(Se.current=!0),re.current.scrollTop=re.current.scrollHeight)}x.useEffect(()=>{Se.current&&Ge()},[p]),x.useEffect(()=>()=>{Pe.current!==null&&window.clearTimeout(Pe.current)},[]);async function Ze(ie){if(p.length===0)return;const Te=zf(i,p,ie),Fe=await Ff(Te);We(ie==="technical"?"тех":"чат"),De(Fe?"success":"error"),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{De("idle")},2200)}function rt(){if(!re.current)return;const ie=re.current,Te=ie.scrollHeight-ie.scrollTop-ie.clientHeight;Se.current=Te<16}return o.jsx(Mn,{className:"assistant-panel-frame",title:"Режим ассистента",children:o.jsxs("div",{className:"assistant-live-shell",children:[o.jsxs("div",{className:"assistant-toolbar",children:[o.jsxs("div",{className:"assistant-toolbar-actions",children:[o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Ze("default")},disabled:p.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Ze("technical")},disabled:p.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>W(),disabled:z&&p.length===0,children:"Сбросить сессию"})]}),o.jsxs("div",{className:"assistant-toolbar-meta",children:[i?o.jsx("span",{className:"status-chip",children:`session: ${i}`}):null,o.jsxs("div",{className:"assistant-toolbar-meta-right",children:[U?o.jsx("span",{className:"assistant-live-status",children:U}):null,Ae==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",$e,")"]}):null,Ae==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),oe?o.jsx("p",{className:"error-text assistant-toolbar-error",children:oe}):null]}),o.jsx("div",{ref:re,className:"assistant-chat-list",onScroll:rt,children:p.map((ie,Te)=>{const Fe=ie.role==="assistant"&&Me&&typeof te=="function"&&(typeof q=="function"?q(ie,Te):!0),fe=ie.role==="assistant"&&typeof se=="function"?se(ie,Te):!1;return o.jsxs("article",{className:`assistant-msg ${ie.role}`,children:[o.jsxs("header",{className:"assistant-msg-head",children:[o.jsxs("div",{className:"assistant-msg-head-main",children:[o.jsx("strong",{children:Of(ie.role)}),o.jsx("span",{children:$f(ie.created_at)})]}),ie.role==="assistant"&&Me?o.jsx("div",{className:"assistant-msg-head-actions",children:o.jsx("button",{type:"button",className:fe?"autoruns-comment-icon assistant-comment-btn commented":"autoruns-comment-icon assistant-comment-btn",onClick:()=>te?.(ie,Te),disabled:!Fe,title:Fe?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":Fe?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:o.jsx(Uf,{commented:fe})})}):null]}),o.jsx("div",{className:"assistant-msg-body",children:Gf(ie,j,T,$)}),ie.role==="assistant"&&ie.debug?o.jsxs("details",{className:"assistant-debug",children:[o.jsx("summary",{children:"Показать технический разбор"}),o.jsx(Gt,{value:ie.debug})]}):null]},ie.message_id)})}),o.jsxs("div",{className:"assistant-compose",children:[j?o.jsxs("div",{className:"assistant-compose-context",children:[o.jsx("span",{className:"assistant-compose-context-label",children:"Выбранный объект"}),o.jsxs("div",{className:"assistant-compose-context-pill",title:j.source_text,children:[o.jsx("span",{className:"assistant-compose-context-pill-text",children:j.preview_text}),o.jsx("button",{type:"button",className:"assistant-compose-context-clear",onClick:$,"aria-label":"Убрать выбранный объект",title:"Убрать выбранный объект",children:"×"})]})]}):null,o.jsxs("label",{className:"full-width",children:["Сообщение",o.jsx("textarea",{className:"assistant-input-textarea",value:m,onChange:ie=>R(ie.target.value),rows:4,placeholder:j?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),o.jsxs("div",{className:"button-row assistant-send-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:Y,onChange:ie=>F(ie.target.checked)}),"Mock-режим"]}),o.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{Ge(!0),I()},disabled:z||!m.trim(),children:z?"Выполняю...":"Отправить"})]})]})]})})}const bi={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},sl="needs_dialog_policy_fix",gt="__all__",al="__live__:",wc="ndc_autoruns_ui_config_v1",jc="ndc-autoruns-save",Hi=["Анализ запроса","Получение данных","Подготовка ответа"];function Jf(i,p){const m=i.trim();if(!m)return"";if(!p)return m;const R=m.toLowerCase(),j=p.anchor_text.trim(),T=j.toLowerCase();return T&&R.includes(T)?m:`По выбранному объекту "${j}": ${m}`}const Ji=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function Yf(i=Ji){return i.reduce((p,m)=>(p[m.id]=m.defaultPrompt,p),{})}const kc={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:Yf(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function Vi(i){const p=String(i??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(p)?p:""}function Cc(i){const p=typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):160;return Math.max(110,Math.min(520,p))}function Xf(i){const p=i.getFullYear(),m=String(i.getMonth()+1).padStart(2,"0"),R=String(i.getDate()).padStart(2,"0"),j=String(i.getHours()).padStart(2,"0"),T=String(i.getMinutes()).padStart(2,"0");return`${p}-${m}-${R}T${j}:${T}`}function Nc(){const i=new Date;return i.setDate(i.getDate()-14),Xf(i)}function ol(i){if(!i.trim())return;const p=Date.parse(i);if(Number.isFinite(p))return new Date(p).toISOString()}function ur(i){if(!i)return"нет данных";const p=Date.parse(i);return Number.isFinite(p)?new Date(p).toLocaleString("ru-RU"):i}function Zf(i,p){return p<=0?0:Math.max(0,Math.min(100,Number((i/p*100).toFixed(1))))}function ll(i){return typeof i!="number"?"нет данных":`${i.toFixed(1)}%`}function em(i){return i==="assistant_stage1"?"assistant/s1":i==="assistant_stage2"?"assistant/s2":i==="assistant_p0"?"assistant/p0":i}function Ec(i){return i==="up"?"Рост":i==="down"?"Регресс":"Без изменений"}function tm(i,p){return i.find(m=>m.case_id===p)??null}function Qi(i){const p=Math.max(1,Math.min(5,Math.round(i)));return`${"●".repeat(p)}${"○".repeat(5-p)}`}function Pc(i){return i.length===0?o.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):o.jsx("div",{className:"autoruns-coverage-list",children:i.map(p=>{const m=Zf(p.closed_cases,p.total_cases);return o.jsxs("div",{className:"autoruns-coverage-item",children:[o.jsxs("div",{className:"autoruns-coverage-head",children:[o.jsx("strong",{children:p.domain}),o.jsxs("span",{children:[p.closed_cases,"/",p.total_cases," (",m,"%)"]})]}),o.jsx("div",{className:"autoruns-coverage-bar",children:o.jsx("div",{style:{width:`${m}%`}})})]},p.domain)})})}function il(i){return`${al}${i}`}function js(i){return i.startsWith(al)}function Rc(i){return i.startsWith(al)?i.slice(al.length):""}function Uc(i){const p=i.report_summary?.run_timestamp??i.created_at,m=Math.max(0,i.total_cases-i.completed_cases);return{run_id:il(i.job_id),eval_target:i.eval_target,run_timestamp:p,mode:"single-pass-strict",llm_provider:null,model:null,use_mock:null,analysis_date:i.report_summary?.analysis_date??i.analysis_date??null,prompt_version:null,schema_version:null,suite_id:i.case_set_file,cases_total:i.total_cases,requests_total:null,report_path:`async_job:${i.job_id}`,score_index:i.report_summary?.score_index??null,blocking_failures:0,quality_failures:0,closed_cases:i.completed_cases,open_cases:m,domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]}}function no(i,p){const m=Uc(i),R=i.cases.map(W=>({case_id:W.case_id,domain:null,query_class:null,status:W.status==="completed"?"closed":W.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${i.run_id}-${W.case_id}`,dialog_available:W.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),T=p!==gt&&R.some(W=>W.case_id===p)?p:R.length>0?gt:"",$={ok:!0,run:m,coverage:{closed_cases:i.completed_cases,open_cases:Math.max(0,i.total_cases-i.completed_cases),domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]},cases:R,annotations_summary:{total:0},report:i.report_summary?{run_id:i.report_summary.run_id,run_timestamp:i.report_summary.run_timestamp,score_index:i.report_summary.score_index,cases_total:i.report_summary.cases_total,analysis_date:i.report_summary.analysis_date??i.analysis_date??null}:{}},Y=[];let F=0;if(T===gt)for(const W of i.cases)for(let z=0;zz.case_id===T)??null;for(let z=0;z<(W?.messages.length??0);z+=1){const U=W?.messages[z];U&&Y.push({...U,message_index:z,case_id:T,case_message_index:z,commented:!1,annotation:null})}}const I={ok:!0,run_id:m.run_id,case_id:T,source:"assistant_session",session_id:T===gt?`${i.run_id}::__all__`:`${i.run_id}-${T}`,messages:Y,decomposition:[],assistant_mode:{status:i.status,completed_cases:i.completed_cases,total_cases:i.total_cases},annotations:[]};return{detail:$,dialog:I,caseId:T}}function nm({commented:i}){const p=i?"comment-icon-svg commented":"comment-icon-svg";return o.jsx("svg",{className:p,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M5 6.5h14v9H11.5l-4.5 3v-3H5z"})})}function Mc({resolved:i}){return o.jsxs("svg",{className:i?"resolve-icon-svg resolved":"resolve-icon-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[o.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),i?o.jsx("path",{d:"M5.1 8.2 7.2 10.3 11 6.5"}):null]})}function rm(){return o.jsxs("svg",{className:"autoruns-copy-icon-svg",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2.2"}),o.jsx("path",{d:"M15 7V5.8a1.8 1.8 0 0 0-1.8-1.8H5.8A1.8 1.8 0 0 0 4 5.8v7.4A1.8 1.8 0 0 0 5.8 15H7"})]})}function sm({connection:i,prompts:p,assistantPromptVersion:m,decompositionPromptVersion:R,showAssistantMode:j,showDecompositionMode:T,showProgressMode:$,showCommentsMode:Y,onLog:F}){const[I,W]=x.useState({...bi,fromLocal:Nc()}),[z,U]=x.useState(""),[oe,Me]=x.useState(null),[te,se]=x.useState(null),[q,re]=x.useState(null),[Se,Pe]=x.useState([]),[Ae,De]=x.useState("all"),[$e,We]=x.useState(!1),[Ge,Ze]=x.useState(null),[rt,ie]=x.useState([]),[Te,Fe]=x.useState(""),[fe,Re]=x.useState(""),[me,D]=x.useState(""),[Q,O]=x.useState(Ji),[h,C]=x.useState(kc),[G,ae]=x.useState([]),[ce,de]=x.useState(""),[xe,ge]=x.useState([]),[ee,ke]=x.useState(null),[Ft,qn]=x.useState(null),[An,Tn]=x.useState(!1),[dr,Jt]=x.useState(!1),[Yt,Gn]=x.useState(!1),[mn,Ut]=x.useState(!1),[Xt,pn]=x.useState(!1),[fr,In]=x.useState(!1),[mr,Ln]=x.useState(!1),[Zt,en]=x.useState(!1),[pr,Bt]=x.useState(""),[hn,Be]=x.useState(""),[st,gn]=x.useState(""),[vn,tn]=x.useState([]),[nn,Ct]=x.useState([]),[Dn,rn]=x.useState(""),[bt,vt]=x.useState(null),[Jn,Ke]=x.useState(!1),[hr,yn]=x.useState(!1),[gr,sn]=x.useState(""),[vr,Nt]=x.useState(""),[Yn,yt]=x.useState(String(bi.limit)),[Jr,xt]=x.useState(String(kc.count)),[Et,zn]=x.useState(160),[ue,ot]=x.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:sl,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[ve,_t]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),Pt=x.useRef(!1),we=x.useRef(null),lt=x.useMemo(()=>Q.find(a=>a.id===h.personalityId)??Q[0]??Ji[0],[h.personalityId,Q]),Rt=x.useMemo(()=>G.find(a=>a.generation_id===ce)??G[0]??null,[G,ce]),On=te?tm(te.cases,me):null,J=x.useMemo(()=>$e?Se.filter(a=>!a.resolved):Se,[Se,$e]),Ne=J.find(a=>a.annotation_id===Te)??null,$n=q?.messages.find(a=>a.message_index===ue.messageIndex)??null,Yr=x.useMemo(()=>{if(!q||ue.messageIndex<0)return null;for(let a=ue.messageIndex-1;a>=0;a-=1){const c=q.messages[a];if(c?.role==="user")return c}return null},[ue.messageIndex,q]),xn=x.useMemo(()=>{const a=new Map;for(const c of nn)c.message_id&&a.set(c.message_id,c);return a},[nn]),Ie=ve.messageIndex>=0?vn[ve.messageIndex]??null:null,Xr=x.useMemo(()=>{if(ve.messageIndex<0)return null;for(let a=ve.messageIndex-1;a>=0;a-=1){const c=vn[a];if(c?.role==="user")return c}return null},[ve.messageIndex,vn]),ut=x.useMemo(()=>{const a=J.map(y=>({source:"autorun",key:`autorun:${y.annotation_id}`,updated_at:y.updated_at,rating:y.rating,autorun:y,assistant:null})),c=nn.map(y=>({source:"assistant_live",key:`assistant:${y.annotation_id}`,updated_at:y.updated_at,rating:y.rating,autorun:null,assistant:y}));return[...a,...c].sort((y,A)=>Date.parse(A.updated_at)-Date.parse(y.updated_at))},[nn,J]),yr=x.useMemo(()=>{if(ut.length===0)return null;const a=ut.reduce((c,y)=>c+y.rating,0)/ut.length;return Number(a.toFixed(2))},[ut]),Fn=x.useMemo(()=>{const a=[...oe?.items??[]];return ee&&a.unshift(Uc(ee)),fe&&!a.some(c=>c.run_id===fe)&&te?.run&&a.unshift(te.run),a},[ee,oe?.items,te?.run,fe]),le=x.useCallback(a=>{F?.(`[autoruns] ${a}`)},[F]),Un=x.useCallback(async a=>{const c=String(a??"").trim();if(!c){Ct([]);return}try{const y=await Ce.loadAssistantAnnotations({session_id:c,limit:400});Ct(y.items??[])}catch(y){const A=y instanceof Error?y.message:String(y);le(`Assistant live annotations load error: ${A}`)}},[le]),Mt=x.useCallback(a=>{_t(c=>c.saving&&!a?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),ct=x.useCallback(async(a,c)=>{a.stopPropagation(),a.preventDefault();const y=String(c??"").trim();if(y)try{if(navigator?.clipboard?.writeText)await navigator.clipboard.writeText(y);else{const A=document.createElement("textarea");A.value=y,A.setAttribute("readonly","true"),A.style.position="fixed",A.style.opacity="0",document.body.appendChild(A),A.select(),document.execCommand("copy"),document.body.removeChild(A)}le(`run id copied: ${y}`)}catch(A){const pe=A instanceof Error?A.message:String(A);Be(`Копирование run id: ${pe}`),le(`copy run id error: ${pe}`)}},[le]);function ks(){let a=0;sn(Hi[0]);const c=window.setInterval(()=>{a=Math.min(a+1,Hi.length-1),sn(Hi[a])},650);return()=>window.clearInterval(c)}const St=x.useCallback(()=>{gn(""),tn([]),Ct([]),rn(""),vt(null),sn(""),Nt(""),Mt({force:!0}),le("Live-чат ассистента в истории автопрогонов сброшен.")},[Mt,le]),Cs=x.useCallback(async()=>{const a=Jf(Dn,bt);if(!a)return;yn(!0),Nt(""),rn(""),tn(y=>[...y,{message_id:`autoruns-live-${Date.now()}`,session_id:st||"pending",role:"user",text:a,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=ks();try{const y=await Ce.sendAssistantMessage({connection:i,prompts:p,userMessage:a,sessionId:st||void 0,promptVersion:m,useMock:Jn});gn(y.session_id),tn(y.conversation),await Un(y.session_id),sn("Ответ готов"),le(`Live-ответ ассистента получен: trace=${y.debug.trace_id}`)}catch(y){const A=y instanceof Error?y.message:String(y);Nt(A),sn("Ошибка ассистента"),le(`Live-чат ассистента: ошибка отправки сообщения: ${A}`)}finally{c(),yn(!1)}},[Dn,bt,st,Jn,m,i,Un,le,p]),Zr=x.useCallback(a=>{const c=a.trim();if(!c){yt(String(I.limit));return}if(!/^\d+$/.test(c)){yt(String(I.limit));return}const y=Number.parseInt(c,10);if(!Number.isFinite(y)){yt(String(I.limit));return}const A=Math.max(1,Math.min(500,y));A!==I.limit&&W(pe=>({...pe,limit:A})),yt(String(A))},[I.limit]),es=x.useCallback(a=>{const c=a.trim();if(!c){xt(String(h.count));return}if(!/^\d+$/.test(c)){xt(String(h.count));return}const y=Number.parseInt(c,10);if(!Number.isFinite(y)){xt(String(h.count));return}const A=Math.max(1,Math.min(200,y));A!==h.count&&C(pe=>({...pe,count:A})),xt(String(A))},[h.count]),Xn=x.useCallback(a=>{zn(Cc(a))},[]),Bn=x.useCallback(a=>{const c=a.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&Xn(c)},[Xn]),At=x.useCallback(async()=>{en(!0);try{const a=await Ce.loadAutoRunAnnotations({limit:800,manual_case_decision:Ae});Pe(a.items),Ze(a.manual_case_decision_schema??null),ie(a.available_manual_case_decisions??[]),Fe(c=>a.items.length===0?"":a.items.some(y=>y.annotation_id===c)?c:a.items[0].annotation_id)}catch(a){le(`Annotations load error: ${a instanceof Error?a.message:String(a)}`)}finally{en(!1)}},[Ae,le]),wt=x.useCallback(async()=>{Ut(!0);try{const a=await Ce.loadAutoRunAutogenHistory({limit:180});ae(a.items)}catch(a){le(`Autogen history load error: ${a instanceof Error?a.message:String(a)}`)}finally{Ut(!1)}},[le]),xr=x.useCallback(async()=>{try{const c=(await Ce.loadAutoRunAutogenPersonalityCatalog()).items.map(y=>({id:String(y.id??"").trim(),label:String(y.label??"").trim(),domain:typeof y.domain=="string"?y.domain.trim():"",defaultPrompt:String(y.default_prompt??"").trim()})).filter(y=>y.id.length>0&&y.label.length>0);if(c.length===0)return;O(c.map(y=>({id:y.id,label:y.label,domain:y.domain||"",defaultPrompt:y.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(a){le(`Autogen personality catalog load error: ${a instanceof Error?a.message:String(a)}`)}},[le]),dt=x.useCallback(async()=>{Gn(!0);try{const a=await Ce.loadAutoRunPostAnalysis({run_id:fe&&!js(fe)?fe:void 0,limit_per_queue:30,annotation_limit:1500,from:ol(I.fromLocal),to:ol(I.toLocal),target:I.target,mode:I.mode,use_mock:I.useMock,prompt_contains:I.promptContains.trim()||void 0});qn(a)}catch(a){le(`Post-analysis load error: ${a instanceof Error?a.message:String(a)}`),qn(null)}finally{Gn(!1)}},[I.fromLocal,I.mode,I.promptContains,I.target,I.toLocal,I.useMock,le,fe]),zr=x.useCallback(async()=>{Tn(!0),Be("");try{const a=h.personalityPrompts[h.personalityId]??"",c=[p.systemPrompt,p.developerPrompt,p.domainPrompt,p.schemaNotes,p.fewShotExamples].join(` `).slice(0,900),y=await Ce.generateAutoRunQuestions({mode:h.mode,count:h.count,domain:lt.domain||void 0,persist_to_eval_cases:h.persistToEvalCases,generated_by:h.generatedBy.trim()||void 0,llm:{llm_provider:i.llmProvider,api_key:i.apiKey,model:i.model,base_url:i.baseUrl,temperature:i.temperature,max_output_tokens:i.maxOutputTokens},context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:m,decomposition_prompt_version:R,prompt_fingerprint:c,autogen_personality_id:lt.id,autogen_personality_prompt:a.trim()||void 0}});le(`Generated ${y.generation.count} questions (${y.generation.mode}) id=${y.generation.generation_id}`+(y.generation.saved_case_set_file?` saved=${y.generation.saved_case_set_file}`:"")),de(y.generation.generation_id),ge([...y.generation.questions??[]]),await wt()}catch(a){const c=a instanceof Error?a.message:String(a);Be(`Автогенерация: ${c}`),le(`Autogen generate error: ${c}`)}finally{Tn(!1)}},[m,h.count,h.generatedBy,h.mode,h.personalityId,h.personalityPrompts,h.persistToEvalCases,i.apiKey,i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature,R,wt,le,p.developerPrompt,p.domainPrompt,p.fewShotExamples,p.schemaNotes,p.systemPrompt,lt.domain,lt.id]),bn=x.useCallback(async(a,c)=>{if(js(a)){const y=Rc(a);if(ee&&ee.job_id===y){const A=no(ee,c);Re(a),D(A.caseId),re(A.dialog);return}re(null);return}Ln(!0);try{const y=await Ce.loadAutoRunCaseDialog(a,c);re(y)}catch(y){const A=y instanceof Error?y.message:String(y);Be(`Диалог кейса: ${A}`),re(null),le(`Dialog load error for ${a}/${c}: ${A}`)}finally{Ln(!1)}},[ee,le]),Tt=x.useCallback(async(a,c)=>{if(js(a)){const y=Rc(a);if(ee&&ee.job_id===y){const A=no(ee,c??gt);Re(a),D(A.caseId),se(A.detail),re(A.dialog);return}Re(a),D(""),se(null),re(null);return}In(!0);try{const y=await Ce.loadAutoRunDetail(a);se(y);const A=(c&&(c===gt||y.cases.some(pe=>pe.case_id===c))?c:"")||(y.cases.length>0?gt:"")||"";Re(a),D(A),A?await bn(a,A):re(null)}catch(y){const A=y instanceof Error?y.message:String(y);Be(`Детализация прогона: ${A}`),se(null),re(null),le(`Run detail load error for ${a}: ${A}`)}finally{In(!1)}},[ee,bn,le]),Ht=x.useCallback(async a=>{pn(!0),Be("");try{const c=await Ce.loadAutoRunsHistory({from:ol(I.fromLocal),to:ol(I.toLocal),target:I.target,mode:I.mode,use_mock:I.useMock,prompt_contains:I.promptContains.trim()||void 0,limit:I.limit});if(Me(c),c.items.length===0){Re(""),D(""),se(null),re(null);return}const y=a?.keepSelection??!0,A=a?.preferredRunId??"",pe=a?.preferredCaseId??"",be=y&&A&&c.items.some(on=>on.run_id===A)?A:c.items[0].run_id;await Tt(be,y?pe:void 0),dt()}catch(c){const y=c instanceof Error?c.message:String(c);Be(`История прогонов: ${y}`),le(`History load error: ${y}`)}finally{pn(!1)}},[I.fromLocal,I.limit,I.mode,I.promptContains,I.target,I.toLocal,I.useMock,dt,Tt,le]),Vt=x.useCallback(()=>{we.current!==null&&(window.clearTimeout(we.current),we.current=null)},[]),Zn=x.useCallback(async a=>{try{const c=await Ce.loadEvalRunAsyncStatus(a);ke(c.job);const y=il(a);if(fe===y){const A=no(c.job,me||gt);se(A.detail),re(A.dialog),D(A.caseId)}if(c.job.status==="completed"){Vt(),Jt(!1);const A=c.job.report_summary?.run_id??c.job.run_id;await Ht({keepSelection:!0,preferredRunId:A||fe,preferredCaseId:gt}),await wt(),ke(null);return}if(c.job.status==="failed"){Vt(),Jt(!1),Be(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),le(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}Vt(),we.current=window.setTimeout(()=>{Zn(a)},500)}catch(c){Vt(),Jt(!1);const y=c instanceof Error?c.message:String(c);Be(`Запуск прогонов: ${y}`),le(`Autogen async status error: ${y}`)}},[wt,Ht,le,me,fe,Vt]),d=x.useCallback(async()=>{Vt(),Jt(!0),Be("");try{const a=Rt;if(!a)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const c=xe.map(_r=>_r.trim()).filter(_r=>_r.length>0);if(c.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const y=I.useMock==="true",A=Vi(z),be=(await Ce.startEvalRunAsync({connection:i,prompts:p,promptVersion:m,mode:"single-pass-strict",caseSetFile:a.saved_case_set_file??void 0,useMock:y,evalTarget:"assistant_stage1",questions:c,analysisDate:A||void 0})).job;ke(be);const on=il(be.job_id),jn=no(be,gt);Re(on),D(jn.caseId),se(jn.detail),re(jn.dialog),le(`Запущен async-прогон job=${be.job_id}, run_id=${be.run_id}, вопросов=${c.length}`+(a.saved_case_set_file?`, base_case_set=${a.saved_case_set_file}`:"")+(A?`, analysis_date=${A}`:", analysis_date=current_state")),Zn(be.job_id)}catch(a){const c=a instanceof Error?a.message:String(a);Be(`Запуск прогонов: ${c}`),le(`Autogen run error: ${c}`),Jt(!1)}},[z,m,i,xe,I.useMock,le,Zn,p,Rt,Vt]),P=x.useCallback(a=>{if(a.role!=="assistant")return;const c=a.case_id??me,y=a.case_message_index??a.message_index;ot({open:!0,caseId:c,caseMessageIndex:y,messageIndex:a.message_index,rating:a.annotation?.rating??3,comment:a.annotation?.comment??"",manualCaseDecision:a.annotation?.manual_case_decision??sl,annotationAuthor:a.annotation?.annotation_author??h.generatedBy,saving:!1,error:""})},[h.generatedBy,me]),k=x.useCallback(a=>{ot(c=>c.saving&&!a?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:sl,annotationAuthor:h.generatedBy,saving:!1,error:""})},[h.generatedBy]),ye=x.useCallback(async()=>{const a=fe,c=ue.caseId,y=ue.caseMessageIndex;if(!(!a||!c||y<0)){if(js(a)){ot(A=>({...A,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ue.comment.trim()){ot(A=>({...A,error:"Добавьте комментарий."}));return}ot(A=>({...A,saving:!0,error:""}));try{await Ce.saveAutoRunAnnotation({run_id:a,case_id:c,message_index:y,rating:ue.rating,comment:ue.comment.trim(),manual_case_decision:ue.manualCaseDecision,annotation_author:ue.annotationAuthor.trim()||void 0}),k({force:!0}),Promise.all([Tt(a,me),At(),dt()]).catch(A=>{const pe=A instanceof Error?A.message:String(A);Be(`Обновление после комментария: ${pe}`),le(`Comment refresh error: ${pe}`)})}catch(A){ot(pe=>({...pe,saving:!1,error:A instanceof Error?A.message:String(A)}))}}},[k,ue.annotationAuthor,ue.caseId,ue.caseMessageIndex,ue.comment,ue.manualCaseDecision,ue.rating,At,dt,Tt,le,me,fe]),er=x.useCallback(a=>a.role==="assistant",[]),Hn=x.useCallback(a=>a.role==="assistant"&&xn.has(a.message_id),[xn]),ro=x.useCallback((a,c)=>{if(a.role!=="assistant")return;const y=st.trim(),A=String(a.session_id??"").trim();if(!(y||A)){Nt("Сначала получите ответ ассистента в активной сессии.");return}!y&&A&&gn(A);const be=xn.get(a.message_id)??null;Nt(""),_t({open:!0,messageIndex:c,rating:be?.rating??3,comment:be?.comment??"",annotationAuthor:be?.annotation_author??"manual_reviewer",saving:!1,error:""})},[xn,st]),Ns=x.useCallback(async()=>{if(ve.messageIndex<0)return;if(!ve.comment.trim()){_t(y=>({...y,error:"Добавьте комментарий."}));return}const a=vn[ve.messageIndex]??null,c=st.trim()||(a?.role==="assistant"?String(a.session_id??"").trim():"");if(!c){_t(y=>({...y,error:"Сессия ассистента не найдена."}));return}_t(y=>({...y,saving:!0,error:""}));try{const y=await Ce.saveAssistantAnnotation({session_id:c,message_index:ve.messageIndex,rating:ve.rating,comment:ve.comment.trim(),annotation_author:ve.annotationAuthor.trim()||void 0});Ct(A=>{const pe=[...A],be=pe.findIndex(on=>on.annotation_id===y.annotation.annotation_id);return be>=0?pe[be]=y.annotation:pe.unshift(y.annotation),pe.sort((on,jn)=>Date.parse(jn.updated_at)-Date.parse(on.updated_at))}),Mt({force:!0})}catch(y){const A=y instanceof Error?y.message:String(y);_t(pe=>({...pe,saving:!1,error:A}))}},[ve.annotationAuthor,ve.comment,ve.messageIndex,ve.rating,vn,st,Mt]),Or=x.useCallback(a=>{Pe(c=>c.map(y=>y.annotation_id===a.annotation_id?{...y,...a}:y)),re(c=>c&&{...c,annotations:c.annotations.map(y=>y.annotation_id===a.annotation_id?a:y),messages:c.messages.map(y=>!y.annotation||y.annotation.annotation_id!==a.annotation_id?y:{...y,commented:!0,annotation:a})})},[]),_n=x.useCallback(async(a,c)=>{if(a.annotation_id){if(js(a.run_id)){Be("Статус выполнения можно менять только для завершённых прогонов.");return}Bt(a.annotation_id);try{const y=await Ce.updateAutoRunAnnotation({annotation_id:a.annotation_id,resolved:c,resolved_by:h.generatedBy||void 0});Or(y.annotation),dt()}catch(y){const A=y instanceof Error?y.message:String(y);Be(`Смена статуса кейса: ${A}`),le(`Annotation resolve toggle error: ${A}`)}finally{Bt("")}}},[Or,h.generatedBy,dt,le]),Sn=x.useCallback(async a=>{Fe(a.annotation_id),await Tt(a.run_id,a.case_id),oe?.items.some(c=>c.run_id===a.run_id)||Be("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[oe?.items,Tt]);x.useEffect(()=>{Pt.current||(Pt.current=!0,Ht({keepSelection:!1}),wt(),xr(),dt())},[wt,xr,Ht,dt]),x.useEffect(()=>{Pt.current&&At()},[Ae,At]),x.useEffect(()=>{Fe(a=>J.length===0?"":J.some(c=>c.annotation_id===a)?a:J[0].annotation_id)},[J]),x.useEffect(()=>{de(a=>G.length===0?"":a&&G.some(c=>c.generation_id===a)?a:G[0].generation_id)},[G]),x.useEffect(()=>{if(!Rt){ge([]);return}ge([...Rt.questions])},[Rt?.generation_id]),x.useEffect(()=>{yt(String(I.limit))},[I.limit]),x.useEffect(()=>{xt(String(h.count))},[h.count]),x.useEffect(()=>{if(!st.trim()){Ct([]);return}Un(st)},[st,Un]),x.useEffect(()=>{if(!ee)return;const a=il(ee.job_id);if(fe!==a)return;const c=no(ee,me||gt);se(c.detail),re(c.dialog),D(c.caseId)},[ee,me,fe]),x.useEffect(()=>()=>{Vt()},[Vt]),x.useEffect(()=>{Q.length!==0&&C(a=>{let c=!1;const y={...a.personalityPrompts};for(const pe of Q)(typeof y[pe.id]!="string"||y[pe.id].trim().length===0)&&(y[pe.id]=pe.defaultPrompt,c=!0);let A=a.personalityId;return Q.some(pe=>pe.id===a.personalityId)||(A=Q[0].id,c=!0),c?{...a,personalityId:A,personalityPrompts:y}:a})},[Q]),x.useEffect(()=>{const a=localStorage.getItem(wc);if(a)try{const c=JSON.parse(a);if(c.filters){const y=c.filters;W(A=>({...A,...y,limit:typeof y.limit=="number"?Math.max(1,Math.min(500,y.limit)):A.limit}))}typeof c.analysisDate=="string"&&U(Vi(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&zn(Cc(c.autogenPersonalityPromptHeight)),c.autoGenSettings&&C(y=>{const A={...y.personalityPrompts},pe=c.autoGenSettings?.personalityPrompts??{};for(const[on,jn]of Object.entries(pe))typeof jn=="string"&&on.trim().length>0&&(A[on.trim()]=jn);const be=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():y.personalityId;return{...y,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"?c.autoGenSettings.mode:y.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):y.count,personalityId:be,personalityPrompts:A,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:y.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:y.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&De(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&We(c.hideResolvedAnnotations)}catch{}},[]);const wn=x.useCallback(()=>{const a={filters:I,analysisDate:z,autogenPersonalityPromptHeight:Et,autoGenSettings:{mode:h.mode,count:h.count,personalityId:h.personalityId,personalityPrompts:h.personalityPrompts,persistToEvalCases:h.persistToEvalCases,generatedBy:h.generatedBy},annotationDecisionFilter:Ae,hideResolvedAnnotations:$e};localStorage.setItem(wc,JSON.stringify(a))},[z,Ae,h,Et,I,$e]);return x.useEffect(()=>{const a=()=>{wn(),le("Сохранены настройки панели автопрогонов.")};return window.addEventListener(jc,a),()=>{window.removeEventListener(jc,a)}},[le,wn]),o.jsxs(Mn,{className:"autoruns-frame",title:"",hideHeader:!0,children:[o.jsxs("div",{className:"autoruns-columns",children:[o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Настройки"})}),o.jsx("h4",{children:"Настройки выборки"}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата с",o.jsx("input",{type:"datetime-local",value:I.fromLocal,onChange:a=>W(c=>({...c,fromLocal:a.target.value}))})]}),o.jsxs("label",{children:["Дата по",o.jsx("input",{type:"datetime-local",value:I.toLocal,onChange:a=>W(c=>({...c,toLocal:a.target.value}))})]}),o.jsxs("label",{children:["Целевой контур",o.jsxs("select",{value:I.target,onChange:a=>W(c=>({...c,target:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(oe?.available.targets??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Режим",o.jsxs("select",{value:I.mode,onChange:a=>W(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(oe?.available.modes??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Использовать mock",o.jsxs("select",{value:I.useMock,onChange:a=>W(c=>({...c,useMock:a.target.value})),children:[o.jsx("option",{value:"any",children:"любой"}),o.jsx("option",{value:"true",children:"да"}),o.jsx("option",{value:"false",children:"нет"})]})]}),o.jsxs("label",{children:["Лимит",o.jsx("input",{type:"number",min:1,max:500,value:Yn,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&yt(c)},onBlur:a=>Zr(a.target.value),onKeyDown:a=>{a.key==="Enter"&&Zr(a.target.value)}})]}),o.jsxs("label",{className:"full-width",children:["Версия промпта содержит",o.jsx("input",{value:I.promptContains,onChange:a=>W(c=>({...c,promptContains:a.target.value})),placeholder:"normalizer_v2_0_2 / address_query_runtime_v1",list:"autoruns-prompt-versions"})]})]}),o.jsx("datalist",{id:"autoruns-prompt-versions",children:(oe?.available.prompt_versions??[]).map(a=>o.jsx("option",{value:a},a))}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Xt,onClick:()=>{Ht({keepSelection:!1})},children:Xt?"Обновляю...":"Применить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{W({...bi,fromLocal:Nc()}),Be("")},children:"Сбросить фильтры"})]}),o.jsx("h4",{children:"Контур генерации"}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Провайдер:"}),o.jsx("strong",{children:i.llmProvider})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Модель:"}),o.jsx("strong",{children:i.model||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт ассистента:"}),o.jsx("strong",{children:m})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт декомпозиции:"}),o.jsx("strong",{children:R})]})]}),o.jsx("h4",{children:"Автогенерация вопросов"}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Режим генерации",o.jsxs("select",{value:h.mode,onChange:a=>C(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"codex_creative",children:"codex_creative"}),o.jsx("option",{value:"qwen_seed",children:"qwen_seed"})]})]}),o.jsxs("label",{children:["Кол-во",o.jsx("input",{type:"number",min:1,max:200,value:Jr,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&xt(c)},onBlur:a=>es(a.target.value),onKeyDown:a=>{a.key==="Enter"&&es(a.target.value)}})]}),o.jsxs("label",{children:["Личность автогенерации",o.jsx("select",{value:h.personalityId,onChange:a=>C(c=>({...c,personalityId:a.target.value})),children:Q.map(a=>o.jsx("option",{value:a.id,children:a.label},a.id))})]}),o.jsxs("label",{children:["Кто генерирует",o.jsx("input",{value:h.generatedBy,onChange:a=>C(c=>({...c,generatedBy:a.target.value})),placeholder:"manual_reviewer"})]}),o.jsxs("label",{className:"full-width",children:["Промпт личности",o.jsx("textarea",{className:"autoruns-personality-prompt",value:h.personalityPrompts[h.personalityId]??"",onChange:a=>C(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:a.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${Et}px`},onMouseUp:Bn,onTouchEnd:Bn})]}),o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:h.persistToEvalCases,onChange:a=>C(c=>({...c,persistToEvalCases:a.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата анализа (срез)",o.jsx("input",{type:"date",value:z,onChange:a=>U(Vi(a.target.value))})]}),o.jsx("div",{className:"button-row",children:o.jsx("button",{type:"button",className:"tab",disabled:!z,onClick:()=>U(""),children:"Сбросить дату среза"})})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:An,onClick:()=>{zr()},children:An?"Генерирую...":"Сгенерировать пачку"}),o.jsx("button",{type:"button",className:"tab",disabled:mn,onClick:()=>{wt()},children:mn?"Обновляю...":"Обновить историю"}),o.jsx("button",{type:"button",className:"autoruns-run-launch-btn",disabled:dr||xe.length===0,onClick:()=>{d()},children:dr?"Запускаю...":"Запустить прогоны"})]}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{className:"full-width",children:["Кейс-сет для запуска",o.jsxs("select",{value:ce,onChange:a=>de(a.target.value),disabled:G.length===0,children:[G.length===0?o.jsx("option",{value:"",children:"нет генераций"}):null,G.map(a=>o.jsxs("option",{value:a.generation_id,children:[ur(a.created_at)," | ",a.mode," | ",a.count," | ",a.saved_case_set_file??"без файла"]},a.generation_id))]})]})}),o.jsxs("div",{className:"autoruns-generated-questions",children:[o.jsxs("div",{className:"autoruns-generated-questions-head",children:[o.jsxs("strong",{children:["Вопросы к запуску: ",xe.length]}),o.jsx("button",{type:"button",className:"tab",onClick:()=>ge([...Rt?.questions??[]]),disabled:!Rt,children:"Восстановить"})]}),xe.length===0?o.jsx("p",{className:"muted",children:"Список вопросов пуст. Сгенерируйте пачку или восстановите из выбранной генерации."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:xe.map((a,c)=>o.jsxs("div",{className:"autoruns-generated-question-item",children:[o.jsxs("span",{children:[c+1,". ",a]}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onClick:()=>ge(y=>y.filter((A,pe)=>pe!==c)),title:"Удалить вопрос из запуска","aria-label":"Удалить вопрос из запуска",children:"+"})]},`${c}-${a.slice(0,24)}`))})]}),o.jsx("p",{className:"muted",children:"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."}),o.jsxs("div",{className:"autoruns-autogen-list",children:[mn?o.jsx("p",{className:"muted",children:"Загружаю историю автогенераций..."}):null,!mn&&G.length===0?o.jsx("p",{className:"muted",children:"История автогенераций пока пустая."}):null,G.slice(0,30).map(a=>o.jsxs("article",{className:ce===a.generation_id?"autoruns-autogen-item selected":"autoruns-autogen-item",onClick:()=>de(a.generation_id),children:[o.jsxs("header",{children:[o.jsx("strong",{children:ur(a.created_at)}),o.jsx("span",{children:a.mode})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["id=",a.generation_id," | count=",a.count]}),o.jsxs("div",{className:"autoruns-run-meta",children:["домен=",a.domain??"общий",a.generated_by?` | автор=${a.generated_by}`:""]}),a.saved_case_set_file?o.jsxs("div",{className:"autoruns-run-meta",children:["кейс-сет=",a.saved_case_set_file]}):null,(a.questions??[]).length>0?o.jsx("p",{children:a.questions[0]}):null]},a.generation_id))]}),o.jsxs("details",{className:"autoruns-prompt-details",children:[o.jsx("summary",{children:"Копия активного промпта (только чтение)"}),o.jsxs("label",{children:["Системный",o.jsx("textarea",{readOnly:!0,value:p.systemPrompt})]}),o.jsxs("label",{children:["Разработчика",o.jsx("textarea",{readOnly:!0,value:p.developerPrompt})]}),o.jsxs("label",{children:["Доменный",o.jsx("textarea",{readOnly:!0,value:p.domainPrompt})]}),o.jsxs("label",{children:["Заметки по схеме",o.jsx("textarea",{readOnly:!0,value:p.schemaNotes})]}),o.jsxs("label",{children:["Примеры few-shot",o.jsx("textarea",{readOnly:!0,value:p.fewShotExamples})]})]}),hn?o.jsx("p",{className:"error-text",children:hn}):null]}),o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Выдача прогонов"})}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Всего"}),o.jsx("strong",{children:(oe?.stats.runs_total??0)+(ee?1:0)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний score"}),o.jsx("strong",{children:ll(oe?.stats.avg_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:oe?Ec(oe.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Блокеры"}),o.jsx("strong",{children:oe?.stats.blocking_runs??0})]})]}),o.jsxs("div",{className:"autoruns-run-list",children:[Fn.map(a=>o.jsxs("button",{type:"button",className:fe===a.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{Tt(a.run_id)},children:[o.jsxs("div",{className:"autoruns-run-head",children:[o.jsx("strong",{children:ur(a.run_timestamp)}),o.jsx("span",{children:em(a.eval_target)})]}),o.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[o.jsx("span",{children:a.run_id}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{ct(c,a.run_id)},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),ct(c,a.run_id))},title:"Скопировать run id","aria-label":`Скопировать run id ${a.run_id}`,children:o.jsx(rm,{})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["режим=",a.mode??"нет данных"," | mock=",String(a.use_mock)]}),o.jsxs("div",{className:"autoruns-run-meta",children:["analysis_date=",a.analysis_date??"current_state"]}),a.llm_provider||a.model?o.jsxs("div",{className:"autoruns-run-meta",children:["llm=",a.llm_provider??"нет данных"," | модель=",a.model??"нет данных"]}):null,o.jsxs("div",{className:"autoruns-run-meta",children:["промпт=",a.prompt_version??"нет данных"]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["оценка: ",ll(a.score_index)]}),o.jsxs("span",{children:["закрыто/открыто: ",a.closed_cases,"/",a.open_cases]})]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["блокеры: ",a.blocking_failures]}),o.jsxs("span",{children:["качество: ",a.quality_failures]})]})]},a.run_id)),Fn.length===0?o.jsx("p",{className:"muted",children:"За выбранный диапазон прогонов нет."}):null]})]}),o.jsxs("section",{className:"autoruns-col",children:[o.jsxs("div",{className:"autoruns-col-header",children:[o.jsx("h3",{children:"Диалог прогона"}),o.jsxs("div",{className:"autoruns-dialog-toolbar",children:[o.jsxs("label",{children:["Прогон",o.jsx("select",{value:fe,onChange:a=>{const c=a.target.value;Tt(c)},children:Fn.map(a=>o.jsxs("option",{value:a.run_id,children:[ur(a.run_timestamp)," | ",a.run_id]},a.run_id))})]}),o.jsxs("label",{children:["Кейс",o.jsxs("select",{value:me,onChange:a=>{const c=a.target.value;D(c),fe&&c&&bn(fe,c)},children:[(te?.cases.length??0)>0?o.jsx("option",{value:gt,children:"ВСЕ кейсы подряд"}):null,(te?.cases??[]).map(a=>o.jsxs("option",{value:a.case_id,children:[a.case_id," | ",a.status]},a.case_id))]})]})]})]}),o.jsxs("div",{className:"autoruns-case-list",children:[(te?.cases.length??0)>0?o.jsxs("button",{type:"button",className:me===gt?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{D(gt),fe&&bn(fe,gt)},children:[o.jsx("span",{children:"ВСЕ кейсы подряд"}),o.jsx("span",{children:te?.cases.length})]},gt):null,(te?.cases??[]).map(a=>o.jsxs("button",{type:"button",className:me===a.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{D(a.case_id),fe&&bn(fe,a.case_id)},children:[o.jsx("span",{children:a.case_id}),o.jsxs("span",{children:[a.status,a.commented_count>0?` | комм=${a.commented_count}`:""]})]},a.case_id))]}),o.jsxs("div",{className:"autoruns-dialog-view",children:[mr||fr?o.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!mr&&!fr&&(q?.messages.length??0)===0?o.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(q?.messages??[]).map((a,c)=>{const y=a.role==="assistant"?"assistant":"user";return o.jsxs("article",{className:`autoruns-msg ${y}`,children:[o.jsxs("header",{children:[o.jsx("strong",{children:y==="assistant"?"Система":"Модель/вопрос"}),o.jsxs("div",{className:"autoruns-msg-head-actions",children:[a.case_id?o.jsx("span",{className:"autoruns-msg-case-tag",children:a.case_id}):null,o.jsx("span",{children:a.created_at?ur(a.created_at):"нет данных"}),y==="assistant"&&!js(fe)?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:a.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>P(a),title:"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b","aria-label":"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b",children:o.jsx(nm,{commented:a.commented})}),a.annotation?o.jsx("button",{type:"button",className:a.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{_n(a.annotation,!a.annotation.resolved)},disabled:pr===a.annotation.annotation_id,title:a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Mc,{resolved:a.annotation.resolved})}):null]}):null]})]}),o.jsx("p",{children:a.text}),y==="assistant"&&a.annotation?o.jsxs("div",{className:"autoruns-msg-annotation",children:[o.jsx("strong",{children:Qi(a.annotation.rating)}),o.jsx("span",{children:a.annotation.comment}),o.jsxs("span",{className:"muted",children:[a.annotation.manual_case_decision,a.annotation.annotation_author?` | ${a.annotation.annotation_author}`:""]})]}):null,(a.trace_id||a.reply_type)&&o.jsxs("footer",{children:[a.trace_id?o.jsxs("span",{children:["trace=",a.trace_id]}):null,a.reply_type?o.jsxs("span",{children:["reply_type=",a.reply_type]}):null]})]},a.message_id??`${y}-${c}`)})]})]}),j?o.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:o.jsx(Fc,{sessionId:st,conversation:vn,inputValue:Dn,onInputChange:rn,selectedContextChip:bt,onSelectContextChip:vt,onClearContextChip:()=>vt(null),useMock:Jn,onUseMockChange:Ke,onSend:Cs,onClear:St,busy:hr,statusText:gr,errorMessage:vr,showCommentAction:!0,onCommentAssistantMessage:ro,isAssistantMessageCommented:Hn,canCommentAssistantMessage:er})}):null,T?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Режим декомпозиции"})}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"кейс:"}),o.jsx("strong",{children:On?.case_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"домен:"}),o.jsx("strong",{children:On?.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"класс запроса:"}),o.jsx("strong",{children:On?.query_class??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"trace:"}),o.jsx("strong",{children:On?.trace_id??"нет данных"})]})]}),o.jsx("h4",{children:"Шаги декомпозиции"}),(q?.decomposition.length??0)>0?o.jsx("ol",{className:"autoruns-decomposition-list",children:(q?.decomposition??[]).map((a,c)=>o.jsx("li",{children:a},`${c}-${a.slice(0,24)}`))}):o.jsx("p",{className:"muted",children:"В логах кейса нет явной декомпозиции."})]}):null,$?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Прогресс / регресс"})}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Последний score"}),o.jsx("strong",{children:ll(oe?.stats.latest_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Предыдущий"}),o.jsx("strong",{children:ll(oe?.stats.previous_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:oe?Ec(oe.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Пробелы качества"}),o.jsx("strong",{children:oe?.stats.quality_gap_runs??0})]})]}),o.jsx("h4",{children:"Покрытие доменов (история)"}),Pc(oe?.stats.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),Pc(te?.coverage.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),Yt?o.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,Yt?null:o.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(Ft?.post_analysis.stats.by_queue??{}).map(([a,c])=>o.jsxs("div",{children:[o.jsx("span",{children:a}),o.jsx("strong",{children:c})]},a))}),o.jsxs("div",{className:"autoruns-autogen-list",children:[(Ft?.post_analysis.recommended_regression_candidates??[]).slice(0,12).map(a=>o.jsxs("article",{className:"autoruns-autogen-item",children:[o.jsxs("header",{children:[o.jsx("strong",{children:a.manual_case_decision}),o.jsxs("span",{children:[a.rating,"/5"]})]}),o.jsxs("div",{className:"autoruns-run-meta",children:[a.domain??"неизвестно"," / ",a.query_class??"неизвестно"]}),o.jsx("p",{children:a.comment})]},a.annotation_id)),!Yt&&(Ft?.post_analysis.recommended_regression_candidates.length??0)===0?o.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Y?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Комментарии"})}),o.jsx("h4",{children:"Размеченные ответы"}),o.jsxs("div",{className:"autoruns-comment-filter-row",children:[o.jsxs("label",{children:["Фильтр решений",o.jsxs("select",{value:Ae,onChange:a=>De(a.target.value),children:[o.jsx("option",{value:"all",children:"все"}),(rt.length>0?rt:Ge?.enum??[]).map(a=>o.jsx("option",{value:a,children:String(Ge?.labels?.[a]??a)},a))]})]}),o.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>We(a=>!a),children:$e?"Показать выполненные":"Скрыть выполненные"})]}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Комментариев"}),o.jsx("strong",{children:ut.length})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний рейтинг"}),o.jsx("strong",{children:yr===null?"нет данных":`${yr.toFixed(2)} / 5`})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Последний"}),o.jsx("strong",{children:ut.length>0?ur(ut[0].updated_at):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Статус"}),o.jsx("strong",{children:Zt?"обновляю":"готово"})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Zt,onClick:()=>{At()},children:Zt?"Обновляю...":"Обновить список"}),o.jsx("button",{type:"button",className:"tab",disabled:Yt,onClick:()=>{dt()},children:Yt?"Идет пост-анализ...":"Обновить пост-анализ"})]}),o.jsxs("div",{className:"autoruns-comments-list",children:[Zt?o.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!Zt&&ut.length===0?o.jsx("p",{className:"muted",children:Se.length===0&&nn.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,ut.map(a=>{if(a.source==="assistant_live"){const y=a.assistant;return o.jsxs("article",{className:"autoruns-comment-item",children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Qi(y.rating)}),o.jsx("div",{className:"autoruns-comment-head-actions",children:o.jsx("span",{children:ur(y.updated_at)})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",y.session_id]}),o.jsxs("div",{className:"autoruns-run-meta",children:["msg=",y.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",y.annotation_author?` | author=${y.annotation_author}`:""]}),y.context.question_text?o.jsxs("p",{children:["Q: ",y.context.question_text]}):null,y.context.answer_text?o.jsxs("p",{children:["A: ",y.context.answer_text]}):null,o.jsx("p",{children:y.comment})]},a.key)}const c=a.autorun;return o.jsxs("article",{className:Te===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{Sn(c)},role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),Sn(c))},children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Qi(c.rating)}),o.jsxs("div",{className:"autoruns-comment-head-actions",children:[o.jsx("span",{children:ur(c.updated_at)}),o.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:y=>{y.preventDefault(),y.stopPropagation(),_n(c,!c.resolved)},disabled:pr===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Mc,{resolved:c.resolved})})]})]}),o.jsx("div",{className:"autoruns-run-meta",children:c.run_id}),o.jsxs("div",{className:"autoruns-run-meta",children:["case=",c.case_id," | msg=",c.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["decision=",c.manual_case_decision,c.annotation_author?` | author=${c.annotation_author}`:""]}),c.resolved_at?o.jsxs("div",{className:"autoruns-run-meta",children:["выполнено",": ",ur(c.resolved_at),c.resolved_by?` | by=${c.resolved_by}`:""]}):null,c.context.question_text?o.jsxs("p",{children:["Q: ",c.context.question_text]}):null,c.context.answer_text?o.jsxs("p",{children:["A: ",c.context.answer_text]}):null,o.jsx("p",{children:c.comment})]},a.key)})]}),Ne?o.jsxs(o.Fragment,{children:[o.jsx("h4",{children:"Тех-контекст брака"}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"trace:"}),o.jsx("strong",{children:Ne.technical_context.trace_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"reply_type:"}),o.jsx("strong",{children:Ne.technical_context.reply_type??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"domain:"}),o.jsx("strong",{children:Ne.technical_context.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"query_class:"}),o.jsx("strong",{children:Ne.technical_context.query_class??"нет данных"})]})]}),o.jsx("h4",{children:"JSON разбор"}),o.jsx(Gt,{value:{annotation_id:Ne.annotation_id,run_id:Ne.run_id,case_id:Ne.case_id,message_index:Ne.message_index,rating:Ne.rating,comment:Ne.comment,manual_case_decision:Ne.manual_case_decision,annotation_author:Ne.annotation_author,resolved:Ne.resolved,resolved_at:Ne.resolved_at,resolved_by:Ne.resolved_by,context:Ne.context,technical_context:Ne.technical_context,case_summary:Ne.case_summary?{case_id:Ne.case_summary.case_id,domain:Ne.case_summary.domain,query_class:Ne.case_summary.query_class,checks:Ne.case_summary.checks,metric_subscores:Ne.case_summary.metric_subscores}:null}})]}):null]}):null]}),ve.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Mt()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),Xr?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:Xr.text})]}):null,Ie?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:Ie.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа ассистента",children:[1,2,3,4,5].map(a=>o.jsx("button",{type:"button",className:ve.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>_t(c=>({...c,rating:a})),disabled:ve.saving,"aria-label":`Оценка ${a}`,children:ve.rating>=a?"●":"○"},a))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ve.annotationAuthor,onChange:a=>_t(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ve.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ve.comment,onChange:a=>_t(c=>({...c,comment:a.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:ve.saving})]}),ve.error?o.jsx("p",{className:"error-text",children:ve.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{Ns()},disabled:ve.saving,children:ve.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Mt(),disabled:ve.saving,children:"Отмена"})]})]})}):null,ue.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&k()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу системы"}),o.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),$n?o.jsxs(o.Fragment,{children:[o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:Yr?.text??"Вопрос в диалоге не найден."})]}),o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ системы"}),o.jsx("p",{className:"autoruns-comment-quote",children:$n.text})]})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(a=>o.jsx("button",{type:"button",className:ue.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>ot(c=>({...c,rating:a})),disabled:ue.saving,"aria-label":`Оценка ${a}`,children:ue.rating>=a?"●":"○"},a))}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Решение по кейсу",o.jsx("select",{value:ue.manualCaseDecision,onChange:a=>ot(c=>({...c,manualCaseDecision:a.target.value})),disabled:ue.saving,children:(rt.length>0?rt:Ge?.enum??[sl]).map(a=>o.jsx("option",{value:a,children:String(Ge?.labels?.[a]??a)},a))})]}),o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ue.annotationAuthor,onChange:a=>ot(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ue.saving})]})]}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ue.comment,onChange:a=>ot(c=>({...c,comment:a.target.value})),placeholder:"Почему ответ бракованный, что именно пошло не так, какие технические детали проверить.",rows:4,disabled:ue.saving})]}),ue.error?o.jsx("p",{className:"error-text",children:ue.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ye()},disabled:ue.saving,children:ue.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>k(),disabled:ue.saving,children:"Отмена"})]})]})}):null]})}function Ac({value:i,modelOptions:p,modelsBusy:m,onChange:R,onReloadModels:j,onTestConnection:T,onSaveLocalConfig:$,lastStatus:Y,busy:F}){const I=i.llmProvider==="local",W=p.includes(i.model),[z,U]=x.useState(String(i.temperature)),[oe,Me]=x.useState(String(i.maxOutputTokens));x.useEffect(()=>{U(String(i.temperature))},[i.temperature]),x.useEffect(()=>{Me(String(i.maxOutputTokens))},[i.maxOutputTokens]);const te=q=>{const re=q.replace(",",".").trim();if(!re){U(String(i.temperature));return}const Se=Number(re);if(!Number.isFinite(Se)){U(String(i.temperature));return}R({...i,temperature:Se}),U(String(Se))},se=q=>{const re=q.trim();if(!re){Me(String(i.maxOutputTokens));return}const Se=Number.parseInt(re,10);if(!Number.isFinite(Se)||Se<=0){Me(String(i.maxOutputTokens));return}R({...i,maxOutputTokens:Se}),Me(String(Se))};return o.jsxs(Mn,{title:"LLM Connection",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:o.jsx("span",{className:"status-chip",children:Y||"Status: not checked"}),children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{children:["Provider",o.jsxs("select",{value:i.llmProvider,onChange:q=>{const re=q.target.value==="local"?"local":"openai";R({...i,llmProvider:re,baseUrl:re==="local"?"http://127.0.0.1:1234/v1":"https://api.openai.com/v1"})},children:[o.jsx("option",{value:"openai",children:"OpenAI (token)"}),o.jsx("option",{value:"local",children:"Local (LM Studio / OpenAI-compatible)"})]})]}),o.jsxs("label",{children:["Model",o.jsxs("select",{value:W?i.model:"__manual__",onChange:q=>{const re=q.target.value;re!=="__manual__"&&R({...i,model:re})},children:[o.jsx("option",{value:"__manual__",children:"Manual input"}),p.map(q=>o.jsx("option",{value:q,children:q},q))]})]}),o.jsxs("label",{children:["Model ID (manual)",o.jsx("input",{value:i.model,onChange:q=>R({...i,model:q.target.value}),placeholder:"qwen2.5-14b-instruct or lmstudio loaded model id"})]}),I?null:o.jsxs("label",{className:"full-width",children:["OpenAI API Key",o.jsx("input",{type:"password",value:i.apiKey,onChange:q=>R({...i,apiKey:q.target.value}),placeholder:"sk-..."})]}),o.jsxs("label",{className:I?"full-width":void 0,children:[I?"Local server base URL":"Base URL",o.jsx("input",{value:i.baseUrl,onChange:q=>R({...i,baseUrl:q.target.value}),placeholder:I?"http://127.0.0.1:1234/v1":"https://api.openai.com/v1"})]}),o.jsxs("label",{children:["Temperature",o.jsx("input",{type:"number",step:"0.1",value:z,onChange:q=>U(q.target.value),onBlur:q=>te(q.target.value),onKeyDown:q=>{q.key==="Enter"&&te(q.target.value)}})]}),o.jsxs("label",{children:["Max output tokens",o.jsx("input",{type:"number",value:oe,onChange:q=>Me(q.target.value),onBlur:q=>se(q.target.value),onKeyDown:q=>{q.key==="Enter"&&se(q.target.value)}})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>$(),children:"Save local config"}),o.jsx("button",{type:"button",onClick:()=>j(),disabled:F||m,children:m?"Loading models...":"Load model list"}),o.jsx("button",{type:"button",onClick:()=>T(),disabled:F,children:F?"Checking...":"Test connection"})]})]})}function om({items:i,onRefresh:p,onOpenTrace:m}){return o.jsx(Mn,{title:"История нормализаций",subtitle:"Короткий вопрос, confidence, route hint и статус валидации.",actions:o.jsx("button",{type:"button",onClick:()=>p(),children:"Обновить"}),children:o.jsxs("div",{className:"history-list",children:[i.length===0?o.jsx("p",{className:"muted",children:"История пока пустая."}):null,i.map(R=>o.jsxs("button",{type:"button",className:"history-item",onClick:()=>m(R.trace_id),children:[o.jsxs("div",{className:"history-row",children:[o.jsx("strong",{children:R.route_hint??"route: n/a"}),o.jsx("span",{children:R.validation_passed?"schema: ok":"schema: fail"})]}),o.jsx("p",{children:R.question_short}),o.jsxs("div",{className:"history-row",children:[o.jsx("span",{children:R.model}),o.jsx("span",{children:new Date(R.timestamp).toLocaleString("ru-RU")})]})]},R.trace_id))]})})}function cr(i){return i==null||i===""?"—":String(i)}function lm({result:i}){return o.jsx(Mn,{title:"Runtime метрики",subtitle:"trace_id, токены, latency и статус валидации.",children:o.jsxs("div",{className:"metrics-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"trace_id"}),o.jsx("strong",{children:cr(i?.trace_id)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"request_started_at"}),o.jsx("strong",{children:cr(i?new Date(Date.now()-i.latency_ms).toISOString():null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"request_finished_at"}),o.jsx("strong",{children:cr(i?new Date().toISOString():null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"latency_ms"}),o.jsx("strong",{children:cr(i?.latency_ms)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"input_tokens"}),o.jsx("strong",{children:cr(i?.usage?.input_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"output_tokens"}),o.jsx("strong",{children:cr(i?.usage?.output_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"total_tokens"}),o.jsx("strong",{children:cr(i?.usage?.total_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"validation_status"}),o.jsx("strong",{children:i?.validation?.passed?"passed":"failed"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"prompt_version"}),o.jsx("strong",{children:cr(i?.prompt_version)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"schema_version"}),o.jsx("strong",{children:cr(i?.schema_version)})]})]})})}const im={normalized:"Normalized JSON",fragments:"Fragment View",scope:"Scope View",flags:"Flags View",route:"Route Simulation",raw:"Raw model output",validation:"Validation",logs:"Logs"};function am(i){return i&&typeof i=="object"?i:null}function um({tab:i,onTabChange:p,result:m,appLogs:R}){const j=["normalized","fragments","scope","flags","route","raw","validation","logs"],T=am(m?.normalized),$=String(T?.schema_version??""),Y=$==="normalized_query_v2"||$==="normalized_query_v2_0_1"||$==="normalized_query_v2_0_2",F=Y?{fragments:T?.fragments??[],discarded_fragments:T?.discarded_fragments??[]}:{note:"Fragment View доступен для normalized_query_v2."},I=Y?{message_in_scope:T?.message_in_scope??null,scope_confidence:T?.scope_confidence??null,contains_multiple_tasks:T?.contains_multiple_tasks??null,global_notes:T?.global_notes??null}:{note:"Scope View доступен для normalized_query_v2."},W=Y?Array.isArray(T?.fragments)?(T?.fragments).map(z=>({fragment_id:z.fragment_id??null,domain_relevance:z.domain_relevance??null,candidate_labels:z.candidate_labels??[],execution_readiness:z.execution_readiness??null,clarification_reason:z.clarification_reason??null,soft_assumption_used:z.soft_assumption_used??[],route_status:z.route_status??null,no_route_reason:z.no_route_reason??null,flags:z.flags??{}})):[]:{note:"Flags View доступен для normalized_query_v2."};return o.jsxs(Mn,{title:"Выходные данные",subtitle:"Structured output и диагностические вкладки.",children:[o.jsx("div",{className:"tab-row",children:j.map(z=>o.jsx("button",{type:"button",className:i===z?"tab active":"tab",onClick:()=>p(z),children:im[z]},z))}),i==="normalized"?o.jsx(Gt,{value:m?.normalized??{note:"Нет данных."}}):null,i==="fragments"?o.jsx(Gt,{value:F}):null,i==="scope"?o.jsx(Gt,{value:I}):null,i==="flags"?o.jsx(Gt,{value:W}):null,i==="route"?o.jsx(Gt,{value:m?.route_hint_summary??{note:"Нет данных."}}):null,i==="raw"?o.jsx(Gt,{value:m?.raw_model_output??{note:"Нет данных."}}):null,i==="validation"?o.jsx(Gt,{value:m?.validation??{note:"Нет данных."}}):null,i==="logs"?o.jsx(Gt,{value:R}):null]})}function Tc({value:i,onChange:p,presets:m,selectedPresetId:R,onSelectPreset:j,onLoadPreset:T,onSavePreset:$,onResetDefaults:Y,onDiffPrevious:F,presetName:I,onPresetNameChange:W,diffSummary:z}){return o.jsxs(Mn,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:[o.jsxs("div",{className:"prompt-manager-grid",children:[o.jsxs("label",{children:["Системный prompt",o.jsx("textarea",{value:i.systemPrompt,onChange:U=>p({...i,systemPrompt:U.target.value}),rows:6})]}),o.jsxs("label",{children:["Developer / Instruction prompt",o.jsx("textarea",{value:i.developerPrompt,onChange:U=>p({...i,developerPrompt:U.target.value}),rows:6})]}),o.jsxs("label",{children:["Domain prompt",o.jsx("textarea",{value:i.domainPrompt,onChange:U=>p({...i,domainPrompt:U.target.value}),rows:6})]}),o.jsxs("label",{children:["Schema notes",o.jsx("textarea",{value:i.schemaNotes,onChange:U=>p({...i,schemaNotes:U.target.value}),rows:6})]}),o.jsxs("label",{className:"full-width",children:["Few-shot examples",o.jsx("textarea",{value:i.fewShotExamples,onChange:U=>p({...i,fewShotExamples:U.target.value}),rows:8})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("select",{value:R,onChange:U=>j(U.target.value),children:[o.jsx("option",{value:"",children:"Выберите preset..."}),m.map(U=>o.jsx("option",{value:U.id,children:U.name},U.id))]}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Загрузить preset"}),o.jsx("input",{value:I,onChange:U=>W(U.target.value),placeholder:"Имя для сохранения"}),o.jsx("button",{type:"button",onClick:()=>$(),children:"Сохранить preset"}),o.jsx("button",{type:"button",onClick:()=>F(),children:"Diff с предыдущим"}),o.jsx("button",{type:"button",onClick:()=>Y(),children:"Сбросить к default"})]}),z?o.jsx("p",{className:"diff-summary",children:z}):null]})}function cm({value:i,onChange:p,onApplyBatchFormat:m,onNormalize:R,busy:j,useMock:T,onUseMockChange:$,errorMessage:Y}){return o.jsxs(Mn,{title:"Запрос пользователя",subtitle:"NDC semantic front-end: нормализуем, но не отвечаем за бухгалтерскую суть.",children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{className:"full-width",children:["Raw user question",o.jsx("textarea",{value:i.userQuestion,onChange:F=>p({...i,userQuestion:F.target.value}),rows:6,placeholder:"Например: По каким покупателям у нас на конец июня висят отгрузки без оплаты..."})]}),o.jsxs("label",{className:"full-width",children:["Batch queries (`;` separator)",o.jsx("textarea",{value:i.batchQuestionsRaw,onChange:F=>p({...i,batchQuestionsRaw:F.target.value}),onBlur:()=>m(),rows:8,placeholder:"Вопрос 1; Вопрос 2; Вопрос 3"})]}),o.jsxs("label",{children:["Optional period context",o.jsx("input",{value:i.periodHint,onChange:F=>p({...i,periodHint:F.target.value})})]}),o.jsxs("label",{children:["Optional business context",o.jsx("input",{value:i.businessContext,onChange:F=>p({...i,businessContext:F.target.value})})]}),o.jsxs("label",{children:["Optional expected route (eval)",o.jsx("input",{value:i.expectedRoute,onChange:F=>p({...i,expectedRoute:F.target.value})})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:T,onChange:F=>$(F.target.checked)}),"Mock-режим (без вызова OpenAI)"]}),o.jsx("button",{type:"button",onClick:()=>m(),disabled:j||!i.batchQuestionsRaw.trim(),children:"Применить `;` в переносы"}),o.jsx("button",{type:"button",onClick:()=>R(!1),disabled:j||!i.userQuestion.trim(),children:j?"Нормализуем...":"Normalize"}),o.jsx("button",{type:"button",onClick:()=>R(!0),disabled:j||!i.userQuestion.trim(),children:j?"Сохраняем...":"Normalize + Save as test case"})]}),Y?o.jsx("p",{className:"error-text",children:Y}):null]})}function dm({runs:i,selectedRunId:p,onSelectRun:m,onStartRun:R,onFinishRun:j,onRefreshRuns:T,onRunEval:$,onCopyEvalReport:Y,evalBusy:F,traceItems:I,evalReport:W}){return o.jsxs(Mn,{title:"NDC Run Monitor",subtitle:"Важно: кнопка Запустить run создает только run-сущность. Кнопка eval запускает batch-проверку normalizer v2.0.2.",children:[o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>R(),children:"Запустить run"}),o.jsx("button",{type:"button",onClick:()=>j(),disabled:!p,children:"Завершить выбранный run"}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Обновить runs"}),o.jsx("button",{type:"button",onClick:()=>$(),disabled:F,children:F?"Идет eval v2.0.2...":"Запустить eval v2.0.2"})]}),o.jsxs("div",{className:"runtime-stack",children:[o.jsxs("div",{className:"runtime-runs",children:[i.map(z=>o.jsxs("button",{type:"button",className:p===z.runId?"history-item selected":"history-item",onClick:()=>m(z.runId),children:[o.jsxs("div",{className:"history-row",children:[o.jsx("strong",{children:z.status}),o.jsx("span",{children:z.runId})]}),o.jsxs("div",{className:"history-row",children:[o.jsx("span",{children:z.sessionId}),o.jsx("span",{children:new Date(z.updatedAt).toLocaleString("ru-RU")})]})]},z.runId)),i.length===0?o.jsx("p",{className:"muted",children:"Нет активных запусков."}):null]}),o.jsxs("div",{className:"runtime-details",children:[o.jsx("h3",{children:"Trace выбранного run"}),o.jsx(Gt,{value:I}),o.jsxs("div",{className:"eval-report-wrap",children:[o.jsx("h3",{style:{marginTop:12},children:"Отчет eval"}),o.jsx(Gt,{value:W??{note:"Eval пока не запускался"}}),o.jsx("button",{type:"button",className:"copy-cube-button",title:"Скопировать отчет eval",onClick:()=>Y(),children:"⧉"})]})]})]})]})}const fm={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},Ic={systemPrompt:"Ты semantic-normalizer для бухгалтерского ассистента NDC. Возвращай только JSON по схеме normalized_query_v2_0_2.",developerPrompt:"Сначала делай decomposition сообщения на task fragments, затем определяй domain scope и route-critical flags. Для каждого fragment заполняй execution_readiness + route_status + no_route_reason. Если fragment routable, не оставляй его в no_route.",domainPrompt:"Контур: данные текущего предприятия в 1С/NDC. In-scope: документы, проводки, взаиморасчеты, остатки, периодное закрытие, аномалии и контрольные проверки. Out-of-scope: общая теория, законы и оффтоп.",schemaNotes:"schema_version: normalized_query_v2_0_2. Строгий JSON без дополнительных полей.",fewShotExamples:"Q: Проверь по поставщикам хвосты и разложи цепочку документов/оплат. => fragment in_scope, flags: multi_entity + chain_explanation. Q: Как вообще по ФСБУ? => out_of_scope/generic_accounting."},mm={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},Wi={colors:{backgroundRgb:"18, 18, 18",mainSurfaceRgb:"25, 25, 25",horizontalSurfaceRgb:"30, 30, 30",focusSurfaceRgb:"35, 35, 35",assistantChipRgb:"18, 18, 18",assistantChipHoverRgb:"44, 44, 44",assistantChipSelectedRgb:"167, 59, 255",assistantChipSelectedTextRgb:"240, 240, 240",activeRgb:"167, 59, 255",activeTextRgb:"240, 240, 240",textMainRgb:"240, 240, 240",textMutedRgb:"166, 166, 166",dangerRgb:"126, 126, 126",scrollbarTrackRgb:"20, 20, 20",scrollbarThumbRgb:"30, 30, 30",scrollbarThumbHoverRgb:"30, 50, 30"},layout:{modeColumnWidthPx:406,modeToggleWidthPx:188}},Lc="ndc_normalizer_session_config_v1",Dc="ndc_autoruns_layout_config_v1",pm="ndc-autoruns-save",Ki=["Анализ запроса","Получение данных","Подготовка ответа"],hm="assistant",qi="normalizer_v2_0_2",zc="address_query_runtime_v1",gm=["normalized","fragments","scope","flags","route","raw","validation","logs"],Gi="manual_reviewer";function vm(i){return`[${new Date().toLocaleTimeString("ru-RU")}] ${i}`}function ym(i,p){if(!p)return"Previous preset is not selected.";const R=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(j=>i[j]!==p[j]).map(j=>`${j}: ${Math.abs(i[j].length-p[j].length)} chars delta`);return R.length===0?"No changes against previous preset.":`Changed fields: ${R.length}. ${R.join(" | ")}`}function xm(i,p){const m=i.trim();if(!m)return"";if(!p)return m;const R=m.toLowerCase(),j=p.anchor_text.trim(),T=j.toLowerCase();return T&&R.includes(T)?m:`По выбранному объекту "${j}": ${m}`}function _m(){const[i,p]=x.useState(fm),[m,R]=x.useState(Ic),[j,T]=x.useState(mm),[$,Y]=x.useState(null),[F,I]=x.useState([]),[W,z]=x.useState([]),[U,oe]=x.useState("normalized"),[Me,te]=x.useState(!1),[se,q]=x.useState(!1),[re,Se]=x.useState([]),[Pe,Ae]=x.useState(""),[De,$e]=x.useState([]),[We,Ge]=x.useState(""),[Ze,rt]=x.useState("NDC custom preset"),[ie,Te]=x.useState(null),[Fe,fe]=x.useState(""),[Re,me]=x.useState(!1),[D,Q]=x.useState([]),[O,h]=x.useState(""),[C,G]=x.useState([]),[ae,ce]=x.useState(!1),[de,xe]=x.useState(null),[ge,ee]=x.useState(""),[ke,Ft]=x.useState(hm),[qn,An]=x.useState(!0),[Tn,dr]=x.useState(!0),[Jt,Yt]=x.useState(!0),[Gn,mn]=x.useState(!0),[Ut,Xt]=x.useState(!0),[pn,fr]=x.useState(!0),[In,mr]=x.useState(!0),[Ln,Zt]=x.useState(!0),[en,pr]=x.useState(!0),[Bt,hn]=x.useState(!0),[Be,st]=x.useState(!0),[gn,vn]=x.useState(!0),[tn,nn]=x.useState(!0),[Ct,Dn]=x.useState(!0),[rn,bt]=x.useState(!0),[vt,Jn]=x.useState(!0),[Ke,hr]=x.useState(""),[yn,gr]=x.useState([]),[sn,vr]=x.useState(""),[Nt,Yn]=x.useState(null),[yt,Jr]=x.useState(!1),[xt,Et]=x.useState(""),[zn,ue]=x.useState(""),[ot,ve]=x.useState([]),[_t,Pt]=x.useState(!1),[we,lt]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:Gi,saving:!1,error:""}),Rt=x.useRef(!1),On=x.useRef(!1);x.useEffect(()=>{const d=document.documentElement,{colors:P}=Wi;d.style.setProperty("--rgb-background",P.backgroundRgb),d.style.setProperty("--rgb-surface-main",P.mainSurfaceRgb),d.style.setProperty("--rgb-surface-horizontal",P.horizontalSurfaceRgb),d.style.setProperty("--rgb-surface-focus",P.focusSurfaceRgb),d.style.setProperty("--rgb-assistant-chip",P.assistantChipRgb),d.style.setProperty("--rgb-assistant-chip-hover",P.assistantChipHoverRgb),d.style.setProperty("--rgb-assistant-chip-selected",P.assistantChipSelectedRgb),d.style.setProperty("--rgb-assistant-chip-selected-text",P.assistantChipSelectedTextRgb),d.style.setProperty("--rgb-active",P.activeRgb),d.style.setProperty("--rgb-active-text",P.activeTextRgb),d.style.setProperty("--rgb-text-main",P.textMainRgb),d.style.setProperty("--rgb-text-muted",P.textMutedRgb),d.style.setProperty("--rgb-danger",P.dangerRgb),d.style.setProperty("--rgb-scrollbar-track",P.scrollbarTrackRgb),d.style.setProperty("--rgb-scrollbar-thumb",P.scrollbarThumbRgb),d.style.setProperty("--rgb-scrollbar-thumb-hover",P.scrollbarThumbHoverRgb),d.style.setProperty("--mode-column-width",`${Wi.layout.modeColumnWidthPx}px`),d.style.setProperty("--mode-toggle-width",`${Wi.layout.modeToggleWidthPx}px`)},[]);const J=d=>{z(P=>[vm(d),...P].slice(0,300))};function Ne(){let d=0;Et(Ki[0]);const P=window.setInterval(()=>{d=Math.min(d+1,Ki.length-1),Et(Ki[d])},650);return()=>window.clearInterval(P)}x.useEffect(()=>{const d=localStorage.getItem(Lc);if(d)try{const k=JSON.parse(d);p(ye=>({...ye,llmProvider:k.llmProvider==="local"?"local":"openai",model:k.model??ye.model,baseUrl:k.baseUrl??ye.baseUrl,temperature:k.temperature??ye.temperature,maxOutputTokens:k.maxOutputTokens??ye.maxOutputTokens}))}catch{}const P=localStorage.getItem(Dc);if(P)try{const k=JSON.parse(P);(k.uiMode==="assistant"||k.uiMode==="decomposition"||k.uiMode==="autoruns")&&Ft(k.uiMode),k.activeTab&&gm.includes(k.activeTab)&&oe(k.activeTab),typeof k.showAutorunsAssistantMode=="boolean"&&An(k.showAutorunsAssistantMode),typeof k.showAutorunsDecompositionMode=="boolean"&&dr(k.showAutorunsDecompositionMode),typeof k.showAutorunsProgressMode=="boolean"&&Yt(k.showAutorunsProgressMode),typeof k.showAutorunsCommentsMode=="boolean"&&mn(k.showAutorunsCommentsMode),typeof k.showAssistantConnectionMode=="boolean"&&Xt(k.showAssistantConnectionMode),typeof k.showAssistantPromptMode=="boolean"&&fr(k.showAssistantPromptMode),typeof k.showAssistantChatMode=="boolean"&&mr(k.showAssistantChatMode),typeof k.showAssistantCommentsMode=="boolean"&&Zt(k.showAssistantCommentsMode),typeof k.showAssistantSamMode=="boolean"&&pr(k.showAssistantSamMode),typeof k.showDecompositionConnectionMode=="boolean"&&hn(k.showDecompositionConnectionMode),typeof k.showDecompositionPromptMode=="boolean"&&st(k.showDecompositionPromptMode),typeof k.showDecompositionQueryMode=="boolean"&&vn(k.showDecompositionQueryMode),typeof k.showDecompositionOutputMode=="boolean"&&nn(k.showDecompositionOutputMode),typeof k.showDecompositionMetricsMode=="boolean"&&Dn(k.showDecompositionMetricsMode),typeof k.showDecompositionHistoryMode=="boolean"&&bt(k.showDecompositionHistoryMode),typeof k.showDecompositionRuntimeMode=="boolean"&&Jn(k.showDecompositionRuntimeMode),k.prompts&&(R(ye=>({...ye,...k.prompts})),On.current=!0)}catch{}$n(),Yr(),xn()},[]);async function $n(){try{const d=await Ce.loadHistory();I(d.items??[])}catch(d){J(`History load error: ${d instanceof Error?d.message:String(d)}`)}}async function Yr(){try{const P=(await Ce.loadPresets()).presets??[];if($e(P),On.current){Rt.current=!0;return}if(Rt.current)return;const k=P.find(ye=>ye.prompt_version===qi)??P.find(ye=>ye.id==="default-normalizer-v2_0_2");if(!k){Rt.current=!0,J(`Preset autoload skipped: ${qi} not found.`);return}Ge(k.id),Te(m),R({systemPrompt:k.systemPrompt,developerPrompt:k.developerPrompt,domainPrompt:k.domainPrompt,schemaNotes:k.schemaNotes??"",fewShotExamples:k.fewShotExamples??""}),Rt.current=!0,J(`Preset autoloaded: ${k.name} (${k.prompt_version}).`)}catch(d){J(`Presets load error: ${d instanceof Error?d.message:String(d)}`)}}async function xn(){try{const d=await Ce.listRuns();Q(d.items??[])}catch(d){J(`Runs load error: ${d instanceof Error?d.message:String(d)}`)}}function Ie(){localStorage.setItem(Lc,JSON.stringify({model:i.model,llmProvider:i.llmProvider,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})),J("Local config saved (without API key).")}function Xr(){localStorage.setItem(Dc,JSON.stringify({uiMode:ke,activeTab:U,showAutorunsAssistantMode:qn,showAutorunsDecompositionMode:Tn,showAutorunsProgressMode:Jt,showAutorunsCommentsMode:Gn,showAssistantConnectionMode:Ut,showAssistantPromptMode:pn,showAssistantChatMode:In,showAssistantCommentsMode:Ln,showAssistantSamMode:en,showDecompositionConnectionMode:Bt,showDecompositionPromptMode:Be,showDecompositionQueryMode:gn,showDecompositionOutputMode:tn,showDecompositionMetricsMode:Ct,showDecompositionHistoryMode:rn,showDecompositionRuntimeMode:vt,prompts:m})),window.dispatchEvent(new CustomEvent(pm)),J("UI layout and prompts saved.")}async function ut(){te(!0),ee("");try{const d=await Ce.testConnection(i);d.provider==="local"?d.model_found===!0?(Ae(`LOCAL OK - ${d.model}`),J(`Local model is available: ${d.model} (catalog size=${d.models_count??"n/a"}).`)):d.model_found===!1?(Ae(`LOCAL OK, model not loaded - ${d.model}`),J(`Local server is reachable, but model '${d.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(Ae(`LOCAL OK (model list unavailable) - ${d.model}`),J("Local server is reachable, but model catalog could not be verified.")):(Ae(`OPENAI OK - ${d.model}`),J(`OpenAI connection ok: ${d.model}`))}catch(d){const P=d instanceof Error?d.message:String(d);Ae("Connection error"),ee(`Test connection: ${P}`),J(`Test connection error: ${P}`)}finally{te(!1)}}async function yr(){q(!0);try{const P=(await Ce.listModels(i)).models??[];Se(P),P.length>0&&p(k=>k.model&&P.includes(k.model)?k:{...k,model:P[0]}),J(`Model catalog loaded (${i.llmProvider}): ${P.length} items.`)}catch(d){const P=d instanceof Error?d.message:String(d);J(`Load model list error: ${P}`)}finally{q(!1)}}x.useEffect(()=>{Se([])},[i.llmProvider,i.baseUrl]);async function Fn(d){te(!0),ee("");try{const P=await Ce.normalize({connection:i,prompts:m,promptVersion:"normalizer_v2_0_2",query:{userQuestion:j.userQuestion,periodHint:j.periodHint,businessContext:j.businessContext,expectedRoute:j.expectedRoute},saveAsTestCase:d,useMock:Re});Y(P),oe("normalized"),J(`Normalize done: trace=${P.trace_id}, validation=${P.validation.passed?"passed":"failed"}`),$n()}catch(P){const k=P instanceof Error?P.message:String(P);ee(`Normalize: ${k}`),J(`Normalize error: ${k}`)}finally{te(!1)}}function le(){const d=De.find(P=>P.id===We);if(!d){J("Preset is not selected.");return}Te(m),R({systemPrompt:d.systemPrompt,developerPrompt:d.developerPrompt,domainPrompt:d.domainPrompt,schemaNotes:d.schemaNotes??"",fewShotExamples:d.fewShotExamples??""}),J(`Preset loaded: ${d.name}`)}async function Un(){try{await Ce.savePreset({name:Ze||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:m.systemPrompt,developerPrompt:m.developerPrompt,domainPrompt:m.domainPrompt,schemaNotes:m.schemaNotes,fewShotExamples:m.fewShotExamples}),J("Preset saved."),await Yr()}catch(d){J(`Preset save error: ${d instanceof Error?d.message:String(d)}`)}}function Mt(){R(Ic),J("Prompt panel reset to defaults.")}function ct(){const d=ym(m,ie);fe(d),J(d)}function ks(){const d=j.batchQuestionsRaw.split(";").map(P=>P.trim()).filter(Boolean).join(` `);d&&(T(P=>({...P,batchQuestionsRaw:d})),J("Batch field formatted: `;` converted to blank-line separators."))}async function St(d){try{const k=(await Ce.loadTrace(d)).trace,ye=k.parsed_normalized_json??null;Y({trace_id:String(k.trace_id??d),ok:!!k.validation_result?.passed,normalized:ye,route_hint_summary:k.route_hint_summary??(ye?{route_hint:ye.route_hint??null,confidence:ye.confidence?.route_hint??null}:null),raw_model_output:k.raw_model_response??{},validation:k.validation_result??{passed:!1,errors:["validation not found"]},usage:k.usage??{input_tokens:0,output_tokens:0,total_tokens:0},latency_ms:Number(k.latency_ms??0),prompt_version:String(k.prompt_version??"unknown"),schema_version:String(k.schema_version??"unknown")}),oe("raw"),ee(""),J(`Trace opened: ${d}`)}catch(P){const k=P instanceof Error?P.message:String(P);ee(`Trace: ${k}`),J(`Trace open error ${d}: ${k}`)}}async function Cs(){try{const d=await Ce.startRun();h(d.run.runId),J(`Run started: ${d.run.runId}`),J("Tip: start run does not execute normalize by itself. Use 'Run eval v2.0.2' button."),await xn()}catch(d){J(`Run start error: ${d instanceof Error?d.message:String(d)}`)}}async function Zr(){if(O)try{await Ce.finishRun(O),J(`Run finished: ${O}`),await xn()}catch(d){J(`Run finish error: ${d instanceof Error?d.message:String(d)}`)}}async function es(){ce(!0),ee("");try{J("Starting eval in v2 contour.");const d=j.batchQuestionsRaw.trim()||j.userQuestion.trim();if(!d)throw new Error("Fill batch field or Raw user question first.");const P=await Ce.runEval({connection:i,prompts:m,promptVersion:"normalizer_v2_0_2",mode:"single-pass-strict",rawQuestions:d,useMock:Re});xe(P.report),J("Eval v2.0.2 run finished.");const k=P.report;if(k.run_id&&J(`Eval run id: ${k.run_id}`),k.metrics){const ye=k.metrics;J(`Eval metrics v2.0.2: schema=${ye.schema_validation_pass_rate??"n/a"}%, route_accuracy=${ye.route_resolution_accuracy??"n/a"}%, no_route_precision=${ye.no_route_precision??"n/a"}%, state_consistency=${ye.execution_state_consistency_rate??"n/a"}%`)}await $n()}catch(d){const P=d instanceof Error?d.message:String(d);P.includes("Legacy eval runner supports normalized_query_v1 only")?(xe({status:"plan_only",prompt_version:"normalizer_v2",reason:"backend eval runner is still legacy-v1 only",plan_file:"reports/v2_pilot_eval_plan.md",next_steps:["run cheap mock sanity for schema/fragment/scope","run small real batch (10-15 messages, temperature=0)","run challenge-30 replay with v2 metrics"]}),J("Backend is legacy-only for eval right now. Showing v2 pilot plan.")):(ee(`Eval: ${P}`),J(`Eval run error: ${P}`))}finally{ce(!1)}}async function Xn(){try{const d=JSON.stringify(de??{},null,2);await navigator.clipboard.writeText(d),J("Eval report copied to clipboard.")}catch(d){J(`Eval report copy error: ${d instanceof Error?d.message:String(d)}`)}}const Bn=x.useMemo(()=>{const d=new Map;for(const P of ot)P.message_id&&d.set(P.message_id,P);return d},[ot]),At=we.messageIndex>=0?yn[we.messageIndex]??null:null,wt=x.useMemo(()=>{if(we.messageIndex<0)return null;for(let d=we.messageIndex-1;d>=0;d-=1){const P=yn[d];if(P?.role==="user")return P}return null},[we.messageIndex,yn]);async function xr(d){if(!d.trim()){ve([]);return}Pt(!0);try{const P=await Ce.loadAssistantAnnotations({session_id:d,limit:400});ve(P.items??[])}catch(P){const k=P instanceof Error?P.message:String(P);J(`Assistant annotations load error: ${k}`)}finally{Pt(!1)}}function dt(d){lt(P=>P.saving&&!d?.force?P:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:Gi,saving:!1,error:""})}function zr(d,P){if(d.role!=="assistant")return;const k=Ke.trim(),ye=String(d.session_id??"").trim();if(!(k||ye)){ue("Сначала получите ответ ассистента в активной сессии.");return}!k&&ye&&hr(ye);const Hn=Bn.get(d.message_id)??null;lt({open:!0,messageIndex:P,rating:Hn?.rating??3,comment:Hn?.comment??"",annotationAuthor:Hn?.annotation_author??Gi,saving:!1,error:""})}function bn(d){return d.role==="assistant"}function Tt(d){return d.role==="assistant"&&Bn.has(d.message_id)}async function Ht(){if(!Ke.trim()){lt(d=>({...d,error:"Сессия ассистента не найдена."}));return}if(!(we.messageIndex<0)){if(!we.comment.trim()){lt(d=>({...d,error:"Добавьте комментарий."}));return}lt(d=>({...d,saving:!0,error:""}));try{const d=await Ce.saveAssistantAnnotation({session_id:Ke,message_index:we.messageIndex,rating:we.rating,comment:we.comment.trim(),annotation_author:we.annotationAuthor.trim()||void 0});ve(P=>{const k=[...P],ye=k.findIndex(er=>er.annotation_id===d.annotation.annotation_id);return ye>=0?k[ye]=d.annotation:k.unshift(d.annotation),k.sort((er,Hn)=>Date.parse(Hn.updated_at)-Date.parse(er.updated_at))}),dt({force:!0})}catch(d){const P=d instanceof Error?d.message:String(d);lt(k=>({...k,saving:!1,error:P}))}}}function Vt(){hr(""),gr([]),vr(""),Yn(null),Et(""),ue(""),ve([]),dt({force:!0}),J("Assistant session reset.")}async function Zn(){const d=xm(sn,Nt);if(!d)return;Jr(!0),ue(""),vr(""),gr(k=>[...k,{message_id:`local-${Date.now()}`,session_id:Ke||"pending",role:"user",text:d,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const P=Ne();try{const k=await Ce.sendAssistantMessage({connection:i,prompts:m,userMessage:d,sessionId:Ke||void 0,promptVersion:zc,useMock:Re});hr(k.session_id),gr(k.conversation),Et("Ответ готов"),await xr(k.session_id),J(`Assistant reply received: trace=${k.debug.trace_id}`)}catch(k){const ye=k instanceof Error?k.message:String(k);ue(ye),Et("Ошибка ассистента"),J(`Assistant error: ${ye}`)}finally{P(),Jr(!1)}}return x.useEffect(()=>{if(!Ke.trim()){ve([]);return}xr(Ke)},[Ke]),x.useEffect(()=>{if(!O){G([]);return}Ce.runTrace(O).then(d=>G(d.items)).catch(d=>J(`Run trace error: ${d instanceof Error?d.message:String(d)}`))},[O]),o.jsxs("main",{className:`app-root ${ke==="assistant"||ke==="decomposition"||ke==="autoruns"?"app-root-autoruns":""}`,children:[o.jsxs("header",{className:"app-topbar",children:[o.jsxs("div",{className:"mode-switch-row",children:[o.jsx("button",{type:"button",className:ke==="assistant"?"tab active":"tab",onClick:()=>Ft("assistant"),children:"Ассистент"}),o.jsx("button",{type:"button",className:ke==="decomposition"?"tab active":"tab",onClick:()=>Ft("decomposition"),children:"Декомпозиция"}),o.jsx("button",{type:"button",className:ke==="autoruns"?"tab active":"tab",onClick:()=>Ft("autoruns"),children:"История автопрогонов"}),o.jsx("button",{type:"button",className:"tab",onClick:Xr,children:"Сохранить"})]}),ke==="assistant"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:Ut?"tab active":"tab",onClick:()=>Xt(d=>!d),children:"LLM Connector"}),o.jsx("button",{type:"button",className:pn?"tab active":"tab",onClick:()=>fr(d=>!d),children:"Prompt Manager"}),o.jsx("button",{type:"button",className:In?"tab active":"tab",onClick:()=>mr(d=>!d),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:Ln?"tab active":"tab",onClick:()=>Zt(d=>!d),children:"Комментарии ассистента"}),o.jsx("button",{type:"button",className:en?"tab active":"tab",onClick:()=>pr(d=>!d),children:"SAM"})]}):ke==="decomposition"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:Bt?"tab active":"tab",onClick:()=>hn(d=>!d),children:"LLM"}),o.jsx("button",{type:"button",className:Be?"tab active":"tab",onClick:()=>st(d=>!d),children:"Prompt"}),o.jsx("button",{type:"button",className:gn?"tab active":"tab",onClick:()=>vn(d=>!d),children:"Запрос"}),o.jsx("button",{type:"button",className:tn?"tab active":"tab",onClick:()=>nn(d=>!d),children:"Выход"}),o.jsx("button",{type:"button",className:Ct?"tab active":"tab",onClick:()=>Dn(d=>!d),children:"Метрики"}),o.jsx("button",{type:"button",className:rn?"tab active":"tab",onClick:()=>bt(d=>!d),children:"История"}),o.jsx("button",{type:"button",className:vt?"tab active":"tab",onClick:()=>Jn(d=>!d),children:"NDC Run Monitor"})]}):ke==="autoruns"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:qn?"tab active":"tab",onClick:()=>An(d=>!d),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:Tn?"tab active":"tab",onClick:()=>dr(d=>!d),children:"Режим декомпозиции"}),o.jsx("button",{type:"button",className:Jt?"tab active":"tab",onClick:()=>Yt(d=>!d),children:"Прогресс/регресс"}),o.jsx("button",{type:"button",className:Gn?"tab active":"tab",onClick:()=>mn(d=>!d),children:"Комментарии"})]}):null]}),ke==="assistant"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[Ut?o.jsx("div",{className:"mode-col",children:o.jsx(Ac,{value:i,modelOptions:re,modelsBusy:se,onChange:p,onReloadModels:yr,onSaveLocalConfig:Ie,onTestConnection:ut,lastStatus:Pe,busy:Me||yt})}):null,pn?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(Tc,{value:m,onChange:R,presets:De,selectedPresetId:We,onSelectPreset:Ge,onLoadPreset:le,onSavePreset:Un,onResetDefaults:Mt,onDiffPrevious:ct,presetName:Ze,onPresetNameChange:rt,diffSummary:Fe})}):null,In?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(Fc,{sessionId:Ke,conversation:yn,inputValue:sn,onInputChange:vr,selectedContextChip:Nt,onSelectContextChip:Yn,onClearContextChip:()=>Yn(null),useMock:Re,onUseMockChange:me,onSend:Zn,onClear:Vt,busy:yt,statusText:xt,errorMessage:zn,showCommentAction:!0,onCommentAssistantMessage:zr,isAssistantMessageCommented:Tt,canCommentAssistantMessage:bn})}):null,Ln?o.jsx("div",{className:"mode-col",children:o.jsx(Mn,{className:"assistant-comments-frame",title:"Комментарии ассистента",children:o.jsxs("div",{className:"assistant-comments-shell",children:[o.jsxs("div",{className:"assistant-comments-toolbar",children:[o.jsx("span",{className:"muted",children:Ke?`session: ${Ke}`:"Сессия не запущена"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{xr(Ke)},disabled:!Ke||_t,children:_t?"Обновляю...":"Обновить"})]}),o.jsxs("div",{className:"assistant-comments-list",children:[Ke?null:o.jsx("p",{className:"muted",children:"Появится после первого ответа ассистента."}),Ke&&ot.length===0&&!_t?o.jsx("p",{className:"muted",children:"Комментариев по этой сессии пока нет."}):null,ot.map(d=>o.jsxs("article",{className:"assistant-comment-item",children:[o.jsxs("div",{className:"assistant-comment-head",children:[o.jsx("strong",{children:`${"●".repeat(Math.max(1,Math.min(5,Math.round(d.rating))))}${"○".repeat(Math.max(0,5-Math.round(d.rating)))}`}),o.jsx("span",{children:new Date(d.updated_at).toLocaleString("ru-RU")})]}),d.context.question_text?o.jsxs("p",{children:["Q: ",d.context.question_text]}):null,d.context.answer_text?o.jsxs("p",{children:["A: ",d.context.answer_text]}):null,o.jsx("p",{children:d.comment}),o.jsxs("div",{className:"assistant-comment-meta",children:[d.context.trace_id?o.jsx("span",{children:`trace=${d.context.trace_id}`}):null,d.context.reply_type?o.jsx("span",{children:`reply_type=${d.context.reply_type}`}):null]})]},d.annotation_id))]})]})})}):null,en?o.jsx("div",{className:"mode-col",children:o.jsx(Af,{sessionId:Ke,conversation:yn,statusText:xt,errorMessage:zn,useMock:Re,appLogs:W})}):null,!Ut&&!pn&&!In&&!Ln&&!en?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима ассистента скрыты. Включите нужные блоки справа в шапке."}):null]})}):ke==="decomposition"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[Bt?o.jsx("div",{className:"mode-col",children:o.jsx(Ac,{value:i,modelOptions:re,modelsBusy:se,onChange:p,onReloadModels:yr,onSaveLocalConfig:Ie,onTestConnection:ut,lastStatus:Pe,busy:Me})}):null,Be?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(Tc,{value:m,onChange:R,presets:De,selectedPresetId:We,onSelectPreset:Ge,onLoadPreset:le,onSavePreset:Un,onResetDefaults:Mt,onDiffPrevious:ct,presetName:Ze,onPresetNameChange:rt,diffSummary:Fe})}):null,gn?o.jsx("div",{className:"mode-col",children:o.jsx(cm,{value:j,onChange:T,onApplyBatchFormat:ks,onNormalize:Fn,busy:Me,useMock:Re,onUseMockChange:me,errorMessage:ge})}):null,tn?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(um,{tab:U,onTabChange:oe,result:$,appLogs:W})}):null,Ct?o.jsx("div",{className:"mode-col",children:o.jsx(lm,{result:$})}):null,rn?o.jsx("div",{className:"mode-col",children:o.jsx(om,{items:F,onRefresh:$n,onOpenTrace:St})}):null,vt?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(dm,{runs:D,selectedRunId:O,onSelectRun:h,onStartRun:Cs,onFinishRun:Zr,onRefreshRuns:xn,onRunEval:es,onCopyEvalReport:Xn,evalBusy:ae,traceItems:C,evalReport:de})}):null,!Bt&&!Be&&!gn&&!tn&&!Ct&&!rn&&!vt?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима декомпозиции скрыты. Включите нужные блоки справа в шапке."}):null]})}):o.jsx("div",{className:"layout-grid layout-grid-autoruns",children:o.jsx(sm,{connection:i,prompts:m,assistantPromptVersion:zc,decompositionPromptVersion:qi,showAssistantMode:qn,showDecompositionMode:Tn,showProgressMode:Jt,showCommentsMode:Gn,onLog:J})}),we.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:d=>{d.target===d.currentTarget&&dt()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Эта разметка хранится отдельно от комментариев автопрогонов."}),wt?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:wt.text})]}):null,At?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:At.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(d=>o.jsx("button",{type:"button",className:we.rating>=d?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>lt(P=>({...P,rating:d})),disabled:we.saving,"aria-label":`Оценка ${d}`,children:we.rating>=d?"●":"○"},d))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:we.annotationAuthor,onChange:d=>lt(P=>({...P,annotationAuthor:d.target.value})),placeholder:"manual_reviewer",disabled:we.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:we.comment,onChange:d=>lt(P=>({...P,comment:d.target.value})),placeholder:"Что именно не так в ответе и что проверить.",rows:4,disabled:we.saving})]}),we.error?o.jsx("p",{className:"error-text",children:we.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{Ht()},disabled:we.saving,children:we.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>dt(),disabled:we.saving,children:"Отмена"})]})]})}):null]})}Pf.createRoot(document.getElementById("root")).render(o.jsx(Sf.StrictMode,{children:o.jsx(_m,{})}));