(function(){const p=document.createElement("link").relList;if(p&&p.supports&&p.supports("modulepreload"))return;for(const j of document.querySelectorAll('link[rel="modulepreload"]'))N(j);new MutationObserver(j=>{for(const T of j)if(T.type==="childList")for(const $ of T.addedNodes)$.tagName==="LINK"&&$.rel==="modulepreload"&&N($)}).observe(document,{childList:!0,subtree:!0});function f(j){const T={};return j.integrity&&(T.integrity=j.integrity),j.referrerPolicy&&(T.referrerPolicy=j.referrerPolicy),j.crossOrigin==="use-credentials"?T.credentials="include":j.crossOrigin==="anonymous"?T.credentials="omit":T.credentials="same-origin",T}function N(j){if(j.ep)return;j.ep=!0;const T=f(j);fetch(j.href,T)}})();function Vc(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Wi={exports:{}},mo={},qi={exports:{}},he={};var Sc;function wf(){if(Sc)return he;Sc=1;var i=Symbol.for("react.element"),p=Symbol.for("react.portal"),f=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),j=Symbol.for("react.profiler"),T=Symbol.for("react.provider"),$=Symbol.for("react.context"),Y=Symbol.for("react.forward_ref"),b=Symbol.for("react.suspense"),Q=Symbol.for("react.memo"),G=Symbol.for("react.lazy"),z=Symbol.iterator;function ne(y){return y===null||typeof y!="object"?null:(y=z&&y[z]||y["@@iterator"],typeof y=="function"?y:null)}var Ne={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},le=Object.assign,ce={};function me(y,C,J){this.props=y,this.context=C,this.refs=ce,this.updater=J||Ne}me.prototype.isReactComponent={},me.prototype.setState=function(y,C){if(typeof y!="object"&&typeof y!="function"&&y!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,y,C,"setState")},me.prototype.forceUpdate=function(y){this.updater.enqueueForceUpdate(this,y,"forceUpdate")};function Qe(){}Qe.prototype=me.prototype;function De(y,C,J){this.props=y,this.context=C,this.refs=ce,this.updater=J||Ne}var We=De.prototype=new Qe;We.constructor=De,le(We,me.prototype),We.isPureReactComponent=!0;var je=Array.isArray,W=Object.prototype.hasOwnProperty,de={current:null},Me={key:!0,ref:!0,__self:!0,__source:!0};function Ze(y,C,J){var oe,pe={},ae=null,Se=null;if(C!=null)for(oe in C.ref!==void 0&&(Se=C.ref),C.key!==void 0&&(ae=""+C.key),C)W.call(C,oe)&&!Me.hasOwnProperty(oe)&&(pe[oe]=C[oe]);var ge=arguments.length-2;if(ge===1)pe.children=J;else if(1>>1,C=I[y];if(0>>1;yj(pe,O))aej(Se,pe)?(I[y]=Se,I[ae]=O,y=ae):(I[y]=pe,I[oe]=O,y=oe);else if(aej(Se,O))I[y]=Se,I[ae]=O,y=ae;else break e}}return X}function j(I,X){var O=I.sortIndex-X.sortIndex;return O!==0?O:I.id-X.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 b=[],Q=[],G=1,z=null,ne=3,Ne=!1,le=!1,ce=!1,me=typeof setTimeout=="function"?setTimeout:null,Qe=typeof clearTimeout=="function"?clearTimeout:null,De=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function We(I){for(var X=f(Q);X!==null;){if(X.callback===null)N(Q);else if(X.startTime<=I)N(Q),X.sortIndex=X.expirationTime,p(b,X);else break;X=f(Q)}}function je(I){if(ce=!1,We(I),!le)if(f(b)!==null)le=!0,Te(W);else{var X=f(Q);X!==null&&Ae(je,X.startTime-I)}}function W(I,X){le=!1,ce&&(ce=!1,Qe(Ze),Ze=-1),Ne=!0;var O=ne;try{for(We(X),z=f(b);z!==null&&(!(z.expirationTime>X)||I&&!Et());){var y=z.callback;if(typeof y=="function"){z.callback=null,ne=z.priorityLevel;var C=y(z.expirationTime<=X);X=i.unstable_now(),typeof C=="function"?z.callback=C:z===f(b)&&N(b),We(X)}else N(b);z=f(b)}if(z!==null)var J=!0;else{var oe=f(Q);oe!==null&&Ae(je,oe.startTime-X),J=!1}return J}finally{z=null,ne=O,Ne=!1}}var de=!1,Me=null,Ze=-1,ct=5,st=-1;function Et(){return!(i.unstable_now()-stI||125y?(I.sortIndex=O,p(Q,I),f(b)===null&&I===f(Q)&&(ce?(Qe(Ze),Ze=-1):ce=!0,Ae(je,O-y))):(I.sortIndex=C,p(b,I),le||Ne||(le=!0,Te(W))),I},i.unstable_shouldYield=Et,i.unstable_wrapCallback=function(I){var X=ne;return function(){var O=ne;ne=X;try{return I.apply(this,arguments)}finally{ne=O}}}})(Ji)),Ji}var Nc;function Ef(){return Nc||(Nc=1,Gi.exports=Nf()),Gi.exports}var Ec;function Pf(){if(Ec)return Wt;Ec=1;var i=aa(),p=Ef();function f(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),b=Object.prototype.hasOwnProperty,Q=/^[: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]*$/,G={},z={};function ne(e){return b.call(z,e)?!0:b.call(G,e)?!1:Q.test(e)?z[e]=!0:(G[e]=!0,!1)}function Ne(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 le(e,t,n,r){if(t===null||typeof t>"u"||Ne(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 ce(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 me={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){me[e]=new ce(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];me[t]=new ce(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){me[e]=new ce(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){me[e]=new ce(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){me[e]=new ce(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){me[e]=new ce(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){me[e]=new ce(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){me[e]=new ce(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){me[e]=new ce(e,5,!1,e.toLowerCase(),null,!1,!1)});var Qe=/[\-:]([a-z])/g;function De(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Qe,De);me[t]=new ce(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Qe,De);me[t]=new ce(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Qe,De);me[t]=new ce(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){me[e]=new ce(e,1,!1,e.toLowerCase(),null,!1,!1)}),me.xlinkHref=new ce("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){me[e]=new ce(e,1,!1,e.toLowerCase(),null,!0,!0)});function We(e,t,n,r){var s=me.hasOwnProperty(t)?me[t]:null;(s!==null?s.type!==0:r||!(2d||s[u]!==l[d]){var h=` `+s[u].replace(" at new "," at ");return e.displayName&&h.includes("")&&(h=h.replace("",e.displayName)),h}while(1<=u&&0<=d);break}}}finally{J=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?C(e):""}function pe(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=oe(e.type,!1),e;case 11:return e=oe(e.type.render,!1),e;case 1:return e=oe(e.type,!0),e;default:return""}}function ae(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 Me:return"Fragment";case de:return"Portal";case ct:return"Profiler";case Ze:return"StrictMode";case Le:return"Suspense";case H:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Et:return(e.displayName||"Context")+".Consumer";case st: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:ae(e.type)||"Memo";case Te:t=e._payload,e=e._init;try{return ae(e(t))}catch{}}return null}function Se(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ae(t);case 8:return t===Ze?"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 ve(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ee(e){var t=ve(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 gn(e){e._valueTracker||(e._valueTracker=Ee(e))}function vn(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ve(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Yn(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Ln(e,t){var n=t.checked;return O({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Xn(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 Pe(e,t){t=t.checked,t!=null&&We(e,"checked",t,!1)}function qt(e,t){Pe(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")?dt(e,t.type,n):t.hasOwnProperty("defaultValue")&&dt(e,t.type,ge(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ot(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 dt(e,t,n){(t!=="number"||Yn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var lt=Array.isArray;function yn(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=xt.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Oe(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var rn={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},On=["Webkit","ms","Moz","O"];Object.keys(rn).forEach(function(e){On.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),rn[t]=rn[e]})});function xr(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||rn.hasOwnProperty(e)&&rn[e]?(""+t).trim():t+"px"}function Dn(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=xr(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var Qr=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 Sn(e,t){if(t){if(Qr[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(f(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(f(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(f(61))}if(t.style!=null&&typeof t.style!="object")throw Error(f(62))}}function sn(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Lt=null;function Zn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Kt=null,on=null,Ot=null;function _r(e){if(e=Ys(e)){if(typeof Kt!="function")throw Error(f(280));var t=e.stateNode;t&&(t=ko(t),Kt(e.stateNode,e.type,t))}}function zn(e){on?Ot?Ot.push(e):Ot=[e]:on=e}function Sr(){if(on){var e=on,t=Ot;if(Ot=on=null,_r(e),t)for(e=0;e>>=0,e===0?32:31-(sr(e)/Hn|0)|0}var $t=64,kn=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 ke(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,l=e.pingedLanes,u=n&268435455;if(u!==0){var d=u&~s;d!==0?r=At(d):(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 it(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-be(t),e[t]=n}function lr(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=Bs),pa=" ",ha=!1;function ga(e,t){switch(e){case"keyup":return gd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function va(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gs=!1;function yd(e,t){switch(e){case"compositionend":return va(t);case"keypress":return t.which!==32?null:(ha=!0,pa);case"textInput":return e=t.data,e===pa&&ha?null:e;default:return null}}function xd(e,t){if(gs)return e==="compositionend"||!Nl&&ga(e,t)?(e=R(),v=c=a=null,gs=!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=ka(n)}}function Na(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Na(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ea(){for(var e=window,t=Yn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Yn(e.document)}return t}function Ml(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Pd(e){var t=Ea(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Na(n.ownerDocument.documentElement,n)){if(r!==null&&Ml(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=Ca(n,l);var u=Ca(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,vs=null,Al=null,Ws=null,Rl=!1;function Pa(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Rl||vs==null||vs!==Yn(r)||(r=vs,"selectionStart"in r&&Ml(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}),Ws&&Qs(Ws,r)||(Ws=r,r=So(Al,"onSelect"),0ws||(e.current=Hl[ws],Hl[ws]=null,ws--)}function $e(e,t){ws++,Hl[ws]=e.current,e.current=t}var Ir={},wt=Tr(Ir),bt=Tr(!1),Zr=Ir;function js(e,t){var n=e.type.contextTypes;if(!n)return Ir;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 Bt(e){return e=e.childContextTypes,e!=null}function Co(){He(bt),He(wt)}function Ha(e,t,n){if(wt.current!==Ir)throw Error(f(168));$e(wt,t),$e(bt,n)}function Va(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(f(108,Se(e)||"Unknown",s));return O({},n,r)}function No(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ir,Zr=wt.current,$e(wt,e),$e(bt,bt.current),!0}function Qa(e,t,n){var r=e.stateNode;if(!r)throw Error(f(169));n?(e=Va(e,t,Zr),r.__reactInternalMemoizedMergedChildContext=e,He(bt),He(wt),$e(wt,e)):He(bt),$e(bt,n)}var cr=null,Eo=!1,Vl=!1;function Wa(e){cr===null?cr=[e]:cr.push(e)}function Ud(e){Eo=!0,Wa(e)}function Lr(){if(!Vl&&cr!==null){Vl=!0;var e=0,t=F;try{var n=cr;for(F=1;e>=u,s-=u,dr=1<<32-be(t)+s|n<se?(ht=ee,ee=null):ht=ee.sibling;var we=P(_,ee,S[se],L);if(we===null){ee===null&&(ee=ht);break}e&&ee&&we.alternate===null&&t(_,ee),g=l(we,g,se),Z===null?K=we:Z.sibling=we,Z=we,ee=ht}if(se===S.length)return n(_,ee),Ve&&ts(_,se),K;if(ee===null){for(;sese?(ht=ee,ee=null):ht=ee.sibling;var Hr=P(_,ee,we.value,L);if(Hr===null){ee===null&&(ee=ht);break}e&&ee&&Hr.alternate===null&&t(_,ee),g=l(Hr,g,se),Z===null?K=Hr:Z.sibling=Hr,Z=Hr,ee=ht}if(we.done)return n(_,ee),Ve&&ts(_,se),K;if(ee===null){for(;!we.done;se++,we=S.next())we=A(_,we.value,L),we!==null&&(g=l(we,g,se),Z===null?K=we:Z.sibling=we,Z=we);return Ve&&ts(_,se),K}for(ee=r(_,ee);!we.done;se++,we=S.next())we=U(ee,_,se,we.value,L),we!==null&&(e&&we.alternate!==null&&ee.delete(we.key===null?se:we.key),g=l(we,g,se),Z===null?K=we:Z.sibling=we,Z=we);return e&&ee.forEach(function(Sf){return t(_,Sf)}),Ve&&ts(_,se),K}function et(_,g,S,L){if(typeof S=="object"&&S!==null&&S.type===Me&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case W:e:{for(var K=S.key,Z=g;Z!==null;){if(Z.key===K){if(K=S.type,K===Me){if(Z.tag===7){n(_,Z.sibling),g=s(Z,S.props.children),g.return=_,_=g;break e}}else if(Z.elementType===K||typeof K=="object"&&K!==null&&K.$$typeof===Te&&Xa(K)===Z.type){n(_,Z.sibling),g=s(Z,S.props),g.ref=Xs(_,Z,S),g.return=_,_=g;break e}n(_,Z);break}else t(_,Z);Z=Z.sibling}S.type===Me?(g=us(S.props.children,_.mode,L,S.key),g.return=_,_=g):(L=tl(S.type,S.key,S.props,null,_.mode,L),L.ref=Xs(_,g,S),L.return=_,_=L)}return u(_);case de:e:{for(Z=S.key;g!==null;){if(g.key===Z)if(g.tag===4&&g.stateNode.containerInfo===S.containerInfo&&g.stateNode.implementation===S.implementation){n(_,g.sibling),g=s(g,S.children||[]),g.return=_,_=g;break e}else{n(_,g);break}else t(_,g);g=g.sibling}g=bi(S,_.mode,L),g.return=_,_=g}return u(_);case Te:return Z=S._init,et(_,g,Z(S._payload),L)}if(lt(S))return V(_,g,S,L);if(X(S))return q(_,g,S,L);Ro(_,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,g!==null&&g.tag===6?(n(_,g.sibling),g=s(g,S),g.return=_,_=g):(n(_,g),g=Ui(S,_.mode,L),g.return=_,_=g),u(_)):n(_,g)}return et}var Es=Za(!0),eu=Za(!1),To=Tr(null),Io=null,Ps=null,Jl=null;function Yl(){Jl=Ps=Io=null}function Xl(e){var t=To.current;He(To),e._currentValue=t}function Zl(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 Ms(e,t){Io=e,Jl=Ps=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Ht=!0),e.firstContext=null)}function fn(e){var t=e._currentValue;if(Jl!==e)if(e={context:e,memoizedValue:t,next:null},Ps===null){if(Io===null)throw Error(f(308));Ps=e,Io.dependencies={lanes:0,firstContext:e}}else Ps=Ps.next=e;return t}var ns=null;function ei(e){ns===null?ns=[e]:ns.push(e)}function tu(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,ei(t)):(n.next=s.next,s.next=n),t.interleaved=n,mr(e,r)}function mr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Or=!1;function ti(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function nu(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 pr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Dr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(xe&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,mr(e,n)}return s=r.interleaved,s===null?(t.next=t,ei(r)):(t.next=s.next,s.next=t),r.interleaved=t,mr(e,n)}function Lo(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,ir(e,n)}}function ru(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 Oo(e,t,n,r){var s=e.updateQueue;Or=!1;var l=s.firstBaseUpdate,u=s.lastBaseUpdate,d=s.shared.pending;if(d!==null){s.shared.pending=null;var h=d,w=h.next;h.next=null,u===null?l=w:u.next=w,u=h;var M=e.alternate;M!==null&&(M=M.updateQueue,d=M.lastBaseUpdate,d!==u&&(d===null?M.firstBaseUpdate=w:d.next=w,M.lastBaseUpdate=h))}if(l!==null){var A=s.baseState;u=0,M=w=h=null,d=l;do{var P=d.lane,U=d.eventTime;if((r&P)===P){M!==null&&(M=M.next={eventTime:U,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var V=e,q=d;switch(P=t,U=n,q.tag){case 1:if(V=q.payload,typeof V=="function"){A=V.call(U,A,P);break e}A=V;break e;case 3:V.flags=V.flags&-65537|128;case 0:if(V=q.payload,P=typeof V=="function"?V.call(U,A,P):V,P==null)break e;A=O({},A,P);break e;case 2:Or=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,P=s.effects,P===null?s.effects=[d]:P.push(d))}else U={eventTime:U,lane:P,tag:d.tag,payload:d.payload,callback:d.callback,next:null},M===null?(w=M=U,h=A):M=M.next=U,u|=P;if(d=d.next,d===null){if(d=s.shared.pending,d===null)break;P=d,d=P.next,P.next=null,s.lastBaseUpdate=P,s.shared.pending=null}}while(!0);if(M===null&&(h=A),s.baseState=h,s.firstBaseUpdate=w,s.lastBaseUpdate=M,t=s.shared.interleaved,t!==null){s=t;do u|=s.lane,s=s.next;while(s!==t)}else l===null&&(s.shared.lanes=0);os|=u,e.lanes=u,e.memoizedState=A}}function su(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=li.transition;li.transition={};try{e(!1),t()}finally{F=n,li.transition=r}}function ju(){return mn().memoizedState}function Vd(e,t,n){var r=Ur(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ku(e))Cu(t,n);else if(n=tu(e,t,n,r),n!==null){var s=Tt();Tn(n,e,r,s),Nu(n,t,r)}}function Qd(e,t,n){var r=Ur(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ku(e))Cu(t,s);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var u=t.lastRenderedState,d=l(u,n);if(s.hasEagerState=!0,s.eagerState=d,En(d,u)){var h=t.interleaved;h===null?(s.next=s,ei(t)):(s.next=h.next,h.next=s),t.interleaved=s;return}}catch{}n=tu(e,t,s,r),n!==null&&(s=Tt(),Tn(n,e,r,s),Nu(n,t,r))}}function ku(e){var t=e.alternate;return e===Ke||t!==null&&t===Ke}function Cu(e,t){no=$o=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Nu(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ir(e,n)}}var bo={readContext:fn,useCallback:jt,useContext:jt,useEffect:jt,useImperativeHandle:jt,useInsertionEffect:jt,useLayoutEffect:jt,useMemo:jt,useReducer:jt,useRef:jt,useState:jt,useDebugValue:jt,useDeferredValue:jt,useTransition:jt,useMutableSource:jt,useSyncExternalStore:jt,useId:jt,unstable_isNewReconciler:!1},Wd={readContext:fn,useCallback:function(e,t){return Gn().memoizedState=[e,t===void 0?null:t],e},useContext:fn,useEffect:hu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Fo(4194308,4,yu.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Fo(4194308,4,e,t)},useInsertionEffect:function(e,t){return Fo(4,2,e,t)},useMemo:function(e,t){var n=Gn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Gn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Vd.bind(null,Ke,e),[r.memoizedState,e]},useRef:function(e){var t=Gn();return e={current:e},t.memoizedState=e},useState:mu,useDebugValue:mi,useDeferredValue:function(e){return Gn().memoizedState=e},useTransition:function(){var e=mu(!1),t=e[0];return e=Hd.bind(null,e[1]),Gn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ke,s=Gn();if(Ve){if(n===void 0)throw Error(f(407));n=n()}else{if(n=t(),pt===null)throw Error(f(349));(ss&30)!==0||au(r,t,n)}s.memoizedState=n;var l={value:n,getSnapshot:t};return s.queue=l,hu(cu.bind(null,r,l,e),[e]),r.flags|=2048,oo(9,uu.bind(null,r,l,n,t),void 0,null),n},useId:function(){var e=Gn(),t=pt.identifierPrefix;if(Ve){var n=fr,r=dr;n=(r&~(1<<32-be(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ro++,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[qn]=t,e[Js]=r,Wu(e,t,!1,!1),t.stateNode=e;e:{switch(u=sn(n,r),n){case"dialog":Be("cancel",e),Be("close",e),s=r;break;case"iframe":case"object":case"embed":Be("load",e),s=r;break;case"video":case"audio":for(s=0;sLs&&(t.flags|=128,r=!0,lo(l,!1),t.lanes=4194304)}else{if(!r)if(e=Do(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),lo(l,!0),l.tail===null&&l.tailMode==="hidden"&&!u.alternate&&!Ve)return kt(t),null}else 2*D()-l.renderingStartTime>Ls&&n!==1073741824&&(t.flags|=128,r=!0,lo(l,!1),t.lanes=4194304);l.isBackwards?(u.sibling=t.child,t.child=u):(n=l.last,n!==null?n.sibling=u:t.child=u,l.last=u)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=D(),t.sibling=null,n=qe.current,$e(qe,r?n&1|2:n&1),t):(kt(t),null);case 22:case 23:return zi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(en&1073741824)!==0&&(kt(t),t.subtreeFlags&6&&(t.flags|=8192)):kt(t),null;case 24:return null;case 25:return null}throw Error(f(156,t.tag))}function ef(e,t){switch(Wl(t),t.tag){case 1:return Bt(t.type)&&Co(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return As(),He(bt),He(wt),oi(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return ri(t),null;case 13:if(He(qe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(f(340));Ns()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return He(qe),null;case 4:return As(),null;case 10:return Xl(t.type._context),null;case 22:case 23:return zi(),null;case 24:return null;default:return null}}var Qo=!1,Ct=!1,tf=typeof WeakSet=="function"?WeakSet:Set,B=null;function Ts(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Xe(e,t,r)}else n.current=null}function Ci(e,t,n){try{n()}catch(r){Xe(e,t,r)}}var Gu=!1;function nf(e,t){if(zl=ms,e=Ea(),Ml(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,l=r.focusNode;r=r.focusOffset;try{n.nodeType,l.nodeType}catch{n=null;break e}var u=0,d=-1,h=-1,w=0,M=0,A=e,P=null;t:for(;;){for(var U;A!==n||s!==0&&A.nodeType!==3||(d=u+s),A!==l||r!==0&&A.nodeType!==3||(h=u+r),A.nodeType===3&&(u+=A.nodeValue.length),(U=A.firstChild)!==null;)P=A,A=U;for(;;){if(A===e)break t;if(P===n&&++w===s&&(d=u),P===l&&++M===r&&(h=u),(U=A.nextSibling)!==null)break;A=P,P=A.parentNode}A=U}n=d===-1||h===-1?null:{start:d,end:h}}else n=null}n=n||{start:0,end:0}}else n=null;for($l={focusedElem:e,selectionRange:n},ms=!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 V=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(V!==null){var q=V.memoizedProps,et=V.memoizedState,_=t.stateNode,g=_.getSnapshotBeforeUpdate(t.elementType===t.type?q:Mn(t.type,q),et);_.__reactInternalSnapshotBeforeUpdate=g}break;case 3:var S=t.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(f(163))}}catch(L){Xe(t,t.return,L)}if(e=t.sibling,e!==null){e.return=t.return,B=e;break}B=t.return}return V=Gu,Gu=!1,V}function io(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&&Ci(t,n,l)}s=s.next}while(s!==r)}}function Wo(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 Ni(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 Ju(e){var t=e.alternate;t!==null&&(e.alternate=null,Ju(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[qn],delete t[Js],delete t[Bl],delete t[$d],delete t[Fd])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Yu(e){return e.tag===5||e.tag===3||e.tag===4}function Xu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Yu(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 Ei(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=jo));else if(r!==4&&(e=e.child,e!==null))for(Ei(e,t,n),e=e.sibling;e!==null;)Ei(e,t,n),e=e.sibling}function Pi(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(Pi(e,t,n),e=e.sibling;e!==null;)Pi(e,t,n),e=e.sibling}var vt=null,An=!1;function zr(e,t,n){for(n=n.child;n!==null;)Zu(e,t,n),n=n.sibling}function Zu(e,t,n){if(Ue&&typeof Ue.onCommitFiberUnmount=="function")try{Ue.onCommitFiberUnmount(ue,n)}catch{}switch(n.tag){case 5:Ct||Ts(n,t);case 6:var r=vt,s=An;vt=null,zr(e,t,n),vt=r,An=s,vt!==null&&(An?(e=vt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):vt.removeChild(n.stateNode));break;case 18:vt!==null&&(An?(e=vt,n=n.stateNode,e.nodeType===8?bl(e.parentNode,n):e.nodeType===1&&bl(e,n),Jr(e)):bl(vt,n.stateNode));break;case 4:r=vt,s=An,vt=n.stateNode.containerInfo,An=!0,zr(e,t,n),vt=r,An=s;break;case 0:case 11:case 14:case 15:if(!Ct&&(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)&&Ci(n,t,u),s=s.next}while(s!==r)}zr(e,t,n);break;case 1:if(!Ct&&(Ts(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(d){Xe(n,t,d)}zr(e,t,n);break;case 21:zr(e,t,n);break;case 22:n.mode&1?(Ct=(r=Ct)||n.memoizedState!==null,zr(e,t,n),Ct=r):zr(e,t,n);break;default:zr(e,t,n)}}function ec(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new tf),t.forEach(function(r){var s=ff.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Rn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~l}if(r=s,r=D()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*sf(r/1960))-r,10e?16:e,Fr===null)var r=!1;else{if(e=Fr,Fr=null,Yo=0,(xe&6)!==0)throw Error(f(331));var s=xe;for(xe|=4,B=e.current;B!==null;){var l=B,u=l.child;if((B.flags&16)!==0){var d=l.deletions;if(d!==null){for(var h=0;hD()-Ri?is(e,0):Ai|=n),Qt(e,t)}function mc(e,t){t===0&&((e.mode&1)===0?t=1:(t=kn,kn<<=1,(kn&130023424)===0&&(kn=4194304)));var n=Tt();e=mr(e,t),e!==null&&(it(e,t,n),Qt(e,n))}function df(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),mc(e,n)}function ff(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(f(314))}r!==null&&r.delete(t),mc(e,n)}var pc;pc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||bt.current)Ht=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Ht=!1,Xd(e,t,n);Ht=(e.flags&131072)!==0}else Ht=!1,Ve&&(t.flags&1048576)!==0&&qa(t,Mo,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Vo(e,t),e=t.pendingProps;var s=js(t,wt.current);Ms(t,n),s=ai(null,t,r,e,s,n);var l=ui();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,Bt(r)?(l=!0,No(t)):l=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,ti(t),s.updater=Bo,t.stateNode=s,s._reactInternals=t,hi(t,r,e,n),t=xi(null,t,r,!0,l,n)):(t.tag=0,Ve&&l&&Ql(t),Rt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Vo(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=pf(r),e=Mn(r,e),s){case 0:t=yi(null,t,r,e,n);break e;case 1:t=Uu(null,t,r,e,n);break e;case 11:t=Ou(null,t,r,e,n);break e;case 14:t=Du(null,t,r,Mn(r.type,e),n);break e}throw Error(f(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Mn(r,s),yi(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Mn(r,s),Uu(e,t,r,s,n);case 3:e:{if(bu(t),e===null)throw Error(f(387));r=t.pendingProps,l=t.memoizedState,s=l.element,nu(e,t),Oo(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=Rs(Error(f(423)),t),t=Bu(e,t,r,n,s);break e}else if(r!==s){s=Rs(Error(f(424)),t),t=Bu(e,t,r,n,s);break e}else for(Zt=Rr(t.stateNode.containerInfo.firstChild),Xt=t,Ve=!0,Pn=null,n=eu(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Ns(),r===s){t=hr(e,t,n);break e}Rt(e,t,r,n)}t=t.child}return t;case 5:return ou(t),e===null&&Kl(t),r=t.type,s=t.pendingProps,l=e!==null?e.memoizedProps:null,u=s.children,Fl(r,s)?u=null:l!==null&&Fl(r,l)&&(t.flags|=32),Fu(e,t),Rt(e,t,u,n),t.child;case 6:return e===null&&Kl(t),null;case 13:return Hu(e,t,n);case 4:return ni(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Es(t,null,r,n):Rt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Mn(r,s),Ou(e,t,r,s,n);case 7:return Rt(e,t,t.pendingProps,n),t.child;case 8:return Rt(e,t,t.pendingProps.children,n),t.child;case 12:return Rt(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,$e(To,r._currentValue),r._currentValue=u,l!==null)if(En(l.value,u)){if(l.children===s.children&&!bt.current){t=hr(e,t,n);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var d=l.dependencies;if(d!==null){u=l.child;for(var h=d.firstContext;h!==null;){if(h.context===r){if(l.tag===1){h=pr(-1,n&-n),h.tag=2;var w=l.updateQueue;if(w!==null){w=w.shared;var M=w.pending;M===null?h.next=h:(h.next=M.next,M.next=h),w.pending=h}}l.lanes|=n,h=l.alternate,h!==null&&(h.lanes|=n),Zl(l.return,n,t),d.lanes|=n;break}h=h.next}}else if(l.tag===10)u=l.type===t.type?null:l.child;else if(l.tag===18){if(u=l.return,u===null)throw Error(f(341));u.lanes|=n,d=u.alternate,d!==null&&(d.lanes|=n),Zl(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}Rt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Ms(t,n),s=fn(s),r=r(s),t.flags|=1,Rt(e,t,r,n),t.child;case 14:return r=t.type,s=Mn(r,t.pendingProps),s=Mn(r.type,s),Du(e,t,r,s,n);case 15:return zu(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Mn(r,s),Vo(e,t),t.tag=1,Bt(r)?(e=!0,No(t)):e=!1,Ms(t,n),Pu(t,r,s),hi(t,r,s,n),xi(null,t,r,!0,e,n);case 19:return Qu(e,t,n);case 22:return $u(e,t,n)}throw Error(f(156,t.tag))};function hc(e,t){return Pt(e,t)}function mf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function hn(e,t,n,r){return new mf(e,t,n,r)}function Fi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function pf(e){if(typeof e=="function")return Fi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ie)return 11;if(e===Fe)return 14}return 2}function Br(e,t){var n=e.alternate;return n===null?(n=hn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function tl(e,t,n,r,s,l){var u=2;if(r=e,typeof e=="function")Fi(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Me:return us(n.children,s,l,t);case Ze:u=8,s|=8;break;case ct:return e=hn(12,n,t,s|2),e.elementType=ct,e.lanes=l,e;case Le:return e=hn(13,n,t,s),e.elementType=Le,e.lanes=l,e;case H:return e=hn(19,n,t,s),e.elementType=H,e.lanes=l,e;case Ae:return nl(n,s,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case st:u=10;break e;case Et:u=9;break e;case ie:u=11;break e;case Fe:u=14;break e;case Te:u=16,r=null;break e}throw Error(f(130,e==null?e:typeof e,""))}return t=hn(u,n,t,s),t.elementType=e,t.type=r,t.lanes=l,t}function us(e,t,n,r){return e=hn(7,e,r,t),e.lanes=n,e}function nl(e,t,n,r){return e=hn(22,e,r,t),e.elementType=Ae,e.lanes=n,e.stateNode={isHidden:!1},e}function Ui(e,t,n){return e=hn(6,e,null,t),e.lanes=n,e}function bi(e,t,n){return t=hn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function hf(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=or(0),this.expirationTimes=or(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=or(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Bi(e,t,n,r,s,l,u,d,h){return e=new hf(e,t,n,d,h),t===1?(t=1,l===!0&&(t|=8)):t=0,l=hn(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ti(l),e}function gf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(p){console.error(p)}}return i(),Ki.exports=Pf(),Ki.exports}var Mc;function Af(){if(Mc)return ul;Mc=1;var i=Mf();return ul.createRoot=i.createRoot,ul.hydrateRoot=i.hydrateRoot,ul}var Rf=Af();const Tf=Vc(Rf),If="/api";async function Ce(i,p){const f=await fetch(`${If}${i}`,{...p,headers:{"Content-Type":"application/json",...p?.headers??{}}}),N=await f.json();if(!f.ok){const j=N.error?.message??"Ошибка запроса";throw new Error(j)}return N}const _e={async loadSharedConnectionConfig(){return Ce("/llm/shared-connection")},async saveSharedConnectionConfig(i){return Ce("/llm/shared-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,model:i.model,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})})},async listModels(i){return Ce("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async testConnection(i){return Ce("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async normalize(i){return Ce("/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 Ce("/history")},async loadTrace(i){return Ce(`/history/${i}`)},async loadPresets(){return Ce("/presets")},async savePreset(i){return Ce("/presets/save",{method:"POST",body:JSON.stringify(i)})},async runEval(i){return Ce("/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 Ce("/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 Ce(`/eval/run-async/${encodeURIComponent(i)}`)},async startRun(){return Ce("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(i){return Ce("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:i,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return Ce("/accounting-agent/v1/runs")},async listResults(){return Ce("/accounting-agent/v1/results")},async runTrace(i){return Ce(`/accounting-agent/v1/trace/run/${i}`)},async sendAssistantMessage(i){return Ce("/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 Ce(`/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 f=p.toString();return Ce(`/assistant/annotations${f?`?${f}`:""}`)},async saveAssistantAnnotation(i){return Ce("/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 f=p.toString();return Ce(`/autoruns/history${f?`?${f}`:""}`)},async loadAutoRunDetail(i){return Ce(`/autoruns/history/${encodeURIComponent(i)}`)},async loadAutoRunCaseDialog(i,p){return Ce(`/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 f=p.toString();return Ce(`/autoruns/annotations${f?`?${f}`:""}`)},async saveAutoRunAnnotation(i){return Ce("/autoruns/annotations",{method:"POST",body:JSON.stringify(i)})},async updateAutoRunAnnotation(i){return Ce(`/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 f=p.toString();return Ce(`/autoruns/post-analysis${f?`?${f}`:""}`)},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 f=p.toString();return Ce(`/autoruns/autogen/history${f?`?${f}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return Ce("/autoruns/autogen/personality-catalog")},async generateAutoRunQuestions(i){return Ce("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(i)})}};function tn({value:i}){return o.jsx("pre",{className:"json-view",children:JSON.stringify(i??{},null,2)})}function In({title:i,subtitle:p,actions:f,className:N,hideHeader:j,children:T}){return o.jsxs("section",{className:N?`panel-frame ${N}`:"panel-frame",children:[j?null:o.jsxs("header",{className:"panel-header",children:[o.jsxs("div",{children:[o.jsx("h2",{children:i}),p?o.jsx("p",{children:p}):null]}),f?o.jsx("div",{className:"panel-actions",children:f}):null]}),o.jsx("div",{className:"panel-body",children:T})]})}function Lf(i){const p=new Date(i);return Number.isNaN(p.getTime())?i:p.toLocaleString("ru-RU")}function Of({sessionId:i,conversation:p,statusText:f,errorMessage:N,useMock:j,appLogs:T}){const $=p.filter(Q=>Q.role==="assistant").length,Y=p.filter(Q=>Q.role==="user").length,b=p.length>0?p[p.length-1]:null;return o.jsxs(In,{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:f||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"ошибка"}),o.jsx("strong",{children:N||"нет"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"последнее сообщение"}),o.jsx("strong",{children:b?.created_at?Lf(b.created_at):"нет данных"})]})]}),o.jsx("h3",{style:{marginTop:12},children:"Последние системные логи"}),o.jsx(tn,{value:T.slice(0,120)})]})}const Df=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,zf=[/\b(?:debug_payload_json|technical_breakdown_json)\b/i,/\b(?:route_summary|semantic_profile|domain_scope|relation_patterns|account_scope)\b/i,/\b(?:coverage_report|retrieval_status|problem_unit_state|candidate_evidence)\b/i,/\b(?:graph_domain_scope|graph_runtime|selection_reason|why_included)\b/i];function $f(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function Ff(i){const p=String(i??""),f=p.match(Df);return(f?p.slice(0,f.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($=>!zf.some(Y=>Y.test($))).join(` `).trim()}function Uf(i,p,f="default"){const N=f==="technical",j=[];j.push("# Assistant conversation export"),j.push(`session_id: ${i||"n/a"}`),j.push(`export_mode: ${f}`),j.push(`exported_at: ${new Date().toISOString()}`),j.push("");for(let T=0;T{j.length!==0&&(N.push(j.join(` `)),j=[])};for(const $ of f){const Y=$.trimEnd(),b=Y.trim();if(!b){T();continue}const Q=/^Блок\s+\d+\./i.test(b),G=/^\d+\.\s/.test(b);(Q||G)&&j.length>0&&T(),j.push(Y)}return T(),N.length>0?N:[i]}function qf(i,p){const f=[],N=/\*\*(.+?)\*\*/g;let j=0,T=0,$;for(;($=N.exec(i))!==null;)$.index>j&&(f.push(o.jsx("span",{children:i.slice(j,$.index)},`${p}-t-${T}`)),T+=1),f.push(o.jsx("strong",{children:$[1]},`${p}-b-${T}`)),T+=1,j=N.lastIndex;return j0?f:[o.jsx("span",{children:i},`${p}-raw`)]}function Kf(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 Gf(i,p=40){const f=i.replace(/\s+/g," ").trim();if(f.length<=p)return f;const N=f.split(" ").slice(0,3).join(" ").trim();return N.length>=10&&N.length<=p?`${N}…`:`${f.slice(0,p-1).trimEnd()}…`}function Qc(i){return i.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Jf(i){const p=i.replace(/\r\n?/g,` `).split(` `).map(j=>j.trim()).find(Boolean),f=Qc(p??"");return(f.split("|")[0]?.trim()??f).replace(/\s+/g," ").trim()}function Yf(i){const p=i.replace(/\r\n?/g,` `).split(` `).map(N=>N.trim()).find(Boolean);return!p||!/^\d+\.\s/.test(p)?!1:Qc(p).includes("|")}function Xf(i,p){const f=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(!f)return null;const N=Jf(p)||f;return{message_id:i.message_id,source_text:f,anchor_text:N,preview_text:Gf(N)}}function Zf(i,p,f,N){return Wf(i.text).map((T,$)=>{const Y=T.split(` `),b=i.role==="assistant"&&Yf(T),Q=b?Xf(i,T):null,G=!!Q&&p?.message_id===Q?.message_id&&p?.source_text===Q?.source_text,z=Y.map((ne,Ne)=>o.jsx("p",{className:Kf(ne),children:qf(ne,`line-${$}-${Ne}`)},`line-${$}-${Ne}`));return!b||!Q?o.jsx("div",{className:"assistant-msg-block",children:z},`block-${$}`):o.jsx("div",{className:G?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(G){N();return}f(Q)},onKeyDown:ne=>{if(!(ne.key!=="Enter"&&ne.key!==" ")){if(ne.preventDefault(),G){N();return}f(Q)}},children:z},`block-${$}`)})}function Wc({sessionId:i,conversation:p,inputValue:f,onInputChange:N,selectedContextChip:j,onSelectContextChip:T,onClearContextChip:$,useMock:Y,onUseMockChange:b,onSend:Q,onClear:G,busy:z,statusText:ne,errorMessage:Ne,showCommentAction:le=!1,onCommentAssistantMessage:ce,isAssistantMessageCommented:me,canCommentAssistantMessage:Qe}){const De=x.useRef(null),We=x.useRef(!0),je=x.useRef(null),[W,de]=x.useState("idle"),[Me,Ze]=x.useState("чат");function ct(ie=!1){De.current&&(ie&&(We.current=!0),De.current.scrollTop=De.current.scrollHeight)}x.useEffect(()=>{We.current&&ct()},[p]),x.useEffect(()=>()=>{je.current!==null&&window.clearTimeout(je.current)},[]);async function st(ie){if(p.length===0)return;const Le=Uf(i,p,ie),H=await Hf(Le);Ze(ie==="technical"?"тех":"чат"),de(H?"success":"error"),je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{de("idle")},2200)}function Et(){if(!De.current)return;const ie=De.current,Le=ie.scrollHeight-ie.scrollTop-ie.clientHeight;We.current=Le<16}return o.jsx(In,{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:()=>{st("default")},disabled:p.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{st("technical")},disabled:p.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>G(),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:[ne?o.jsx("span",{className:"assistant-live-status",children:ne}):null,W==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Me,")"]}):null,W==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),Ne?o.jsx("p",{className:"error-text assistant-toolbar-error",children:Ne}):null]}),o.jsx("div",{ref:De,className:"assistant-chat-list",onScroll:Et,children:p.map((ie,Le)=>{const H=ie.role==="assistant"&&le&&typeof ce=="function"&&(typeof Qe=="function"?Qe(ie,Le):!0),Fe=ie.role==="assistant"&&typeof me=="function"?me(ie,Le):!1;return o.jsxs("article",{className:`assistant-msg ${ie.role}`,children:[o.jsxs("header",{className:"assistant-msg-head",children:[o.jsxs("div",{className:"assistant-msg-head-main",children:[o.jsx("strong",{children:bf(ie.role)}),o.jsx("span",{children:Bf(ie.created_at)})]}),ie.role==="assistant"&&le?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:()=>ce?.(ie,Le),disabled:!H,title:H?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":H?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:o.jsx(Vf,{commented:Fe})})}):null]}),o.jsx("div",{className:"assistant-msg-body",children:Zf(ie,j,T,$)}),ie.role==="assistant"&&ie.debug?o.jsxs("details",{className:"assistant-debug",children:[o.jsx("summary",{children:"Показать технический разбор"}),o.jsx(tn,{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:f,onChange:ie=>N(ie.target.value),rows:4,placeholder:j?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),o.jsxs("div",{className:"button-row assistant-send-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:Y,onChange:ie=>b(ie.target.checked)}),"Mock-режим"]}),o.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{ct(!0),Q()},disabled:z||!f.trim(),children:z?"Выполняю...":"Отправить"})]})]})]})})}const cl="http://127.0.0.1:1234/v1",Ac="https://api.openai.com/v1",hl="qwen2.5-14b-instruct-1m",ua="unsloth/qwen3-30b-a3b-instruct-2507",em=[{value:hl,label:"Qwen2.5 14B Instruct 1M"},{value:ua,label:"Qwen3 30B A3B Instruct 2507"}];function tm(i){return i.llmProvider!=="local"?"openai":i.model===ua?"local_qwen3":i.model===hl?"local_qwen25":"local_custom"}function nm(i,p){const f=new Map;if(p)for(const N of em)f.set(N.value,N);for(const N of i)f.has(N)||f.set(N,{value:N,label:N});return Array.from(f.values())}function oa({value:i,modelOptions:p,modelsBusy:f,onChange:N,onReloadModels:j,onTestConnection:T,onSaveLocalConfig:$,lastStatus:Y,busy:b,embedded:Q=!1}){const G=i.llmProvider==="local",z=tm(i),ne=nm(p,G),Ne=ne.some(W=>W.value===i.model),[le,ce]=x.useState(String(i.temperature)),[me,Qe]=x.useState(String(i.maxOutputTokens));x.useEffect(()=>{ce(String(i.temperature))},[i.temperature]),x.useEffect(()=>{Qe(String(i.maxOutputTokens))},[i.maxOutputTokens]);const De=W=>{const de=W.replace(",",".").trim();if(!de){ce(String(i.temperature));return}const Me=Number(de);if(!Number.isFinite(Me)){ce(String(i.temperature));return}N({...i,temperature:Me}),ce(String(Me))},We=W=>{const de=W.trim();if(!de){Qe(String(i.maxOutputTokens));return}const Me=Number.parseInt(de,10);if(!Number.isFinite(Me)||Me<=0){Qe(String(i.maxOutputTokens));return}N({...i,maxOutputTokens:Me}),Qe(String(Me))},je=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{children:["Provider",o.jsxs("select",{value:z,onChange:W=>{const de=W.target.value;if(de==="openai"){N({...i,llmProvider:"openai",baseUrl:Ac});return}if(de==="local_qwen25"){N({...i,llmProvider:"local",model:hl,baseUrl:cl});return}if(de==="local_qwen3"){N({...i,llmProvider:"local",model:ua,baseUrl:cl});return}N({...i,llmProvider:"local",model:i.llmProvider==="local"?i.model:hl,baseUrl:cl})},children:[o.jsx("option",{value:"openai",children:"OpenAI (token)"}),o.jsx("option",{value:"local_qwen25",children:"Qwen2.5 14B Instruct 1M (Local LM Studio)"}),o.jsx("option",{value:"local_qwen3",children:"Qwen3 30B A3B Instruct 2507 (Local LM Studio)"}),o.jsx("option",{value:"local_custom",children:"Local custom (LM Studio / OpenAI-compatible)"})]})]}),o.jsxs("label",{children:["Model",o.jsxs("select",{value:Ne?i.model:"__manual__",onChange:W=>{const de=W.target.value;de!=="__manual__"&&N({...i,model:de})},children:[o.jsx("option",{value:"__manual__",children:"Manual input"}),ne.map(W=>o.jsx("option",{value:W.value,children:W.label},W.value))]})]}),o.jsxs("label",{children:["Model ID (manual / current)",o.jsx("input",{value:i.model,onChange:W=>N({...i,model:W.target.value}),placeholder:"qwen2.5-14b-instruct-1m or unsloth/qwen3-30b-a3b-instruct-2507"})]}),G?null:o.jsxs("label",{className:"full-width",children:["OpenAI API Key",o.jsx("input",{type:"password",value:i.apiKey,onChange:W=>N({...i,apiKey:W.target.value}),placeholder:"sk-..."})]}),o.jsxs("label",{className:G?"full-width":void 0,children:[G?"Local server base URL":"Base URL",o.jsx("input",{value:i.baseUrl,onChange:W=>N({...i,baseUrl:W.target.value}),placeholder:G?cl:Ac})]}),o.jsxs("label",{children:["Temperature",o.jsx("input",{type:"number",step:"0.1",value:le,onChange:W=>ce(W.target.value),onBlur:W=>De(W.target.value),onKeyDown:W=>{W.key==="Enter"&&De(W.target.value)}})]}),o.jsxs("label",{children:["Max output tokens",o.jsx("input",{type:"number",value:me,onChange:W=>Qe(W.target.value),onBlur:W=>We(W.target.value),onKeyDown:W=>{W.key==="Enter"&&We(W.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:b||f,children:f?"Loading models...":"Load model list"}),o.jsx("button",{type:"button",onClick:()=>T(),disabled:b,children:b?"Checking...":"Test connection"})]})]});return Q?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsxs("div",{className:"embedded-panel-section-header",children:[o.jsxs("div",{children:[o.jsx("h4",{children:"LLM Connector"}),o.jsx("p",{children:"Switch between OpenAI cloud and local OpenAI-compatible server."})]}),o.jsx("span",{className:"status-chip",children:Y||"Status: not checked"})]}),je]}):o.jsx(In,{title:"LLM Connector",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:o.jsx("span",{className:"status-chip",children:Y||"Status: not checked"}),children:je})}function la({value:i,onChange:p,presets:f,selectedPresetId:N,onSelectPreset:j,onLoadPreset:T,onSavePreset:$,onResetDefaults:Y,onDiffPrevious:b,presetName:Q,onPresetNameChange:G,diffSummary:z,embedded:ne=!1}){const Ne=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"prompt-manager-grid",children:[o.jsxs("label",{children:["Системный prompt",o.jsx("textarea",{value:i.systemPrompt,onChange:le=>p({...i,systemPrompt:le.target.value}),rows:6})]}),o.jsxs("label",{children:["Developer / Instruction prompt",o.jsx("textarea",{value:i.developerPrompt,onChange:le=>p({...i,developerPrompt:le.target.value}),rows:6})]}),o.jsxs("label",{children:["Domain prompt",o.jsx("textarea",{value:i.domainPrompt,onChange:le=>p({...i,domainPrompt:le.target.value}),rows:6})]}),o.jsxs("label",{children:["Schema notes",o.jsx("textarea",{value:i.schemaNotes,onChange:le=>p({...i,schemaNotes:le.target.value}),rows:6})]}),o.jsxs("label",{className:"full-width",children:["Few-shot examples",o.jsx("textarea",{value:i.fewShotExamples,onChange:le=>p({...i,fewShotExamples:le.target.value}),rows:8})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("select",{value:N,onChange:le=>j(le.target.value),children:[o.jsx("option",{value:"",children:"Выберите preset..."}),f.map(le=>o.jsx("option",{value:le.id,children:le.name},le.id))]}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Загрузить preset"}),o.jsx("input",{value:Q,onChange:le=>G(le.target.value),placeholder:"Имя для сохранения"}),o.jsx("button",{type:"button",onClick:()=>$(),children:"Сохранить preset"}),o.jsx("button",{type:"button",onClick:()=>b(),children:"Diff с предыдущим"}),o.jsx("button",{type:"button",onClick:()=>Y(),children:"Сбросить к default"})]}),z?o.jsx("p",{className:"diff-summary",children:z}):null]});return ne?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsx("div",{className:"embedded-panel-section-header",children:o.jsxs("div",{children:[o.jsx("h4",{children:"Prompt Manager"}),o.jsx("p",{children:"Системный, developer и domain уровни управляются отдельно."})]})}),Ne]}):o.jsx(In,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:Ne})}const Yi={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},dl="needs_dialog_policy_fix",Nt="__all__",gl="__live__:",Rc="ndc_autoruns_ui_config_v1",Tc="ndc-autoruns-save",Xi=["Анализ запроса","Получение данных","Подготовка ответа"];function rm(i,p){const f=i.trim();if(!f)return"";if(!p)return f;const N=f.toLowerCase(),j=p.anchor_text.trim(),T=j.toLowerCase();return T&&N.includes(T)?f:`По выбранному объекту "${j}": ${f}`}const ia=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function sm(i=ia){return i.reduce((p,f)=>(p[f.id]=f.defaultPrompt,p),{})}const Ic={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:sm(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function Zi(i){const p=String(i??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(p)?p:""}function Lc(i){const p=typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):160;return Math.max(110,Math.min(520,p))}function om(i){const p=i.getFullYear(),f=String(i.getMonth()+1).padStart(2,"0"),N=String(i.getDate()).padStart(2,"0"),j=String(i.getHours()).padStart(2,"0"),T=String(i.getMinutes()).padStart(2,"0");return`${p}-${f}-${N}T${j}:${T}`}function Oc(){const i=new Date;return i.setDate(i.getDate()-14),om(i)}function fl(i){if(!i.trim())return;const p=Date.parse(i);if(Number.isFinite(p))return new Date(p).toISOString()}function vr(i){if(!i)return"нет данных";const p=Date.parse(i);return Number.isFinite(p)?new Date(p).toLocaleString("ru-RU"):i}function lm(i,p){return p<=0?0:Math.max(0,Math.min(100,Number((i/p*100).toFixed(1))))}function ml(i){return typeof i!="number"?"нет данных":`${i.toFixed(1)}%`}function im(i){return i==="assistant_stage1"?"assistant/s1":i==="assistant_stage2"?"assistant/s2":i==="assistant_p0"?"assistant/p0":i}function Dc(i){return i==="up"?"Рост":i==="down"?"Регресс":"Без изменений"}function am(i,p){return i.find(f=>f.case_id===p)??null}function ea(i){const p=Math.max(1,Math.min(5,Math.round(i)));return`${"●".repeat(p)}${"○".repeat(5-p)}`}function zc(i){return i.length===0?o.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):o.jsx("div",{className:"autoruns-coverage-list",children:i.map(p=>{const f=lm(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," (",f,"%)"]})]}),o.jsx("div",{className:"autoruns-coverage-bar",children:o.jsx("div",{style:{width:`${f}%`}})})]},p.domain)})})}function pl(i){return`${gl}${i}`}function Ds(i){return i.startsWith(gl)}function $c(i){return i.startsWith(gl)?i.slice(gl.length):""}function qc(i){const p=i.report_summary?.run_timestamp??i.created_at,f=Math.max(0,i.total_cases-i.completed_cases);return{run_id:pl(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:f,domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]}}function po(i,p){const f=qc(i),N=i.cases.map(G=>({case_id:G.case_id,domain:null,query_class:null,status:G.status==="completed"?"closed":G.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${i.run_id}-${G.case_id}`,dialog_available:G.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),T=p!==Nt&&N.some(G=>G.case_id===p)?p:N.length>0?Nt:"",$={ok:!0,run:f,coverage:{closed_cases:i.completed_cases,open_cases:Math.max(0,i.total_cases-i.completed_cases),domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]},cases:N,annotations_summary:{total:0},report:i.report_summary?{run_id:i.report_summary.run_id,run_timestamp:i.report_summary.run_timestamp,score_index:i.report_summary.score_index,cases_total:i.report_summary.cases_total,analysis_date:i.report_summary.analysis_date??i.analysis_date??null}:{}},Y=[];let b=0;if(T===Nt)for(const G of i.cases)for(let z=0;zz.case_id===T)??null;for(let z=0;z<(G?.messages.length??0);z+=1){const ne=G?.messages[z];ne&&Y.push({...ne,message_index:z,case_id:T,case_message_index:z,commented:!1,annotation:null})}}const Q={ok:!0,run_id:f.run_id,case_id:T,source:"assistant_session",session_id:T===Nt?`${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:Q,caseId:T}}function um({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 Fc({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 cm(){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 dm({connection:i,modelOptions:p,modelsBusy:f,connectionStatus:N,connectionBusy:j,onConnectionChange:T,onReloadModels:$,onSaveLocalConfig:Y,onTestConnection:b,prompts:Q,onPromptsChange:G,promptPresets:z,selectedPresetId:ne,onSelectPreset:Ne,onLoadPreset:le,onSavePreset:ce,onResetDefaults:me,onDiffPrevious:Qe,presetName:De,onPresetNameChange:We,diffSummary:je,assistantPromptVersion:W,decompositionPromptVersion:de,showSettingsMode:Me,showAutoRunsMode:Ze,showAssistantMode:ct,showDecompositionMode:st,showProgressMode:Et,showCommentsMode:ie,onLog:Le}){const[H,Fe]=x.useState({...Yi,fromLocal:Oc()}),[Te,Ae]=x.useState(""),[I,X]=x.useState(null),[O,y]=x.useState(null),[C,J]=x.useState(null),[oe,pe]=x.useState([]),[ae,Se]=x.useState("all"),[ge,ve]=x.useState(!1),[Ee,gn]=x.useState(null),[vn,Yn]=x.useState([]),[Ln,Xn]=x.useState(""),[Pe,qt]=x.useState(""),[ot,dt]=x.useState(""),[lt,yn]=x.useState(ia),[re,It]=x.useState(Ic),[tt,Vr]=x.useState([]),[nn,xn]=x.useState(""),[xt,_n]=x.useState([]),[Oe,rn]=x.useState(null),[On,xr]=x.useState(null),[Dn,Qr]=x.useState(!1),[Sn,sn]=x.useState(!1),[Lt,Zn]=x.useState(!1),[Kt,on]=x.useState(!1),[Ot,_r]=x.useState(!1),[zn,Sr]=x.useState(!1),[$n,wr]=x.useState(!1),[ze,er]=x.useState(!1),[Dt,Fn]=x.useState(""),[wn,Ge]=x.useState(""),[nt,ln]=x.useState(""),[zt,Un]=x.useState([]),[bn,Gt]=x.useState([]),[jr,_t]=x.useState(""),[jn,an]=x.useState(null),[tr,Wr]=x.useState(!1),[Re,Pt]=x.useState(!1),[nr,Bn]=x.useState(""),[cs,D]=x.useState(""),[zs,Mt]=x.useState(String(Yi.limit)),[qr,St]=x.useState(String(Ic.count)),[rr,Kr]=x.useState(160),[ue,Ue]=x.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:dl,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[ye,be]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),sr=x.useRef(!1),Hn=x.useRef(null),Vn=x.useMemo(()=>lt.find(a=>a.id===re.personalityId)??lt[0]??ia[0],[re.personalityId,lt]),$t=x.useMemo(()=>tt.find(a=>a.generation_id===nn)??tt[0]??null,[tt,nn]),kn=O?am(O.cases,ot):null,At=x.useMemo(()=>ge?oe.filter(a=>!a.resolved):oe,[oe,ge]),ke=At.find(a=>a.annotation_id===Ln)??null,ds=C?.messages.find(a=>a.message_index===ue.messageIndex)??null,$s=x.useMemo(()=>{if(!C||ue.messageIndex<0)return null;for(let a=ue.messageIndex-1;a>=0;a-=1){const c=C.messages[a];if(c?.role==="user")return c}return null},[ue.messageIndex,C]),Cn=x.useMemo(()=>{const a=new Map;for(const c of bn)c.message_id&&a.set(c.message_id,c);return a},[bn]),kr=ye.messageIndex>=0?zt[ye.messageIndex]??null:null,or=x.useMemo(()=>{if(ye.messageIndex<0)return null;for(let a=ye.messageIndex-1;a>=0;a-=1){const c=zt[a];if(c?.role==="user")return c}return null},[ye.messageIndex,zt]),it=x.useMemo(()=>{const a=At.map(v=>({source:"autorun",key:`autorun:${v.annotation_id}`,updated_at:v.updated_at,rating:v.rating,autorun:v,assistant:null})),c=bn.map(v=>({source:"assistant_live",key:`assistant:${v.annotation_id}`,updated_at:v.updated_at,rating:v.rating,autorun:null,assistant:v}));return[...a,...c].sort((v,R)=>Date.parse(R.updated_at)-Date.parse(v.updated_at))},[bn,At]),lr=x.useMemo(()=>{if(it.length===0)return null;const a=it.reduce((c,v)=>c+v.rating,0)/it.length;return Number(a.toFixed(2))},[it]),ir=x.useMemo(()=>{const a=[...I?.items??[]];return Oe&&a.unshift(qc(Oe)),Pe&&!a.some(c=>c.run_id===Pe)&&O?.run&&a.unshift(O.run),a},[Oe,I?.items,O?.run,Pe]),F=x.useCallback(a=>{Le?.(`[autoruns] ${a}`)},[Le]),ar=x.useCallback(async a=>{const c=String(a??"").trim();if(!c){Gt([]);return}try{const v=await _e.loadAssistantAnnotations({session_id:c,limit:400});Gt(v.items??[])}catch(v){const R=v instanceof Error?v.message:String(v);F(`Assistant live annotations load error: ${R}`)}},[F]),Nn=x.useCallback(a=>{be(c=>c.saving&&!a?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),Cr=x.useCallback(async(a,c)=>{a.stopPropagation(),a.preventDefault();const v=String(c??"").trim();if(v)try{if(navigator?.clipboard?.writeText)await navigator.clipboard.writeText(v);else{const R=document.createElement("textarea");R.value=v,R.setAttribute("readonly","true"),R.style.position="fixed",R.style.opacity="0",document.body.appendChild(R),R.select(),document.execCommand("copy"),document.body.removeChild(R)}F(`run id copied: ${v}`)}catch(R){const fe=R instanceof Error?R.message:String(R);Ge(`Копирование run id: ${fe}`),F(`copy run id error: ${fe}`)}},[F]);function fs(){let a=0;Bn(Xi[0]);const c=window.setInterval(()=>{a=Math.min(a+1,Xi.length-1),Bn(Xi[a])},650);return()=>window.clearInterval(c)}const m=x.useCallback(()=>{ln(""),Un([]),Gt([]),_t(""),an(null),Bn(""),D(""),Nn({force:!0}),F("Live-чат ассистента в истории автопрогонов сброшен.")},[Nn,F]),E=x.useCallback(async()=>{const a=rm(jr,jn);if(!a)return;Pt(!0),D(""),_t(""),Un(v=>[...v,{message_id:`autoruns-live-${Date.now()}`,session_id:nt||"pending",role:"user",text:a,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=fs();try{const v=await _e.sendAssistantMessage({connection:i,prompts:Q,userMessage:a,sessionId:nt||void 0,promptVersion:W,useMock:tr});ln(v.session_id),Un(v.conversation),await ar(v.session_id),Bn("Ответ готов"),F(`Live-ответ ассистента получен: trace=${v.debug.trace_id}`)}catch(v){const R=v instanceof Error?v.message:String(v);D(R),Bn("Ошибка ассистента"),F(`Live-чат ассистента: ошибка отправки сообщения: ${R}`)}finally{c(),Pt(!1)}},[jr,jn,nt,tr,W,i,ar,F,Q]),k=x.useCallback(a=>{const c=a.trim();if(!c){Mt(String(H.limit));return}if(!/^\d+$/.test(c)){Mt(String(H.limit));return}const v=Number.parseInt(c,10);if(!Number.isFinite(v)){Mt(String(H.limit));return}const R=Math.max(1,Math.min(500,v));R!==H.limit&&Fe(fe=>({...fe,limit:R})),Mt(String(R))},[H.limit]),te=x.useCallback(a=>{const c=a.trim();if(!c){St(String(re.count));return}if(!/^\d+$/.test(c)){St(String(re.count));return}const v=Number.parseInt(c,10);if(!Number.isFinite(v)){St(String(re.count));return}const R=Math.max(1,Math.min(200,v));R!==re.count&&It(fe=>({...fe,count:R})),St(String(R))},[re.count]),Ie=x.useCallback(a=>{Kr(Lc(a))},[]),gt=x.useCallback(a=>{const c=a.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&Ie(c)},[Ie]),Ft=x.useCallback(async()=>{er(!0);try{const a=await _e.loadAutoRunAnnotations({limit:800,manual_case_decision:ae});pe(a.items),gn(a.manual_case_decision_schema??null),Yn(a.available_manual_case_decisions??[]),Xn(c=>a.items.length===0?"":a.items.some(v=>v.annotation_id===c)?c:a.items[0].annotation_id)}catch(a){F(`Annotations load error: ${a instanceof Error?a.message:String(a)}`)}finally{er(!1)}},[ae,F]),Jt=x.useCallback(async()=>{on(!0);try{const a=await _e.loadAutoRunAutogenHistory({limit:180});Vr(a.items)}catch(a){F(`Autogen history load error: ${a instanceof Error?a.message:String(a)}`)}finally{on(!1)}},[F]),Nr=x.useCallback(async()=>{try{const c=(await _e.loadAutoRunAutogenPersonalityCatalog()).items.map(v=>({id:String(v.id??"").trim(),label:String(v.label??"").trim(),domain:typeof v.domain=="string"?v.domain.trim():"",defaultPrompt:String(v.default_prompt??"").trim()})).filter(v=>v.id.length>0&&v.label.length>0);if(c.length===0)return;yn(c.map(v=>({id:v.id,label:v.label,domain:v.domain||"",defaultPrompt:v.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(a){F(`Autogen personality catalog load error: ${a instanceof Error?a.message:String(a)}`)}},[F]),ft=x.useCallback(async()=>{Zn(!0);try{const a=await _e.loadAutoRunPostAnalysis({run_id:Pe&&!Ds(Pe)?Pe:void 0,limit_per_queue:30,annotation_limit:1500,from:fl(H.fromLocal),to:fl(H.toLocal),target:H.target,mode:H.mode,use_mock:H.useMock,prompt_contains:H.promptContains.trim()||void 0});xr(a)}catch(a){F(`Post-analysis load error: ${a instanceof Error?a.message:String(a)}`),xr(null)}finally{Zn(!1)}},[H.fromLocal,H.mode,H.promptContains,H.target,H.toLocal,H.useMock,F,Pe]),vl=x.useCallback(async()=>{Qr(!0),Ge("");try{const a=re.personalityPrompts[re.personalityId]??"",c=[Q.systemPrompt,Q.developerPrompt,Q.domainPrompt,Q.schemaNotes,Q.fewShotExamples].join(` `).slice(0,900),v=await _e.generateAutoRunQuestions({mode:re.mode,count:re.count,domain:Vn.domain||void 0,persist_to_eval_cases:re.persistToEvalCases,generated_by:re.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:W,decomposition_prompt_version:de,prompt_fingerprint:c,autogen_personality_id:Vn.id,autogen_personality_prompt:a.trim()||void 0}});F(`Generated ${v.generation.count} questions (${v.generation.mode}) id=${v.generation.generation_id}`+(v.generation.saved_case_set_file?` saved=${v.generation.saved_case_set_file}`:"")),xn(v.generation.generation_id),_n([...v.generation.questions??[]]),await Jt()}catch(a){const c=a instanceof Error?a.message:String(a);Ge(`Автогенерация: ${c}`),F(`Autogen generate error: ${c}`)}finally{Qr(!1)}},[W,re.count,re.generatedBy,re.mode,re.personalityId,re.personalityPrompts,re.persistToEvalCases,i.apiKey,i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature,de,Jt,F,Q.developerPrompt,Q.domainPrompt,Q.fewShotExamples,Q.schemaNotes,Q.systemPrompt,Vn.domain,Vn.id]),Er=x.useCallback(async(a,c)=>{if(Ds(a)){const v=$c(a);if(Oe&&Oe.job_id===v){const R=po(Oe,c);qt(a),dt(R.caseId),J(R.dialog);return}J(null);return}wr(!0);try{const v=await _e.loadAutoRunCaseDialog(a,c);J(v)}catch(v){const R=v instanceof Error?v.message:String(v);Ge(`Диалог кейса: ${R}`),J(null),F(`Dialog load error for ${a}/${c}: ${R}`)}finally{wr(!1)}},[Oe,F]),Ut=x.useCallback(async(a,c)=>{if(Ds(a)){const v=$c(a);if(Oe&&Oe.job_id===v){const R=po(Oe,c??Nt);qt(a),dt(R.caseId),y(R.detail),J(R.dialog);return}qt(a),dt(""),y(null),J(null);return}Sr(!0);try{const v=await _e.loadAutoRunDetail(a);y(v);const R=(c&&(c===Nt||v.cases.some(fe=>fe.case_id===c))?c:"")||(v.cases.length>0?Nt:"")||"";qt(a),dt(R),R?await Er(a,R):J(null)}catch(v){const R=v instanceof Error?v.message:String(v);Ge(`Детализация прогона: ${R}`),y(null),J(null),F(`Run detail load error for ${a}: ${R}`)}finally{Sr(!1)}},[Oe,Er,F]),Gr=x.useCallback(async a=>{_r(!0),Ge("");try{const c=await _e.loadAutoRunsHistory({from:fl(H.fromLocal),to:fl(H.toLocal),target:H.target,mode:H.mode,use_mock:H.useMock,prompt_contains:H.promptContains.trim()||void 0,limit:H.limit});if(X(c),c.items.length===0){qt(""),dt(""),y(null),J(null);return}const v=a?.keepSelection??!0,R=a?.preferredRunId??"",fe=a?.preferredCaseId??"",Je=v&&R&&c.items.some(Yt=>Yt.run_id===R)?R:c.items[0].run_id;await Ut(Je,v?fe:void 0),ft()}catch(c){const v=c instanceof Error?c.message:String(c);Ge(`История прогонов: ${v}`),F(`History load error: ${v}`)}finally{_r(!1)}},[H.fromLocal,H.limit,H.mode,H.promptContains,H.target,H.toLocal,H.useMock,ft,Ut,F]),un=x.useCallback(()=>{Hn.current!==null&&(window.clearTimeout(Hn.current),Hn.current=null)},[]),Pr=x.useCallback(async a=>{try{const c=await _e.loadEvalRunAsyncStatus(a);rn(c.job);const v=pl(a);if(Pe===v){const R=po(c.job,ot||Nt);y(R.detail),J(R.dialog),dt(R.caseId)}if(c.job.status==="completed"){un(),sn(!1);const R=c.job.report_summary?.run_id??c.job.run_id;await Gr({keepSelection:!0,preferredRunId:R||Pe,preferredCaseId:Nt}),await Jt(),rn(null);return}if(c.job.status==="failed"){un(),sn(!1),Ge(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),F(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}un(),Hn.current=window.setTimeout(()=>{Pr(a)},500)}catch(c){un(),sn(!1);const v=c instanceof Error?c.message:String(c);Ge(`Запуск прогонов: ${v}`),F(`Autogen async status error: ${v}`)}},[Jt,Gr,F,ot,Pe,un]),ho=x.useCallback(async()=>{un(),sn(!0),Ge("");try{const a=$t;if(!a)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const c=xt.map(Wn=>Wn.trim()).filter(Wn=>Wn.length>0);if(c.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const v=H.useMock==="true",R=Zi(Te),Je=(await _e.startEvalRunAsync({connection:i,prompts:Q,promptVersion:W,mode:"single-pass-strict",caseSetFile:a.saved_case_set_file??void 0,useMock:v,evalTarget:"assistant_stage1",questions:c,analysisDate:R||void 0})).job;rn(Je);const Yt=pl(Je.job_id),Ye=po(Je,Nt);qt(Yt),dt(Ye.caseId),y(Ye.detail),J(Ye.dialog),F(`Запущен async-прогон job=${Je.job_id}, run_id=${Je.run_id}, вопросов=${c.length}`+(a.saved_case_set_file?`, base_case_set=${a.saved_case_set_file}`:"")+(R?`, analysis_date=${R}`:", analysis_date=current_state")),Pr(Je.job_id)}catch(a){const c=a instanceof Error?a.message:String(a);Ge(`Запуск прогонов: ${c}`),F(`Autogen run error: ${c}`),sn(!1)}},[Te,W,i,xt,H.useMock,F,Pr,Q,$t,un]),yl=x.useCallback(a=>{if(a.role!=="assistant")return;const c=a.case_id??ot,v=a.case_message_index??a.message_index;Ue({open:!0,caseId:c,caseMessageIndex:v,messageIndex:a.message_index,rating:a.annotation?.rating??3,comment:a.annotation?.comment??"",manualCaseDecision:a.annotation?.manual_case_decision??dl,annotationAuthor:a.annotation?.annotation_author??re.generatedBy,saving:!1,error:""})},[re.generatedBy,ot]),Qn=x.useCallback(a=>{Ue(c=>c.saving&&!a?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:dl,annotationAuthor:re.generatedBy,saving:!1,error:""})},[re.generatedBy]),Jr=x.useCallback(async()=>{const a=Pe,c=ue.caseId,v=ue.caseMessageIndex;if(!(!a||!c||v<0)){if(Ds(a)){Ue(R=>({...R,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ue.comment.trim()){Ue(R=>({...R,error:"Добавьте комментарий."}));return}Ue(R=>({...R,saving:!0,error:""}));try{await _e.saveAutoRunAnnotation({run_id:a,case_id:c,message_index:v,rating:ue.rating,comment:ue.comment.trim(),manual_case_decision:ue.manualCaseDecision,annotation_author:ue.annotationAuthor.trim()||void 0}),Qn({force:!0}),Promise.all([Ut(a,ot),Ft(),ft()]).catch(R=>{const fe=R instanceof Error?R.message:String(R);Ge(`Обновление после комментария: ${fe}`),F(`Comment refresh error: ${fe}`)})}catch(R){Ue(fe=>({...fe,saving:!1,error:R instanceof Error?R.message:String(R)}))}}},[Qn,ue.annotationAuthor,ue.caseId,ue.caseMessageIndex,ue.comment,ue.manualCaseDecision,ue.rating,Ft,ft,Ut,F,ot,Pe]),Mr=x.useCallback(a=>a.role==="assistant",[]),ms=x.useCallback(a=>a.role==="assistant"&&Cn.has(a.message_id),[Cn]),xl=x.useCallback((a,c)=>{if(a.role!=="assistant")return;const v=nt.trim(),R=String(a.session_id??"").trim();if(!(v||R)){D("Сначала получите ответ ассистента в активной сессии.");return}!v&&R&&ln(R);const Je=Cn.get(a.message_id)??null;D(""),be({open:!0,messageIndex:c,rating:Je?.rating??3,comment:Je?.comment??"",annotationAuthor:Je?.annotation_author??"manual_reviewer",saving:!1,error:""})},[Cn,nt]),_l=x.useCallback(async()=>{if(ye.messageIndex<0)return;if(!ye.comment.trim()){be(v=>({...v,error:"Добавьте комментарий."}));return}const a=zt[ye.messageIndex]??null,c=nt.trim()||(a?.role==="assistant"?String(a.session_id??"").trim():"");if(!c){be(v=>({...v,error:"Сессия ассистента не найдена."}));return}be(v=>({...v,saving:!0,error:""}));try{const v=await _e.saveAssistantAnnotation({session_id:c,message_index:ye.messageIndex,rating:ye.rating,comment:ye.comment.trim(),annotation_author:ye.annotationAuthor.trim()||void 0});Gt(R=>{const fe=[...R],Je=fe.findIndex(Yt=>Yt.annotation_id===v.annotation.annotation_id);return Je>=0?fe[Je]=v.annotation:fe.unshift(v.annotation),fe.sort((Yt,Ye)=>Date.parse(Ye.updated_at)-Date.parse(Yt.updated_at))}),Nn({force:!0})}catch(v){const R=v instanceof Error?v.message:String(v);be(fe=>({...fe,saving:!1,error:R}))}},[ye.annotationAuthor,ye.comment,ye.messageIndex,ye.rating,zt,nt,Nn]),ps=x.useCallback(a=>{pe(c=>c.map(v=>v.annotation_id===a.annotation_id?{...v,...a}:v)),J(c=>c&&{...c,annotations:c.annotations.map(v=>v.annotation_id===a.annotation_id?a:v),messages:c.messages.map(v=>!v.annotation||v.annotation.annotation_id!==a.annotation_id?v:{...v,commented:!0,annotation:a})})},[]),Yr=x.useCallback(async(a,c)=>{if(a.annotation_id){if(Ds(a.run_id)){Ge("Статус выполнения можно менять только для завершённых прогонов.");return}Fn(a.annotation_id);try{const v=await _e.updateAutoRunAnnotation({annotation_id:a.annotation_id,resolved:c,resolved_by:re.generatedBy||void 0});ps(v.annotation),ft()}catch(v){const R=v instanceof Error?v.message:String(v);Ge(`Смена статуса кейса: ${R}`),F(`Annotation resolve toggle error: ${R}`)}finally{Fn("")}}},[ps,re.generatedBy,ft,F]),hs=x.useCallback(async a=>{Xn(a.annotation_id),await Ut(a.run_id,a.case_id),I?.items.some(c=>c.run_id===a.run_id)||Ge("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[I?.items,Ut]);x.useEffect(()=>{sr.current||(sr.current=!0,Gr({keepSelection:!1}),Jt(),Nr(),ft())},[Jt,Nr,Gr,ft]),x.useEffect(()=>{sr.current&&Ft()},[ae,Ft]),x.useEffect(()=>{Xn(a=>At.length===0?"":At.some(c=>c.annotation_id===a)?a:At[0].annotation_id)},[At]),x.useEffect(()=>{xn(a=>tt.length===0?"":a&&tt.some(c=>c.generation_id===a)?a:tt[0].generation_id)},[tt]),x.useEffect(()=>{if(!$t){_n([]);return}_n([...$t.questions])},[$t?.generation_id]),x.useEffect(()=>{Mt(String(H.limit))},[H.limit]),x.useEffect(()=>{St(String(re.count))},[re.count]),x.useEffect(()=>{if(!nt.trim()){Gt([]);return}ar(nt)},[nt,ar]),x.useEffect(()=>{if(!Oe)return;const a=pl(Oe.job_id);if(Pe!==a)return;const c=po(Oe,ot||Nt);y(c.detail),J(c.dialog),dt(c.caseId)},[Oe,ot,Pe]),x.useEffect(()=>()=>{un()},[un]),x.useEffect(()=>{lt.length!==0&&It(a=>{let c=!1;const v={...a.personalityPrompts};for(const fe of lt)(typeof v[fe.id]!="string"||v[fe.id].trim().length===0)&&(v[fe.id]=fe.defaultPrompt,c=!0);let R=a.personalityId;return lt.some(fe=>fe.id===a.personalityId)||(R=lt[0].id,c=!0),c?{...a,personalityId:R,personalityPrompts:v}:a})},[lt]),x.useEffect(()=>{const a=localStorage.getItem(Rc);if(a)try{const c=JSON.parse(a);if(c.filters){const v=c.filters;Fe(R=>({...R,...v,limit:typeof v.limit=="number"?Math.max(1,Math.min(500,v.limit)):R.limit}))}typeof c.analysisDate=="string"&&Ae(Zi(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&Kr(Lc(c.autogenPersonalityPromptHeight)),c.autoGenSettings&&It(v=>{const R={...v.personalityPrompts},fe=c.autoGenSettings?.personalityPrompts??{};for(const[Yt,Ye]of Object.entries(fe))typeof Ye=="string"&&Yt.trim().length>0&&(R[Yt.trim()]=Ye);const Je=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():v.personalityId;return{...v,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"?c.autoGenSettings.mode:v.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):v.count,personalityId:Je,personalityPrompts:R,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:v.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:v.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&Se(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&ve(c.hideResolvedAnnotations)}catch{}},[]);const Fs=x.useCallback(()=>{const a={filters:H,analysisDate:Te,autogenPersonalityPromptHeight:rr,autoGenSettings:{mode:re.mode,count:re.count,personalityId:re.personalityId,personalityPrompts:re.personalityPrompts,persistToEvalCases:re.persistToEvalCases,generatedBy:re.generatedBy},annotationDecisionFilter:ae,hideResolvedAnnotations:ge};localStorage.setItem(Rc,JSON.stringify(a))},[Te,ae,re,rr,H,ge]);return x.useEffect(()=>{const a=()=>{Fs(),F("Сохранены настройки панели автопрогонов.")};return window.addEventListener(Tc,a),()=>{window.removeEventListener(Tc,a)}},[F,Fs]),o.jsxs(In,{className:"autoruns-frame",title:"",hideHeader:!0,children:[o.jsxs("div",{className:"autoruns-columns",children:[Me?o.jsxs("section",{className:"autoruns-col autoruns-settings-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Настройки"})}),o.jsxs("div",{className:"autoruns-settings-stack",children:[o.jsx(oa,{embedded:!0,value:i,modelOptions:p,modelsBusy:f,onChange:T,onReloadModels:$,onSaveLocalConfig:Y,onTestConnection:b,lastStatus:N,busy:j}),o.jsx(la,{embedded:!0,value:Q,onChange:G,presets:z,selectedPresetId:ne,onSelectPreset:Ne,onLoadPreset:le,onSavePreset:ce,onResetDefaults:me,onDiffPrevious:Qe,presetName:De,onPresetNameChange:We,diffSummary:je})]})]}):null,Ze?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:H.fromLocal,onChange:a=>Fe(c=>({...c,fromLocal:a.target.value}))})]}),o.jsxs("label",{children:["Дата по",o.jsx("input",{type:"datetime-local",value:H.toLocal,onChange:a=>Fe(c=>({...c,toLocal:a.target.value}))})]}),o.jsxs("label",{children:["Целевой контур",o.jsxs("select",{value:H.target,onChange:a=>Fe(c=>({...c,target:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(I?.available.targets??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Режим",o.jsxs("select",{value:H.mode,onChange:a=>Fe(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(I?.available.modes??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Использовать mock",o.jsxs("select",{value:H.useMock,onChange:a=>Fe(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:zs,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&Mt(c)},onBlur:a=>k(a.target.value),onKeyDown:a=>{a.key==="Enter"&&k(a.target.value)}})]}),o.jsxs("label",{className:"full-width",children:["Версия промпта содержит",o.jsx("input",{value:H.promptContains,onChange:a=>Fe(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:(I?.available.prompt_versions??[]).map(a=>o.jsx("option",{value:a},a))}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Ot,onClick:()=>{Gr({keepSelection:!1})},children:Ot?"Обновляю...":"Применить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{Fe({...Yi,fromLocal:Oc()}),Ge("")},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:W})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт декомпозиции:"}),o.jsx("strong",{children:de})]})]}),o.jsx("h4",{children:"Автогенерация вопросов"}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Режим генерации",o.jsxs("select",{value:re.mode,onChange:a=>It(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:qr,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&St(c)},onBlur:a=>te(a.target.value),onKeyDown:a=>{a.key==="Enter"&&te(a.target.value)}})]}),o.jsxs("label",{children:["Личность автогенерации",o.jsx("select",{value:re.personalityId,onChange:a=>It(c=>({...c,personalityId:a.target.value})),children:lt.map(a=>o.jsx("option",{value:a.id,children:a.label},a.id))})]}),o.jsxs("label",{children:["Кто генерирует",o.jsx("input",{value:re.generatedBy,onChange:a=>It(c=>({...c,generatedBy:a.target.value})),placeholder:"manual_reviewer"})]}),o.jsxs("label",{className:"full-width",children:["Промпт личности",o.jsx("textarea",{className:"autoruns-personality-prompt",value:re.personalityPrompts[re.personalityId]??"",onChange:a=>It(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:a.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${rr}px`},onMouseUp:gt,onTouchEnd:gt})]}),o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:re.persistToEvalCases,onChange:a=>It(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:Te,onChange:a=>Ae(Zi(a.target.value))})]}),o.jsx("div",{className:"button-row",children:o.jsx("button",{type:"button",className:"tab",disabled:!Te,onClick:()=>Ae(""),children:"Сбросить дату среза"})})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Dn,onClick:()=>{vl()},children:Dn?"Генерирую...":"Сгенерировать пачку"}),o.jsx("button",{type:"button",className:"tab",disabled:Kt,onClick:()=>{Jt()},children:Kt?"Обновляю...":"Обновить историю"}),o.jsx("button",{type:"button",className:"autoruns-run-launch-btn",disabled:Sn||xt.length===0,onClick:()=>{ho()},children:Sn?"Запускаю...":"Запустить прогоны"})]}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{className:"full-width",children:["Кейс-сет для запуска",o.jsxs("select",{value:nn,onChange:a=>xn(a.target.value),disabled:tt.length===0,children:[tt.length===0?o.jsx("option",{value:"",children:"нет генераций"}):null,tt.map(a=>o.jsxs("option",{value:a.generation_id,children:[vr(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:["Вопросы к запуску: ",xt.length]}),o.jsx("button",{type:"button",className:"tab",onClick:()=>_n([...$t?.questions??[]]),disabled:!$t,children:"Восстановить"})]}),xt.length===0?o.jsx("p",{className:"muted",children:"Список вопросов пуст. Сгенерируйте пачку или восстановите из выбранной генерации."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:xt.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:()=>_n(v=>v.filter((R,fe)=>fe!==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:[Kt?o.jsx("p",{className:"muted",children:"Загружаю историю автогенераций..."}):null,!Kt&&tt.length===0?o.jsx("p",{className:"muted",children:"История автогенераций пока пустая."}):null,tt.slice(0,30).map(a=>o.jsxs("article",{className:nn===a.generation_id?"autoruns-autogen-item selected":"autoruns-autogen-item",onClick:()=>xn(a.generation_id),children:[o.jsxs("header",{children:[o.jsx("strong",{children:vr(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:Q.systemPrompt})]}),o.jsxs("label",{children:["Разработчика",o.jsx("textarea",{readOnly:!0,value:Q.developerPrompt})]}),o.jsxs("label",{children:["Доменный",o.jsx("textarea",{readOnly:!0,value:Q.domainPrompt})]}),o.jsxs("label",{children:["Заметки по схеме",o.jsx("textarea",{readOnly:!0,value:Q.schemaNotes})]}),o.jsxs("label",{children:["Примеры few-shot",o.jsx("textarea",{readOnly:!0,value:Q.fewShotExamples})]})]}),wn?o.jsx("p",{className:"error-text",children:wn}):null]}):null,o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Выдача прогонов"})}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Всего"}),o.jsx("strong",{children:(I?.stats.runs_total??0)+(Oe?1:0)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний score"}),o.jsx("strong",{children:ml(I?.stats.avg_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:I?Dc(I.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Блокеры"}),o.jsx("strong",{children:I?.stats.blocking_runs??0})]})]}),o.jsxs("div",{className:"autoruns-run-list",children:[ir.map(a=>o.jsxs("button",{type:"button",className:Pe===a.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{Ut(a.run_id)},children:[o.jsxs("div",{className:"autoruns-run-head",children:[o.jsx("strong",{children:vr(a.run_timestamp)}),o.jsx("span",{children:im(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=>{Cr(c,a.run_id)},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Cr(c,a.run_id))},title:"Скопировать run id","aria-label":`Скопировать run id ${a.run_id}`,children:o.jsx(cm,{})})]}),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:["оценка: ",ml(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)),ir.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:Pe,onChange:a=>{const c=a.target.value;Ut(c)},children:ir.map(a=>o.jsxs("option",{value:a.run_id,children:[vr(a.run_timestamp)," | ",a.run_id]},a.run_id))})]}),o.jsxs("label",{children:["Кейс",o.jsxs("select",{value:ot,onChange:a=>{const c=a.target.value;dt(c),Pe&&c&&Er(Pe,c)},children:[(O?.cases.length??0)>0?o.jsx("option",{value:Nt,children:"ВСЕ кейсы подряд"}):null,(O?.cases??[]).map(a=>o.jsxs("option",{value:a.case_id,children:[a.case_id," | ",a.status]},a.case_id))]})]})]})]}),o.jsxs("div",{className:"autoruns-case-list",children:[(O?.cases.length??0)>0?o.jsxs("button",{type:"button",className:ot===Nt?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{dt(Nt),Pe&&Er(Pe,Nt)},children:[o.jsx("span",{children:"ВСЕ кейсы подряд"}),o.jsx("span",{children:O?.cases.length})]},Nt):null,(O?.cases??[]).map(a=>o.jsxs("button",{type:"button",className:ot===a.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{dt(a.case_id),Pe&&Er(Pe,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:[$n||zn?o.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!$n&&!zn&&(C?.messages.length??0)===0?o.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(C?.messages??[]).map((a,c)=>{const v=a.role==="assistant"?"assistant":"user";return o.jsxs("article",{className:`autoruns-msg ${v}`,children:[o.jsxs("header",{children:[o.jsx("strong",{children:v==="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?vr(a.created_at):"нет данных"}),v==="assistant"&&!Ds(Pe)?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:a.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>yl(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(um,{commented:a.commented})}),a.annotation?o.jsx("button",{type:"button",className:a.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{Yr(a.annotation,!a.annotation.resolved)},disabled:Dt===a.annotation.annotation_id,title:a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Fc,{resolved:a.annotation.resolved})}):null]}):null]})]}),o.jsx("p",{children:a.text}),v==="assistant"&&a.annotation?o.jsxs("div",{className:"autoruns-msg-annotation",children:[o.jsx("strong",{children:ea(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??`${v}-${c}`)})]})]}),ct?o.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:o.jsx(Wc,{sessionId:nt,conversation:zt,inputValue:jr,onInputChange:_t,selectedContextChip:jn,onSelectContextChip:an,onClearContextChip:()=>an(null),useMock:tr,onUseMockChange:Wr,onSend:E,onClear:m,busy:Re,statusText:nr,errorMessage:cs,showCommentAction:!0,onCommentAssistantMessage:xl,isAssistantMessageCommented:ms,canCommentAssistantMessage:Mr})}):null,st?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:kn?.case_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"домен:"}),o.jsx("strong",{children:kn?.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"класс запроса:"}),o.jsx("strong",{children:kn?.query_class??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"trace:"}),o.jsx("strong",{children:kn?.trace_id??"нет данных"})]})]}),o.jsx("h4",{children:"Шаги декомпозиции"}),(C?.decomposition.length??0)>0?o.jsx("ol",{className:"autoruns-decomposition-list",children:(C?.decomposition??[]).map((a,c)=>o.jsx("li",{children:a},`${c}-${a.slice(0,24)}`))}):o.jsx("p",{className:"muted",children:"В логах кейса нет явной декомпозиции."})]}):null,Et?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:ml(I?.stats.latest_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Предыдущий"}),o.jsx("strong",{children:ml(I?.stats.previous_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:I?Dc(I.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Пробелы качества"}),o.jsx("strong",{children:I?.stats.quality_gap_runs??0})]})]}),o.jsx("h4",{children:"Покрытие доменов (история)"}),zc(I?.stats.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),zc(O?.coverage.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),Lt?o.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,Lt?null:o.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(On?.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:[(On?.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)),!Lt&&(On?.post_analysis.recommended_regression_candidates.length??0)===0?o.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,ie?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=>Se(a.target.value),children:[o.jsx("option",{value:"all",children:"все"}),(vn.length>0?vn:Ee?.enum??[]).map(a=>o.jsx("option",{value:a,children:String(Ee?.labels?.[a]??a)},a))]})]}),o.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>ve(a=>!a),children:ge?"Показать выполненные":"Скрыть выполненные"})]}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Комментариев"}),o.jsx("strong",{children:it.length})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний рейтинг"}),o.jsx("strong",{children:lr===null?"нет данных":`${lr.toFixed(2)} / 5`})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Последний"}),o.jsx("strong",{children:it.length>0?vr(it[0].updated_at):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Статус"}),o.jsx("strong",{children:ze?"обновляю":"готово"})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:ze,onClick:()=>{Ft()},children:ze?"Обновляю...":"Обновить список"}),o.jsx("button",{type:"button",className:"tab",disabled:Lt,onClick:()=>{ft()},children:Lt?"Идет пост-анализ...":"Обновить пост-анализ"})]}),o.jsxs("div",{className:"autoruns-comments-list",children:[ze?o.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!ze&&it.length===0?o.jsx("p",{className:"muted",children:oe.length===0&&bn.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,it.map(a=>{if(a.source==="assistant_live"){const v=a.assistant;return o.jsxs("article",{className:"autoruns-comment-item",children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:ea(v.rating)}),o.jsx("div",{className:"autoruns-comment-head-actions",children:o.jsx("span",{children:vr(v.updated_at)})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",v.session_id]}),o.jsxs("div",{className:"autoruns-run-meta",children:["msg=",v.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",v.annotation_author?` | author=${v.annotation_author}`:""]}),v.context.question_text?o.jsxs("p",{children:["Q: ",v.context.question_text]}):null,v.context.answer_text?o.jsxs("p",{children:["A: ",v.context.answer_text]}):null,o.jsx("p",{children:v.comment})]},a.key)}const c=a.autorun;return o.jsxs("article",{className:Ln===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{hs(c)},role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),hs(c))},children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:ea(c.rating)}),o.jsxs("div",{className:"autoruns-comment-head-actions",children:[o.jsx("span",{children:vr(c.updated_at)}),o.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:v=>{v.preventDefault(),v.stopPropagation(),Yr(c,!c.resolved)},disabled:Dt===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Fc,{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:["выполнено",": ",vr(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)})]}),ke?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:ke.technical_context.trace_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"reply_type:"}),o.jsx("strong",{children:ke.technical_context.reply_type??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"domain:"}),o.jsx("strong",{children:ke.technical_context.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"query_class:"}),o.jsx("strong",{children:ke.technical_context.query_class??"нет данных"})]})]}),o.jsx("h4",{children:"JSON разбор"}),o.jsx(tn,{value:{annotation_id:ke.annotation_id,run_id:ke.run_id,case_id:ke.case_id,message_index:ke.message_index,rating:ke.rating,comment:ke.comment,manual_case_decision:ke.manual_case_decision,annotation_author:ke.annotation_author,resolved:ke.resolved,resolved_at:ke.resolved_at,resolved_by:ke.resolved_by,context:ke.context,technical_context:ke.technical_context,case_summary:ke.case_summary?{case_id:ke.case_summary.case_id,domain:ke.case_summary.domain,query_class:ke.case_summary.query_class,checks:ke.case_summary.checks,metric_subscores:ke.case_summary.metric_subscores}:null}})]}):null]}):null]}),ye.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Nn()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),or?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:or.text})]}):null,kr?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:kr.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:ye.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>be(c=>({...c,rating:a})),disabled:ye.saving,"aria-label":`Оценка ${a}`,children:ye.rating>=a?"●":"○"},a))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ye.annotationAuthor,onChange:a=>be(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ye.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ye.comment,onChange:a=>be(c=>({...c,comment:a.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:ye.saving})]}),ye.error?o.jsx("p",{className:"error-text",children:ye.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{_l()},disabled:ye.saving,children:ye.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Nn(),disabled:ye.saving,children:"Отмена"})]})]})}):null,ue.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Qn()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу системы"}),o.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),ds?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:$s?.text??"Вопрос в диалоге не найден."})]}),o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ системы"}),o.jsx("p",{className:"autoruns-comment-quote",children:ds.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:()=>Ue(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=>Ue(c=>({...c,manualCaseDecision:a.target.value})),disabled:ue.saving,children:(vn.length>0?vn:Ee?.enum??[dl]).map(a=>o.jsx("option",{value:a,children:String(Ee?.labels?.[a]??a)},a))})]}),o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ue.annotationAuthor,onChange:a=>Ue(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ue.saving})]})]}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ue.comment,onChange:a=>Ue(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:()=>{Jr()},disabled:ue.saving,children:ue.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Qn(),disabled:ue.saving,children:"Отмена"})]})]})}):null]})}function fm({items:i,onRefresh:p,onOpenTrace:f}){return o.jsx(In,{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(N=>o.jsxs("button",{type:"button",className:"history-item",onClick:()=>f(N.trace_id),children:[o.jsxs("div",{className:"history-row",children:[o.jsx("strong",{children:N.route_hint??"route: n/a"}),o.jsx("span",{children:N.validation_passed?"schema: ok":"schema: fail"})]}),o.jsx("p",{children:N.question_short}),o.jsxs("div",{className:"history-row",children:[o.jsx("span",{children:N.model}),o.jsx("span",{children:new Date(N.timestamp).toLocaleString("ru-RU")})]})]},N.trace_id))]})})}function yr(i){return i==null||i===""?"—":String(i)}function mm({result:i}){return o.jsx(In,{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:yr(i?.trace_id)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"request_started_at"}),o.jsx("strong",{children:yr(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:yr(i?new Date().toISOString():null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"latency_ms"}),o.jsx("strong",{children:yr(i?.latency_ms)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"input_tokens"}),o.jsx("strong",{children:yr(i?.usage?.input_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"output_tokens"}),o.jsx("strong",{children:yr(i?.usage?.output_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"total_tokens"}),o.jsx("strong",{children:yr(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:yr(i?.prompt_version)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"schema_version"}),o.jsx("strong",{children:yr(i?.schema_version)})]})]})})}const pm={normalized:"Normalized JSON",fragments:"Fragment View",scope:"Scope View",flags:"Flags View",route:"Route Simulation",raw:"Raw model output",validation:"Validation",logs:"Logs"};function hm(i){return i&&typeof i=="object"?i:null}function gm({tab:i,onTabChange:p,result:f,appLogs:N}){const j=["normalized","fragments","scope","flags","route","raw","validation","logs"],T=hm(f?.normalized),$=String(T?.schema_version??""),Y=$==="normalized_query_v2"||$==="normalized_query_v2_0_1"||$==="normalized_query_v2_0_2",b=Y?{fragments:T?.fragments??[],discarded_fragments:T?.discarded_fragments??[]}:{note:"Fragment View доступен для normalized_query_v2."},Q=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."},G=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(In,{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:pm[z]},z))}),i==="normalized"?o.jsx(tn,{value:f?.normalized??{note:"Нет данных."}}):null,i==="fragments"?o.jsx(tn,{value:b}):null,i==="scope"?o.jsx(tn,{value:Q}):null,i==="flags"?o.jsx(tn,{value:G}):null,i==="route"?o.jsx(tn,{value:f?.route_hint_summary??{note:"Нет данных."}}):null,i==="raw"?o.jsx(tn,{value:f?.raw_model_output??{note:"Нет данных."}}):null,i==="validation"?o.jsx(tn,{value:f?.validation??{note:"Нет данных."}}):null,i==="logs"?o.jsx(tn,{value:N}):null]})}function vm({value:i,onChange:p,onApplyBatchFormat:f,onNormalize:N,busy:j,useMock:T,onUseMockChange:$,errorMessage:Y}){return o.jsxs(In,{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:b=>p({...i,userQuestion:b.target.value}),rows:6,placeholder:"Например: По каким покупателям у нас на конец июня висят отгрузки без оплаты..."})]}),o.jsxs("label",{className:"full-width",children:["Batch queries (`;` separator)",o.jsx("textarea",{value:i.batchQuestionsRaw,onChange:b=>p({...i,batchQuestionsRaw:b.target.value}),onBlur:()=>f(),rows:8,placeholder:"Вопрос 1; Вопрос 2; Вопрос 3"})]}),o.jsxs("label",{children:["Optional period context",o.jsx("input",{value:i.periodHint,onChange:b=>p({...i,periodHint:b.target.value})})]}),o.jsxs("label",{children:["Optional business context",o.jsx("input",{value:i.businessContext,onChange:b=>p({...i,businessContext:b.target.value})})]}),o.jsxs("label",{children:["Optional expected route (eval)",o.jsx("input",{value:i.expectedRoute,onChange:b=>p({...i,expectedRoute:b.target.value})})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:T,onChange:b=>$(b.target.checked)}),"Mock-режим (без вызова OpenAI)"]}),o.jsx("button",{type:"button",onClick:()=>f(),disabled:j||!i.batchQuestionsRaw.trim(),children:"Применить `;` в переносы"}),o.jsx("button",{type:"button",onClick:()=>N(!1),disabled:j||!i.userQuestion.trim(),children:j?"Нормализуем...":"Normalize"}),o.jsx("button",{type:"button",onClick:()=>N(!0),disabled:j||!i.userQuestion.trim(),children:j?"Сохраняем...":"Normalize + Save as test case"})]}),Y?o.jsx("p",{className:"error-text",children:Y}):null]})}function ym({runs:i,selectedRunId:p,onSelectRun:f,onStartRun:N,onFinishRun:j,onRefreshRuns:T,onRunEval:$,onCopyEvalReport:Y,evalBusy:b,traceItems:Q,evalReport:G}){return o.jsxs(In,{title:"NDC Run Monitor",subtitle:"Важно: кнопка Запустить run создает только run-сущность. Кнопка eval запускает batch-проверку normalizer v2.0.2.",children:[o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>N(),children:"Запустить run"}),o.jsx("button",{type:"button",onClick:()=>j(),disabled:!p,children:"Завершить выбранный run"}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Обновить runs"}),o.jsx("button",{type:"button",onClick:()=>$(),disabled:b,children:b?"Идет 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:()=>f(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(tn,{value:Q}),o.jsxs("div",{className:"eval-report-wrap",children:[o.jsx("h3",{style:{marginTop:12},children:"Отчет eval"}),o.jsx(tn,{value:G??{note:"Eval пока не запускался"}}),o.jsx("button",{type:"button",className:"copy-cube-button",title:"Скопировать отчет eval",onClick:()=>Y(),children:"⧉"})]})]})]})]})}const xm={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},Uc={systemPrompt:"Ты semantic-normalizer для бухгалтерского ассистента NDC. Возвращай только JSON по схеме normalized_query_v2_0_2.",developerPrompt:"Сначала делай decomposition сообщения на task fragments, затем определяй domain scope и route-critical flags. Для каждого fragment заполняй execution_readiness + route_status + no_route_reason. Если fragment routable, не оставляй его в no_route.",domainPrompt:"Контур: данные текущего предприятия в 1С/NDC. In-scope: документы, проводки, взаиморасчеты, остатки, периодное закрытие, аномалии и контрольные проверки. Out-of-scope: общая теория, законы и оффтоп.",schemaNotes:"schema_version: normalized_query_v2_0_2. Строгий JSON без дополнительных полей.",fewShotExamples:"Q: Проверь по поставщикам хвосты и разложи цепочку документов/оплат. => fragment in_scope, flags: multi_entity + chain_explanation. Q: Как вообще по ФСБУ? => out_of_scope/generic_accounting."},_m={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},ta={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}},bc="ndc_normalizer_session_config_v1",Bc="ndc_autoruns_layout_config_v1",Sm="ndc-autoruns-save",na=["Анализ запроса","Получение данных","Подготовка ответа"],wm="autoruns",ra="normalizer_v2_0_2",Hc="address_query_runtime_v1",jm=["normalized","fragments","scope","flags","route","raw","validation","logs"],sa="manual_reviewer";function km(i){return`[${new Date().toLocaleTimeString("ru-RU")}] ${i}`}function Cm(i,p){if(!p)return"Previous preset is not selected.";const N=["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 N.length===0?"No changes against previous preset.":`Changed fields: ${N.length}. ${N.join(" | ")}`}function Nm(i,p){const f=i.trim();if(!f)return"";if(!p)return f;const N=f.toLowerCase(),j=p.anchor_text.trim(),T=j.toLowerCase();return T&&N.includes(T)?f:`По выбранному объекту "${j}": ${f}`}function Em(){const[i,p]=x.useState(xm),[f,N]=x.useState(Uc),[j,T]=x.useState(_m),[$,Y]=x.useState(null),[b,Q]=x.useState([]),[G,z]=x.useState([]),[ne,Ne]=x.useState("normalized"),[le,ce]=x.useState(!1),[me,Qe]=x.useState(!1),[De,We]=x.useState([]),[je,W]=x.useState(""),[de,Me]=x.useState([]),[Ze,ct]=x.useState(""),[st,Et]=x.useState("NDC custom preset"),[ie,Le]=x.useState(null),[H,Fe]=x.useState(""),[Te,Ae]=x.useState(!1),[I,X]=x.useState([]),[O,y]=x.useState(""),[C,J]=x.useState([]),[oe,pe]=x.useState(!1),[ae,Se]=x.useState(null),[ge,ve]=x.useState(""),[Ee,gn]=x.useState(wm),[vn,Yn]=x.useState(!0),[Ln,Xn]=x.useState(!0),[Pe,qt]=x.useState(!0),[ot,dt]=x.useState(!0),[lt,yn]=x.useState(!0),[re,It]=x.useState(!0),[tt,Vr]=x.useState(!0),[nn,xn]=x.useState(!0),[xt,_n]=x.useState(!0),[Oe,rn]=x.useState(!0),[On,xr]=x.useState(!0),[Dn,Qr]=x.useState(!0),[Sn,sn]=x.useState(!0),[Lt,Zn]=x.useState(!0),[Kt,on]=x.useState(!0),[Ot,_r]=x.useState(!0),[zn,Sr]=x.useState(!0),[$n,wr]=x.useState(!0),[ze,er]=x.useState(""),[Dt,Fn]=x.useState([]),[wn,Ge]=x.useState(""),[nt,ln]=x.useState(null),[zt,Un]=x.useState(!1),[bn,Gt]=x.useState(""),[jr,_t]=x.useState(""),[jn,an]=x.useState([]),[tr,Wr]=x.useState(!1),[Re,Pt]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:sa,saving:!1,error:""}),nr=x.useRef(!1),Bn=x.useRef(!1),cs=x.useRef(!1);x.useEffect(()=>{const m=document.documentElement,{colors:E}=ta;m.style.setProperty("--rgb-background",E.backgroundRgb),m.style.setProperty("--rgb-surface-main",E.mainSurfaceRgb),m.style.setProperty("--rgb-surface-horizontal",E.horizontalSurfaceRgb),m.style.setProperty("--rgb-surface-focus",E.focusSurfaceRgb),m.style.setProperty("--rgb-assistant-chip",E.assistantChipRgb),m.style.setProperty("--rgb-assistant-chip-hover",E.assistantChipHoverRgb),m.style.setProperty("--rgb-assistant-chip-selected",E.assistantChipSelectedRgb),m.style.setProperty("--rgb-assistant-chip-selected-text",E.assistantChipSelectedTextRgb),m.style.setProperty("--rgb-active",E.activeRgb),m.style.setProperty("--rgb-active-text",E.activeTextRgb),m.style.setProperty("--rgb-text-main",E.textMainRgb),m.style.setProperty("--rgb-text-muted",E.textMutedRgb),m.style.setProperty("--rgb-danger",E.dangerRgb),m.style.setProperty("--rgb-scrollbar-track",E.scrollbarTrackRgb),m.style.setProperty("--rgb-scrollbar-thumb",E.scrollbarThumbRgb),m.style.setProperty("--rgb-scrollbar-thumb-hover",E.scrollbarThumbHoverRgb),m.style.setProperty("--mode-column-width",`${ta.layout.modeColumnWidthPx}px`),m.style.setProperty("--mode-toggle-width",`${ta.layout.modeToggleWidthPx}px`)},[]);const D=m=>{z(E=>[km(m),...E].slice(0,300))};function zs(){let m=0;Gt(na[0]);const E=window.setInterval(()=>{m=Math.min(m+1,na.length-1),Gt(na[m])},650);return()=>window.clearInterval(E)}x.useEffect(()=>{(async()=>{const k=localStorage.getItem(bc);if(k)try{const te=JSON.parse(k);p(Ie=>({...Ie,llmProvider:te.llmProvider==="local"?"local":"openai",model:te.model??Ie.model,baseUrl:te.baseUrl??Ie.baseUrl,temperature:te.temperature??Ie.temperature,maxOutputTokens:te.maxOutputTokens??Ie.maxOutputTokens}))}catch{}try{const te=await _e.loadSharedConnectionConfig();te.connection&&te.connection.llmProvider==="local"&&(p(Ie=>({...Ie,llmProvider:"local",model:te.connection?.model??Ie.model,baseUrl:te.connection?.baseUrl??Ie.baseUrl,temperature:te.connection?.temperature??Ie.temperature,maxOutputTokens:te.connection?.maxOutputTokens??Ie.maxOutputTokens})),D(`Shared local LLM config loaded: ${te.connection.model}`))}catch(te){D(`Shared local config load error: ${te instanceof Error?te.message:String(te)}`)}finally{cs.current=!0}})();const E=localStorage.getItem(Bc);if(E)try{const k=JSON.parse(E);k.uiMode==="decomposition"?gn("decomposition"):(k.uiMode==="assistant"||k.uiMode==="autoruns")&&gn("autoruns"),k.activeTab&&jm.includes(k.activeTab)&&Ne(k.activeTab),typeof k.showAutorunsSettingsMode=="boolean"&&Yn(k.showAutorunsSettingsMode),typeof k.showAutorunsAutoRunsMode=="boolean"&&Xn(k.showAutorunsAutoRunsMode),typeof k.showAutorunsAssistantMode=="boolean"&&qt(k.showAutorunsAssistantMode),typeof k.showAutorunsDecompositionMode=="boolean"&&dt(k.showAutorunsDecompositionMode),typeof k.showAutorunsProgressMode=="boolean"&&yn(k.showAutorunsProgressMode),typeof k.showAutorunsCommentsMode=="boolean"&&It(k.showAutorunsCommentsMode),typeof k.showAssistantConnectionMode=="boolean"&&Vr(k.showAssistantConnectionMode),typeof k.showAssistantPromptMode=="boolean"&&xn(k.showAssistantPromptMode),typeof k.showAssistantChatMode=="boolean"&&_n(k.showAssistantChatMode),typeof k.showAssistantCommentsMode=="boolean"&&rn(k.showAssistantCommentsMode),typeof k.showAssistantSamMode=="boolean"&&xr(k.showAssistantSamMode),typeof k.showDecompositionConnectionMode=="boolean"&&Qr(k.showDecompositionConnectionMode),typeof k.showDecompositionPromptMode=="boolean"&&sn(k.showDecompositionPromptMode),typeof k.showDecompositionQueryMode=="boolean"&&Zn(k.showDecompositionQueryMode),typeof k.showDecompositionOutputMode=="boolean"&&on(k.showDecompositionOutputMode),typeof k.showDecompositionMetricsMode=="boolean"&&_r(k.showDecompositionMetricsMode),typeof k.showDecompositionHistoryMode=="boolean"&&Sr(k.showDecompositionHistoryMode),typeof k.showDecompositionRuntimeMode=="boolean"&&wr(k.showDecompositionRuntimeMode),k.prompts&&(N(te=>({...te,...k.prompts})),Bn.current=!0)}catch{}Mt(),qr(),St()},[]),x.useEffect(()=>{if(!cs.current||i.llmProvider!=="local")return;const m=window.setTimeout(()=>{_e.saveSharedConnectionConfig(i).catch(E=>D(`Shared local config sync error: ${E instanceof Error?E.message:String(E)}`))},250);return()=>window.clearTimeout(m)},[i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature]);async function Mt(){try{const m=await _e.loadHistory();Q(m.items??[])}catch(m){D(`History load error: ${m instanceof Error?m.message:String(m)}`)}}async function qr(){try{const E=(await _e.loadPresets()).presets??[];if(Me(E),Bn.current){nr.current=!0;return}if(nr.current)return;const k=E.find(te=>te.prompt_version===ra)??E.find(te=>te.id==="default-normalizer-v2_0_2");if(!k){nr.current=!0,D(`Preset autoload skipped: ${ra} not found.`);return}ct(k.id),Le(f),N({systemPrompt:k.systemPrompt,developerPrompt:k.developerPrompt,domainPrompt:k.domainPrompt,schemaNotes:k.schemaNotes??"",fewShotExamples:k.fewShotExamples??""}),nr.current=!0,D(`Preset autoloaded: ${k.name} (${k.prompt_version}).`)}catch(m){D(`Presets load error: ${m instanceof Error?m.message:String(m)}`)}}async function St(){try{const m=await _e.listRuns();X(m.items??[])}catch(m){D(`Runs load error: ${m instanceof Error?m.message:String(m)}`)}}function rr(){if(localStorage.setItem(bc,JSON.stringify({model:i.model,llmProvider:i.llmProvider,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})),i.llmProvider==="local"){_e.saveSharedConnectionConfig(i).then(()=>{D("Local config saved and synced to shared agent config (without API key).")}).catch(m=>{D(`Local config saved, but shared sync failed: ${m instanceof Error?m.message:String(m)}`)});return}D("Local config saved (without API key).")}function Kr(){localStorage.setItem(Bc,JSON.stringify({uiMode:Ee,activeTab:ne,showAutorunsSettingsMode:vn,showAutorunsAutoRunsMode:Ln,showAutorunsAssistantMode:Pe,showAutorunsDecompositionMode:ot,showAutorunsProgressMode:lt,showAutorunsCommentsMode:re,showAssistantConnectionMode:tt,showAssistantPromptMode:nn,showAssistantChatMode:xt,showAssistantCommentsMode:Oe,showAssistantSamMode:On,showDecompositionConnectionMode:Dn,showDecompositionPromptMode:Sn,showDecompositionQueryMode:Lt,showDecompositionOutputMode:Kt,showDecompositionMetricsMode:Ot,showDecompositionHistoryMode:zn,showDecompositionRuntimeMode:$n,prompts:f})),window.dispatchEvent(new CustomEvent(Sm)),D("UI layout and prompts saved.")}async function ue(){ce(!0),ve("");try{const m=await _e.testConnection(i);m.provider==="local"?m.model_found===!0?(W(`LOCAL OK - ${m.model}`),D(`Local model is available: ${m.model} (catalog size=${m.models_count??"n/a"}).`)):m.model_found===!1?(W(`LOCAL OK, model not loaded - ${m.model}`),D(`Local server is reachable, but model '${m.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(W(`LOCAL OK (model list unavailable) - ${m.model}`),D("Local server is reachable, but model catalog could not be verified.")):(W(`OPENAI OK - ${m.model}`),D(`OpenAI connection ok: ${m.model}`))}catch(m){const E=m instanceof Error?m.message:String(m);W("Connection error"),ve(`Test connection: ${E}`),D(`Test connection error: ${E}`)}finally{ce(!1)}}async function Ue(){Qe(!0);try{const E=(await _e.listModels(i)).models??[];We(E),E.length>0&&p(k=>k.model&&E.includes(k.model)?k:{...k,model:E[0]}),D(`Model catalog loaded (${i.llmProvider}): ${E.length} items.`)}catch(m){const E=m instanceof Error?m.message:String(m);D(`Load model list error: ${E}`)}finally{Qe(!1)}}x.useEffect(()=>{We([])},[i.llmProvider,i.baseUrl]);async function ye(m){ce(!0),ve("");try{const E=await _e.normalize({connection:i,prompts:f,promptVersion:"normalizer_v2_0_2",query:{userQuestion:j.userQuestion,periodHint:j.periodHint,businessContext:j.businessContext,expectedRoute:j.expectedRoute},saveAsTestCase:m,useMock:Te});Y(E),Ne("normalized"),D(`Normalize done: trace=${E.trace_id}, validation=${E.validation.passed?"passed":"failed"}`),Mt()}catch(E){const k=E instanceof Error?E.message:String(E);ve(`Normalize: ${k}`),D(`Normalize error: ${k}`)}finally{ce(!1)}}function be(){const m=de.find(E=>E.id===Ze);if(!m){D("Preset is not selected.");return}Le(f),N({systemPrompt:m.systemPrompt,developerPrompt:m.developerPrompt,domainPrompt:m.domainPrompt,schemaNotes:m.schemaNotes??"",fewShotExamples:m.fewShotExamples??""}),D(`Preset loaded: ${m.name}`)}async function sr(){try{await _e.savePreset({name:st||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:f.systemPrompt,developerPrompt:f.developerPrompt,domainPrompt:f.domainPrompt,schemaNotes:f.schemaNotes,fewShotExamples:f.fewShotExamples}),D("Preset saved."),await qr()}catch(m){D(`Preset save error: ${m instanceof Error?m.message:String(m)}`)}}function Hn(){N(Uc),D("Prompt panel reset to defaults.")}function Vn(){const m=Cm(f,ie);Fe(m),D(m)}function $t(){const m=j.batchQuestionsRaw.split(";").map(E=>E.trim()).filter(Boolean).join(` `);m&&(T(E=>({...E,batchQuestionsRaw:m})),D("Batch field formatted: `;` converted to blank-line separators."))}async function kn(m){try{const k=(await _e.loadTrace(m)).trace,te=k.parsed_normalized_json??null;Y({trace_id:String(k.trace_id??m),ok:!!k.validation_result?.passed,normalized:te,route_hint_summary:k.route_hint_summary??(te?{route_hint:te.route_hint??null,confidence:te.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")}),Ne("raw"),ve(""),D(`Trace opened: ${m}`)}catch(E){const k=E instanceof Error?E.message:String(E);ve(`Trace: ${k}`),D(`Trace open error ${m}: ${k}`)}}async function At(){try{const m=await _e.startRun();y(m.run.runId),D(`Run started: ${m.run.runId}`),D("Tip: start run does not execute normalize by itself. Use 'Run eval v2.0.2' button."),await St()}catch(m){D(`Run start error: ${m instanceof Error?m.message:String(m)}`)}}async function ke(){if(O)try{await _e.finishRun(O),D(`Run finished: ${O}`),await St()}catch(m){D(`Run finish error: ${m instanceof Error?m.message:String(m)}`)}}async function ds(){pe(!0),ve("");try{D("Starting eval in v2 contour.");const m=j.batchQuestionsRaw.trim()||j.userQuestion.trim();if(!m)throw new Error("Fill batch field or Raw user question first.");const E=await _e.runEval({connection:i,prompts:f,promptVersion:"normalizer_v2_0_2",mode:"single-pass-strict",rawQuestions:m,useMock:Te});Se(E.report),D("Eval v2.0.2 run finished.");const k=E.report;if(k.run_id&&D(`Eval run id: ${k.run_id}`),k.metrics){const te=k.metrics;D(`Eval metrics v2.0.2: schema=${te.schema_validation_pass_rate??"n/a"}%, route_accuracy=${te.route_resolution_accuracy??"n/a"}%, no_route_precision=${te.no_route_precision??"n/a"}%, state_consistency=${te.execution_state_consistency_rate??"n/a"}%`)}await Mt()}catch(m){const E=m instanceof Error?m.message:String(m);E.includes("Legacy eval runner supports normalized_query_v1 only")?(Se({status:"plan_only",prompt_version:"normalizer_v2",reason:"backend eval runner is still legacy-v1 only",plan_file:"reports/v2_pilot_eval_plan.md",next_steps:["run cheap mock sanity for schema/fragment/scope","run small real batch (10-15 messages, temperature=0)","run challenge-30 replay with v2 metrics"]}),D("Backend is legacy-only for eval right now. Showing v2 pilot plan.")):(ve(`Eval: ${E}`),D(`Eval run error: ${E}`))}finally{pe(!1)}}async function $s(){try{const m=JSON.stringify(ae??{},null,2);await navigator.clipboard.writeText(m),D("Eval report copied to clipboard.")}catch(m){D(`Eval report copy error: ${m instanceof Error?m.message:String(m)}`)}}const Cn=x.useMemo(()=>{const m=new Map;for(const E of jn)E.message_id&&m.set(E.message_id,E);return m},[jn]),kr=Re.messageIndex>=0?Dt[Re.messageIndex]??null:null,or=x.useMemo(()=>{if(Re.messageIndex<0)return null;for(let m=Re.messageIndex-1;m>=0;m-=1){const E=Dt[m];if(E?.role==="user")return E}return null},[Re.messageIndex,Dt]);async function it(m){if(!m.trim()){an([]);return}Wr(!0);try{const E=await _e.loadAssistantAnnotations({session_id:m,limit:400});an(E.items??[])}catch(E){const k=E instanceof Error?E.message:String(E);D(`Assistant annotations load error: ${k}`)}finally{Wr(!1)}}function lr(m){Pt(E=>E.saving&&!m?.force?E:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:sa,saving:!1,error:""})}function ir(m,E){if(m.role!=="assistant")return;const k=ze.trim(),te=String(m.session_id??"").trim();if(!(k||te)){_t("Сначала получите ответ ассистента в активной сессии.");return}!k&&te&&er(te);const gt=Cn.get(m.message_id)??null;Pt({open:!0,messageIndex:E,rating:gt?.rating??3,comment:gt?.comment??"",annotationAuthor:gt?.annotation_author??sa,saving:!1,error:""})}function F(m){return m.role==="assistant"}function ar(m){return m.role==="assistant"&&Cn.has(m.message_id)}async function Nn(){if(!ze.trim()){Pt(m=>({...m,error:"Сессия ассистента не найдена."}));return}if(!(Re.messageIndex<0)){if(!Re.comment.trim()){Pt(m=>({...m,error:"Добавьте комментарий."}));return}Pt(m=>({...m,saving:!0,error:""}));try{const m=await _e.saveAssistantAnnotation({session_id:ze,message_index:Re.messageIndex,rating:Re.rating,comment:Re.comment.trim(),annotation_author:Re.annotationAuthor.trim()||void 0});an(E=>{const k=[...E],te=k.findIndex(Ie=>Ie.annotation_id===m.annotation.annotation_id);return te>=0?k[te]=m.annotation:k.unshift(m.annotation),k.sort((Ie,gt)=>Date.parse(gt.updated_at)-Date.parse(Ie.updated_at))}),lr({force:!0})}catch(m){const E=m instanceof Error?m.message:String(m);Pt(k=>({...k,saving:!1,error:E}))}}}function Cr(){er(""),Fn([]),Ge(""),ln(null),Gt(""),_t(""),an([]),lr({force:!0}),D("Assistant session reset.")}async function fs(){const m=Nm(wn,nt);if(!m)return;Un(!0),_t(""),Ge(""),Fn(k=>[...k,{message_id:`local-${Date.now()}`,session_id:ze||"pending",role:"user",text:m,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const E=zs();try{const k=await _e.sendAssistantMessage({connection:i,prompts:f,userMessage:m,sessionId:ze||void 0,promptVersion:Hc,useMock:Te});er(k.session_id),Fn(k.conversation),Gt("Ответ готов"),await it(k.session_id),D(`Assistant reply received: trace=${k.debug.trace_id}`)}catch(k){const te=k instanceof Error?k.message:String(k);_t(te),Gt("Ошибка ассистента"),D(`Assistant error: ${te}`)}finally{E(),Un(!1)}}return x.useEffect(()=>{if(!ze.trim()){an([]);return}it(ze)},[ze]),x.useEffect(()=>{if(!O){J([]);return}_e.runTrace(O).then(m=>J(m.items)).catch(m=>D(`Run trace error: ${m instanceof Error?m.message:String(m)}`))},[O]),o.jsxs("main",{className:`app-root ${Ee==="assistant"||Ee==="decomposition"||Ee==="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:Ee==="autoruns"?"tab active":"tab",onClick:()=>gn("autoruns"),children:"Управление ассистентом"}),o.jsx("button",{type:"button",className:Ee==="decomposition"?"tab active":"tab",onClick:()=>gn("decomposition"),children:"Декомпозиция"}),o.jsx("button",{type:"button",className:"tab",onClick:Kr,children:"Сохранить"})]}),Ee==="assistant"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:tt?"tab active":"tab",onClick:()=>Vr(m=>!m),children:"LLM Connector"}),o.jsx("button",{type:"button",className:nn?"tab active":"tab",onClick:()=>xn(m=>!m),children:"Prompt Manager"}),o.jsx("button",{type:"button",className:xt?"tab active":"tab",onClick:()=>_n(m=>!m),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:Oe?"tab active":"tab",onClick:()=>rn(m=>!m),children:"Комментарии ассистента"}),o.jsx("button",{type:"button",className:On?"tab active":"tab",onClick:()=>xr(m=>!m),children:"SAM"})]}):Ee==="decomposition"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:Dn?"tab active":"tab",onClick:()=>Qr(m=>!m),children:"LLM"}),o.jsx("button",{type:"button",className:Sn?"tab active":"tab",onClick:()=>sn(m=>!m),children:"Prompt"}),o.jsx("button",{type:"button",className:Lt?"tab active":"tab",onClick:()=>Zn(m=>!m),children:"Запрос"}),o.jsx("button",{type:"button",className:Kt?"tab active":"tab",onClick:()=>on(m=>!m),children:"Выход"}),o.jsx("button",{type:"button",className:Ot?"tab active":"tab",onClick:()=>_r(m=>!m),children:"Метрики"}),o.jsx("button",{type:"button",className:zn?"tab active":"tab",onClick:()=>Sr(m=>!m),children:"История"}),o.jsx("button",{type:"button",className:$n?"tab active":"tab",onClick:()=>wr(m=>!m),children:"NDC Run Monitor"})]}):Ee==="autoruns"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:vn?"tab active":"tab",onClick:()=>Yn(m=>!m),children:"Настройки"}),o.jsx("button",{type:"button",className:Ln?"tab active":"tab",onClick:()=>Xn(m=>!m),children:"Автопрогоны"}),o.jsx("button",{type:"button",className:Pe?"tab active":"tab",onClick:()=>qt(m=>!m),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:ot?"tab active":"tab",onClick:()=>dt(m=>!m),children:"Режим декомпозиции"}),o.jsx("button",{type:"button",className:lt?"tab active":"tab",onClick:()=>yn(m=>!m),children:"Прогресс/регресс"}),o.jsx("button",{type:"button",className:re?"tab active":"tab",onClick:()=>It(m=>!m),children:"Комментарии"})]}):null]}),Ee==="assistant"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[tt?o.jsx("div",{className:"mode-col",children:o.jsx(oa,{value:i,modelOptions:De,modelsBusy:me,onChange:p,onReloadModels:Ue,onSaveLocalConfig:rr,onTestConnection:ue,lastStatus:je,busy:le||zt})}):null,nn?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(la,{value:f,onChange:N,presets:de,selectedPresetId:Ze,onSelectPreset:ct,onLoadPreset:be,onSavePreset:sr,onResetDefaults:Hn,onDiffPrevious:Vn,presetName:st,onPresetNameChange:Et,diffSummary:H})}):null,xt?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(Wc,{sessionId:ze,conversation:Dt,inputValue:wn,onInputChange:Ge,selectedContextChip:nt,onSelectContextChip:ln,onClearContextChip:()=>ln(null),useMock:Te,onUseMockChange:Ae,onSend:fs,onClear:Cr,busy:zt,statusText:bn,errorMessage:jr,showCommentAction:!0,onCommentAssistantMessage:ir,isAssistantMessageCommented:ar,canCommentAssistantMessage:F})}):null,Oe?o.jsx("div",{className:"mode-col",children:o.jsx(In,{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:ze?`session: ${ze}`:"Сессия не запущена"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{it(ze)},disabled:!ze||tr,children:tr?"Обновляю...":"Обновить"})]}),o.jsxs("div",{className:"assistant-comments-list",children:[ze?null:o.jsx("p",{className:"muted",children:"Появится после первого ответа ассистента."}),ze&&jn.length===0&&!tr?o.jsx("p",{className:"muted",children:"Комментариев по этой сессии пока нет."}):null,jn.map(m=>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(m.rating))))}${"○".repeat(Math.max(0,5-Math.round(m.rating)))}`}),o.jsx("span",{children:new Date(m.updated_at).toLocaleString("ru-RU")})]}),m.context.question_text?o.jsxs("p",{children:["Q: ",m.context.question_text]}):null,m.context.answer_text?o.jsxs("p",{children:["A: ",m.context.answer_text]}):null,o.jsx("p",{children:m.comment}),o.jsxs("div",{className:"assistant-comment-meta",children:[m.context.trace_id?o.jsx("span",{children:`trace=${m.context.trace_id}`}):null,m.context.reply_type?o.jsx("span",{children:`reply_type=${m.context.reply_type}`}):null]})]},m.annotation_id))]})]})})}):null,On?o.jsx("div",{className:"mode-col",children:o.jsx(Of,{sessionId:ze,conversation:Dt,statusText:bn,errorMessage:jr,useMock:Te,appLogs:G})}):null,!tt&&!nn&&!xt&&!Oe&&!On?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима ассистента скрыты. Включите нужные блоки справа в шапке."}):null]})}):Ee==="decomposition"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[Dn?o.jsx("div",{className:"mode-col",children:o.jsx(oa,{value:i,modelOptions:De,modelsBusy:me,onChange:p,onReloadModels:Ue,onSaveLocalConfig:rr,onTestConnection:ue,lastStatus:je,busy:le})}):null,Sn?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(la,{value:f,onChange:N,presets:de,selectedPresetId:Ze,onSelectPreset:ct,onLoadPreset:be,onSavePreset:sr,onResetDefaults:Hn,onDiffPrevious:Vn,presetName:st,onPresetNameChange:Et,diffSummary:H})}):null,Lt?o.jsx("div",{className:"mode-col",children:o.jsx(vm,{value:j,onChange:T,onApplyBatchFormat:$t,onNormalize:ye,busy:le,useMock:Te,onUseMockChange:Ae,errorMessage:ge})}):null,Kt?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(gm,{tab:ne,onTabChange:Ne,result:$,appLogs:G})}):null,Ot?o.jsx("div",{className:"mode-col",children:o.jsx(mm,{result:$})}):null,zn?o.jsx("div",{className:"mode-col",children:o.jsx(fm,{items:b,onRefresh:Mt,onOpenTrace:kn})}):null,$n?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(ym,{runs:I,selectedRunId:O,onSelectRun:y,onStartRun:At,onFinishRun:ke,onRefreshRuns:St,onRunEval:ds,onCopyEvalReport:$s,evalBusy:oe,traceItems:C,evalReport:ae})}):null,!Dn&&!Sn&&!Lt&&!Kt&&!Ot&&!zn&&!$n?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима декомпозиции скрыты. Включите нужные блоки справа в шапке."}):null]})}):o.jsx("div",{className:"layout-grid layout-grid-autoruns",children:o.jsx(dm,{connection:i,modelOptions:De,modelsBusy:me,connectionStatus:je,connectionBusy:le,onConnectionChange:p,onReloadModels:Ue,onSaveLocalConfig:rr,onTestConnection:ue,prompts:f,onPromptsChange:N,promptPresets:de,selectedPresetId:Ze,onSelectPreset:ct,onLoadPreset:be,onSavePreset:sr,onResetDefaults:Hn,onDiffPrevious:Vn,presetName:st,onPresetNameChange:Et,diffSummary:H,assistantPromptVersion:Hc,decompositionPromptVersion:ra,showSettingsMode:vn,showAutoRunsMode:Ln,showAssistantMode:Pe,showDecompositionMode:ot,showProgressMode:lt,showCommentsMode:re,onLog:D})}),Re.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:m=>{m.target===m.currentTarget&&lr()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Эта разметка хранится отдельно от комментариев автопрогонов."}),or?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:or.text})]}):null,kr?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:kr.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(m=>o.jsx("button",{type:"button",className:Re.rating>=m?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>Pt(E=>({...E,rating:m})),disabled:Re.saving,"aria-label":`Оценка ${m}`,children:Re.rating>=m?"●":"○"},m))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:Re.annotationAuthor,onChange:m=>Pt(E=>({...E,annotationAuthor:m.target.value})),placeholder:"manual_reviewer",disabled:Re.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:Re.comment,onChange:m=>Pt(E=>({...E,comment:m.target.value})),placeholder:"Что именно не так в ответе и что проверить.",rows:4,disabled:Re.saving})]}),Re.error?o.jsx("p",{className:"error-text",children:Re.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{Nn()},disabled:Re.saving,children:Re.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>lr(),disabled:Re.saving,children:"Отмена"})]})]})}):null]})}Tf.createRoot(document.getElementById("root")).render(o.jsx(Cf.StrictMode,{children:o.jsx(Em,{})}));