openfox 2.0.91 → 2.0.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,7 +46,7 @@ var Dj=Object.defineProperty;var Rj=Object.getPrototypeOf;var Oj=Reflect.get;var
46
46
  `);for(k=g=0;g<ie.length&&!ie[g].includes("DetermineComponentFrameRoot");)g++;for(;k<ge.length&&!ge[k].includes("DetermineComponentFrameRoot");)k++;if(g===ie.length||k===ge.length)for(g=ie.length-1,k=ge.length-1;1<=g&&0<=k&&ie[g]!==ge[k];)k--;for(;1<=g&&0<=k;g--,k--)if(ie[g]!==ge[k]){if(g!==1||k!==1)do if(g--,k--,0>k||ie[g]!==ge[k]){var ke=`
47
47
  `+ie[g].replace(" at new "," at ");return s.displayName&&ke.includes("<anonymous>")&&(ke=ke.replace("<anonymous>",s.displayName)),ke}while(1<=g&&0<=k);break}}}finally{ze=!1,Error.prepareStackTrace=f}return(f=s?s.displayName||s.name:"")?Me(f):""}function je(s,o){switch(s.tag){case 26:case 27:case 5:return Me(s.type);case 16:return Me("Lazy");case 13:return s.child!==o&&o!==null?Me("Suspense Fallback"):Me("Suspense");case 19:return Me("SuspenseList");case 0:case 15:return $e(s.type,!1);case 11:return $e(s.type.render,!1);case 1:return $e(s.type,!0);case 31:return Me("Activity");default:return""}}function rt(s){try{var o="",f=null;do o+=je(s,f),f=s,s=s.return;while(s);return o}catch(g){return`
48
48
  Error generating stack: `+g.message+`
49
- `+g.stack}}var Qe=Object.prototype.hasOwnProperty,fe=e.unstable_scheduleCallback,ce=e.unstable_cancelCallback,de=e.unstable_shouldYield,he=e.unstable_requestPaint,De=e.unstable_now,Ue=e.unstable_getCurrentPriorityLevel,re=e.unstable_ImmediatePriority,_e=e.unstable_UserBlockingPriority,Le=e.unstable_NormalPriority,He=e.unstable_LowPriority,qe=e.unstable_IdlePriority,Ke=e.log,tt=e.unstable_setDisableYieldValue,_t=null,It=null;function Kt(s){if(typeof Ke=="function"&&tt(s),It&&typeof It.setStrictMode=="function")try{It.setStrictMode(_t,s)}catch{}}var dt=Math.clz32?Math.clz32:Jt,kn=Math.log,jt=Math.LN2;function Jt(s){return s>>>=0,s===0?32:31-(kn(s)/jt|0)|0}var Br=256,ve=262144,Ve=4194304;function ae(s){var o=s&42;if(o!==0)return o;switch(s&-s){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:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function me(s,o,f){var g=s.pendingLanes;if(g===0)return 0;var k=0,A=s.suspendedLanes,F=s.pingedLanes;s=s.warmLanes;var Y=g&134217727;return Y!==0?(g=Y&~A,g!==0?k=ae(g):(F&=Y,F!==0?k=ae(F):f||(f=Y&~s,f!==0&&(k=ae(f))))):(Y=g&~A,Y!==0?k=ae(Y):F!==0?k=ae(F):f||(f=g&~s,f!==0&&(k=ae(f)))),k===0?0:o!==0&&o!==k&&(o&A)===0&&(A=k&-k,f=o&-o,A>=f||A===32&&(f&4194048)!==0)?o:k}function Ie(s,o){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&o)===0}function gt(s,o){switch(s){case 1:case 2:case 4:case 8:case 64:return o+250;case 16:case 32: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 o+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function vn(){var s=Ve;return Ve<<=1,(Ve&62914560)===0&&(Ve=4194304),s}function rn(s){for(var o=[],f=0;31>f;f++)o.push(s);return o}function Ce(s,o){s.pendingLanes|=o,o!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function Ne(s,o,f,g,k,A){var F=s.pendingLanes;s.pendingLanes=f,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=f,s.entangledLanes&=f,s.errorRecoveryDisabledLanes&=f,s.shellSuspendCounter=0;var Y=s.entanglements,ie=s.expirationTimes,ge=s.hiddenUpdates;for(f=F&~f;0<f;){var ke=31-dt(f),Ae=1<<ke;Y[ke]=0,ie[ke]=-1;var ye=ge[ke];if(ye!==null)for(ge[ke]=null,ke=0;ke<ye.length;ke++){var be=ye[ke];be!==null&&(be.lane&=-536870913)}f&=~Ae}g!==0&&Fe(s,g,0),A!==0&&k===0&&s.tag!==0&&(s.suspendedLanes|=A&~(F&~o))}function Fe(s,o,f){s.pendingLanes|=o,s.suspendedLanes&=~o;var g=31-dt(o);s.entangledLanes|=o,s.entanglements[g]=s.entanglements[g]|1073741824|f&261930}function Ye(s,o){var f=s.entangledLanes|=o;for(s=s.entanglements;f;){var g=31-dt(f),k=1<<g;k&o|s[g]&o&&(s[g]|=o),f&=~k}}function ot(s,o){var f=o&-o;return f=(f&42)!==0?1:nt(f),(f&(s.suspendedLanes|o))!==0?0:f}function nt(s){switch(s){case 2:s=1;break;case 8:s=4;break;case 32:s=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:s=128;break;case 268435456:s=134217728;break;default:s=0}return s}function xt(s){return s&=-s,2<s?8<s?(s&134217727)!==0?32:268435456:8:2}function sn(){var s=Z.p;return s!==0?s:(s=window.event,s===void 0?32:zv(s.type))}function Zt(s,o){var f=Z.p;try{return Z.p=s,o()}finally{Z.p=f}}var qt=Math.random().toString(36).slice(2),an="__reactFiber$"+qt,Fn="__reactProps$"+qt,ea="__reactContainer$"+qt,Kd="__reactEvents$"+qt,_2="__reactListeners$"+qt,S2="__reactHandles$"+qt,rx="__reactResources$"+qt,go="__reactMarker$"+qt;function Yd(s){delete s[an],delete s[Fn],delete s[Kd],delete s[_2],delete s[S2]}function ta(s){var o=s[an];if(o)return o;for(var f=s.parentNode;f;){if(o=f[ea]||f[an]){if(f=o.alternate,o.child!==null||f!==null&&f.child!==null)for(s=Cv(s);s!==null;){if(f=s[an])return f;s=Cv(s)}return o}s=f,f=s.parentNode}return null}function na(s){if(s=s[an]||s[ea]){var o=s.tag;if(o===5||o===6||o===13||o===31||o===26||o===27||o===3)return s}return null}function xo(s){var o=s.tag;if(o===5||o===26||o===27||o===6)return s.stateNode;throw Error(r(33))}function ra(s){var o=s[rx];return o||(o=s[rx]={hoistableStyles:new Map,hoistableScripts:new Map}),o}function _n(s){s[go]=!0}var sx=new Set,ix={};function mi(s,o){sa(s,o),sa(s+"Capture",o)}function sa(s,o){for(ix[s]=o,s=0;s<o.length;s++)sx.add(o[s])}var w2=RegExp("^[: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]*$"),ax={},ox={};function C2(s){return Qe.call(ox,s)?!0:Qe.call(ax,s)?!1:w2.test(s)?ox[s]=!0:(ax[s]=!0,!1)}function tc(s,o,f){if(C2(o))if(f===null)s.removeAttribute(o);else{switch(typeof f){case"undefined":case"function":case"symbol":s.removeAttribute(o);return;case"boolean":var g=o.toLowerCase().slice(0,5);if(g!=="data-"&&g!=="aria-"){s.removeAttribute(o);return}}s.setAttribute(o,""+f)}}function nc(s,o,f){if(f===null)s.removeAttribute(o);else{switch(typeof f){case"undefined":case"function":case"symbol":case"boolean":s.removeAttribute(o);return}s.setAttribute(o,""+f)}}function Jr(s,o,f,g){if(g===null)s.removeAttribute(f);else{switch(typeof g){case"undefined":case"function":case"symbol":case"boolean":s.removeAttribute(f);return}s.setAttributeNS(o,f,""+g)}}function dr(s){switch(typeof s){case"bigint":case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function lx(s){var o=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(o==="checkbox"||o==="radio")}function k2(s,o,f){var g=Object.getOwnPropertyDescriptor(s.constructor.prototype,o);if(!s.hasOwnProperty(o)&&typeof g<"u"&&typeof g.get=="function"&&typeof g.set=="function"){var k=g.get,A=g.set;return Object.defineProperty(s,o,{configurable:!0,get:function(){return k.call(this)},set:function(F){f=""+F,A.call(this,F)}}),Object.defineProperty(s,o,{enumerable:g.enumerable}),{getValue:function(){return f},setValue:function(F){f=""+F},stopTracking:function(){s._valueTracker=null,delete s[o]}}}}function Xd(s){if(!s._valueTracker){var o=lx(s)?"checked":"value";s._valueTracker=k2(s,o,""+s[o])}}function cx(s){if(!s)return!1;var o=s._valueTracker;if(!o)return!0;var f=o.getValue(),g="";return s&&(g=lx(s)?s.checked?"true":"false":s.value),s=g,s!==f?(o.setValue(s),!0):!1}function rc(s){if(s=s||(typeof document<"u"?document:void 0),typeof s>"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var E2=/[\n"\\]/g;function hr(s){return s.replace(E2,function(o){return"\\"+o.charCodeAt(0).toString(16)+" "})}function Qd(s,o,f,g,k,A,F,Y){s.name="",F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"?s.type=F:s.removeAttribute("type"),o!=null?F==="number"?(o===0&&s.value===""||s.value!=o)&&(s.value=""+dr(o)):s.value!==""+dr(o)&&(s.value=""+dr(o)):F!=="submit"&&F!=="reset"||s.removeAttribute("value"),o!=null?Jd(s,F,dr(o)):f!=null?Jd(s,F,dr(f)):g!=null&&s.removeAttribute("value"),k==null&&A!=null&&(s.defaultChecked=!!A),k!=null&&(s.checked=k&&typeof k!="function"&&typeof k!="symbol"),Y!=null&&typeof Y!="function"&&typeof Y!="symbol"&&typeof Y!="boolean"?s.name=""+dr(Y):s.removeAttribute("name")}function ux(s,o,f,g,k,A,F,Y){if(A!=null&&typeof A!="function"&&typeof A!="symbol"&&typeof A!="boolean"&&(s.type=A),o!=null||f!=null){if(!(A!=="submit"&&A!=="reset"||o!=null)){Xd(s);return}f=f!=null?""+dr(f):"",o=o!=null?""+dr(o):f,Y||o===s.value||(s.value=o),s.defaultValue=o}g=g??k,g=typeof g!="function"&&typeof g!="symbol"&&!!g,s.checked=Y?s.checked:!!g,s.defaultChecked=!!g,F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"&&(s.name=F),Xd(s)}function Jd(s,o,f){o==="number"&&rc(s.ownerDocument)===s||s.defaultValue===""+f||(s.defaultValue=""+f)}function ia(s,o,f,g){if(s=s.options,o){o={};for(var k=0;k<f.length;k++)o["$"+f[k]]=!0;for(f=0;f<s.length;f++)k=o.hasOwnProperty("$"+s[f].value),s[f].selected!==k&&(s[f].selected=k),k&&g&&(s[f].defaultSelected=!0)}else{for(f=""+dr(f),o=null,k=0;k<s.length;k++){if(s[k].value===f){s[k].selected=!0,g&&(s[k].defaultSelected=!0);return}o!==null||s[k].disabled||(o=s[k])}o!==null&&(o.selected=!0)}}function dx(s,o,f){if(o!=null&&(o=""+dr(o),o!==s.value&&(s.value=o),f==null)){s.defaultValue!==o&&(s.defaultValue=o);return}s.defaultValue=f!=null?""+dr(f):""}function hx(s,o,f,g){if(o==null){if(g!=null){if(f!=null)throw Error(r(92));if(V(g)){if(1<g.length)throw Error(r(93));g=g[0]}f=g}f==null&&(f=""),o=f}f=dr(o),s.defaultValue=f,g=s.textContent,g===f&&g!==""&&g!==null&&(s.value=g),Xd(s)}function aa(s,o){if(o){var f=s.firstChild;if(f&&f===s.lastChild&&f.nodeType===3){f.nodeValue=o;return}}s.textContent=o}var j2=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function fx(s,o,f){var g=o.indexOf("--")===0;f==null||typeof f=="boolean"||f===""?g?s.setProperty(o,""):o==="float"?s.cssFloat="":s[o]="":g?s.setProperty(o,f):typeof f!="number"||f===0||j2.has(o)?o==="float"?s.cssFloat=f:s[o]=(""+f).trim():s[o]=f+"px"}function mx(s,o,f){if(o!=null&&typeof o!="object")throw Error(r(62));if(s=s.style,f!=null){for(var g in f)!f.hasOwnProperty(g)||o!=null&&o.hasOwnProperty(g)||(g.indexOf("--")===0?s.setProperty(g,""):g==="float"?s.cssFloat="":s[g]="");for(var k in o)g=o[k],o.hasOwnProperty(k)&&f[k]!==g&&fx(s,k,g)}else for(var A in o)o.hasOwnProperty(A)&&fx(s,A,o[A])}function Zd(s){if(s.indexOf("-")===-1)return!1;switch(s){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 N2=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),T2=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function sc(s){return T2.test(""+s)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":s}function Zr(){}var eh=null;function th(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var oa=null,la=null;function px(s){var o=na(s);if(o&&(s=o.stateNode)){var f=s[Fn]||null;e:switch(s=o.stateNode,o.type){case"input":if(Qd(s,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name),o=f.name,f.type==="radio"&&o!=null){for(f=s;f.parentNode;)f=f.parentNode;for(f=f.querySelectorAll('input[name="'+hr(""+o)+'"][type="radio"]'),o=0;o<f.length;o++){var g=f[o];if(g!==s&&g.form===s.form){var k=g[Fn]||null;if(!k)throw Error(r(90));Qd(g,k.value,k.defaultValue,k.defaultValue,k.checked,k.defaultChecked,k.type,k.name)}}for(o=0;o<f.length;o++)g=f[o],g.form===s.form&&cx(g)}break e;case"textarea":dx(s,f.value,f.defaultValue);break e;case"select":o=f.value,o!=null&&ia(s,!!f.multiple,o,!1)}}}var nh=!1;function gx(s,o,f){if(nh)return s(o,f);nh=!0;try{var g=s(o);return g}finally{if(nh=!1,(oa!==null||la!==null)&&(Gc(),oa&&(o=oa,s=la,la=oa=null,px(o),s)))for(o=0;o<s.length;o++)px(s[o])}}function yo(s,o){var f=s.stateNode;if(f===null)return null;var g=f[Fn]||null;if(g===null)return null;f=g[o];e:switch(o){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(g=!g.disabled)||(s=s.type,g=!(s==="button"||s==="input"||s==="select"||s==="textarea")),s=!g;break e;default:s=!1}if(s)return null;if(f&&typeof f!="function")throw Error(r(231,o,typeof f));return f}var es=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),rh=!1;if(es)try{var bo={};Object.defineProperty(bo,"passive",{get:function(){rh=!0}}),window.addEventListener("test",bo,bo),window.removeEventListener("test",bo,bo)}catch{rh=!1}var Ts=null,sh=null,ic=null;function xx(){if(ic)return ic;var s,o=sh,f=o.length,g,k="value"in Ts?Ts.value:Ts.textContent,A=k.length;for(s=0;s<f&&o[s]===k[s];s++);var F=f-s;for(g=1;g<=F&&o[f-g]===k[A-g];g++);return ic=k.slice(s,1<g?1-g:void 0)}function ac(s){var o=s.keyCode;return"charCode"in s?(s=s.charCode,s===0&&o===13&&(s=13)):s=o,s===10&&(s=13),32<=s||s===13?s:0}function oc(){return!0}function yx(){return!1}function Vn(s){function o(f,g,k,A,F){this._reactName=f,this._targetInst=k,this.type=g,this.nativeEvent=A,this.target=F,this.currentTarget=null;for(var Y in s)s.hasOwnProperty(Y)&&(f=s[Y],this[Y]=f?f(A):A[Y]);return this.isDefaultPrevented=(A.defaultPrevented!=null?A.defaultPrevented:A.returnValue===!1)?oc:yx,this.isPropagationStopped=yx,this}return m(o.prototype,{preventDefault:function(){this.defaultPrevented=!0;var f=this.nativeEvent;f&&(f.preventDefault?f.preventDefault():typeof f.returnValue!="unknown"&&(f.returnValue=!1),this.isDefaultPrevented=oc)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=oc)},persist:function(){},isPersistent:oc}),o}var pi={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(s){return s.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},lc=Vn(pi),vo=m({},pi,{view:0,detail:0}),A2=Vn(vo),ih,ah,_o,cc=m({},vo,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:lh,button:0,buttons:0,relatedTarget:function(s){return s.relatedTarget===void 0?s.fromElement===s.srcElement?s.toElement:s.fromElement:s.relatedTarget},movementX:function(s){return"movementX"in s?s.movementX:(s!==_o&&(_o&&s.type==="mousemove"?(ih=s.screenX-_o.screenX,ah=s.screenY-_o.screenY):ah=ih=0,_o=s),ih)},movementY:function(s){return"movementY"in s?s.movementY:ah}}),bx=Vn(cc),L2=m({},cc,{dataTransfer:0}),D2=Vn(L2),R2=m({},vo,{relatedTarget:0}),oh=Vn(R2),O2=m({},pi,{animationName:0,elapsedTime:0,pseudoElement:0}),I2=Vn(O2),M2=m({},pi,{clipboardData:function(s){return"clipboardData"in s?s.clipboardData:window.clipboardData}}),P2=Vn(M2),B2=m({},pi,{data:0}),vx=Vn(B2),$2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},z2={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},H2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function U2(s){var o=this.nativeEvent;return o.getModifierState?o.getModifierState(s):(s=H2[s])?!!o[s]:!1}function lh(){return U2}var F2=m({},vo,{key:function(s){if(s.key){var o=$2[s.key]||s.key;if(o!=="Unidentified")return o}return s.type==="keypress"?(s=ac(s),s===13?"Enter":String.fromCharCode(s)):s.type==="keydown"||s.type==="keyup"?z2[s.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:lh,charCode:function(s){return s.type==="keypress"?ac(s):0},keyCode:function(s){return s.type==="keydown"||s.type==="keyup"?s.keyCode:0},which:function(s){return s.type==="keypress"?ac(s):s.type==="keydown"||s.type==="keyup"?s.keyCode:0}}),V2=Vn(F2),G2=m({},cc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),_x=Vn(G2),W2=m({},vo,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:lh}),q2=Vn(W2),K2=m({},pi,{propertyName:0,elapsedTime:0,pseudoElement:0}),Y2=Vn(K2),X2=m({},cc,{deltaX:function(s){return"deltaX"in s?s.deltaX:"wheelDeltaX"in s?-s.wheelDeltaX:0},deltaY:function(s){return"deltaY"in s?s.deltaY:"wheelDeltaY"in s?-s.wheelDeltaY:"wheelDelta"in s?-s.wheelDelta:0},deltaZ:0,deltaMode:0}),Q2=Vn(X2),J2=m({},pi,{newState:0,oldState:0}),Z2=Vn(J2),eE=[9,13,27,32],ch=es&&"CompositionEvent"in window,So=null;es&&"documentMode"in document&&(So=document.documentMode);var tE=es&&"TextEvent"in window&&!So,Sx=es&&(!ch||So&&8<So&&11>=So),wx=" ",Cx=!1;function kx(s,o){switch(s){case"keyup":return eE.indexOf(o.keyCode)!==-1;case"keydown":return o.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ex(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var ca=!1;function nE(s,o){switch(s){case"compositionend":return Ex(o);case"keypress":return o.which!==32?null:(Cx=!0,wx);case"textInput":return s=o.data,s===wx&&Cx?null:s;default:return null}}function rE(s,o){if(ca)return s==="compositionend"||!ch&&kx(s,o)?(s=xx(),ic=sh=Ts=null,ca=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(o.ctrlKey||o.altKey||o.metaKey)||o.ctrlKey&&o.altKey){if(o.char&&1<o.char.length)return o.char;if(o.which)return String.fromCharCode(o.which)}return null;case"compositionend":return Sx&&o.locale!=="ko"?null:o.data;default:return null}}var sE={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function jx(s){var o=s&&s.nodeName&&s.nodeName.toLowerCase();return o==="input"?!!sE[s.type]:o==="textarea"}function Nx(s,o,f,g){oa?la?la.push(g):la=[g]:oa=g,o=Jc(o,"onChange"),0<o.length&&(f=new lc("onChange","change",null,f,g),s.push({event:f,listeners:o}))}var wo=null,Co=null;function iE(s){uv(s,0)}function uc(s){var o=xo(s);if(cx(o))return s}function Tx(s,o){if(s==="change")return o}var Ax=!1;if(es){var uh;if(es){var dh="oninput"in document;if(!dh){var Lx=document.createElement("div");Lx.setAttribute("oninput","return;"),dh=typeof Lx.oninput=="function"}uh=dh}else uh=!1;Ax=uh&&(!document.documentMode||9<document.documentMode)}function Dx(){wo&&(wo.detachEvent("onpropertychange",Rx),Co=wo=null)}function Rx(s){if(s.propertyName==="value"&&uc(Co)){var o=[];Nx(o,Co,s,th(s)),gx(iE,o)}}function aE(s,o,f){s==="focusin"?(Dx(),wo=o,Co=f,wo.attachEvent("onpropertychange",Rx)):s==="focusout"&&Dx()}function oE(s){if(s==="selectionchange"||s==="keyup"||s==="keydown")return uc(Co)}function lE(s,o){if(s==="click")return uc(o)}function cE(s,o){if(s==="input"||s==="change")return uc(o)}function uE(s,o){return s===o&&(s!==0||1/s===1/o)||s!==s&&o!==o}var tr=typeof Object.is=="function"?Object.is:uE;function ko(s,o){if(tr(s,o))return!0;if(typeof s!="object"||s===null||typeof o!="object"||o===null)return!1;var f=Object.keys(s),g=Object.keys(o);if(f.length!==g.length)return!1;for(g=0;g<f.length;g++){var k=f[g];if(!Qe.call(o,k)||!tr(s[k],o[k]))return!1}return!0}function Ox(s){for(;s&&s.firstChild;)s=s.firstChild;return s}function Ix(s,o){var f=Ox(s);s=0;for(var g;f;){if(f.nodeType===3){if(g=s+f.textContent.length,s<=o&&g>=o)return{node:f,offset:o-s};s=g}e:{for(;f;){if(f.nextSibling){f=f.nextSibling;break e}f=f.parentNode}f=void 0}f=Ox(f)}}function Mx(s,o){return s&&o?s===o?!0:s&&s.nodeType===3?!1:o&&o.nodeType===3?Mx(s,o.parentNode):"contains"in s?s.contains(o):s.compareDocumentPosition?!!(s.compareDocumentPosition(o)&16):!1:!1}function Px(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var o=rc(s.document);o instanceof s.HTMLIFrameElement;){try{var f=typeof o.contentWindow.location.href=="string"}catch{f=!1}if(f)s=o.contentWindow;else break;o=rc(s.document)}return o}function hh(s){var o=s&&s.nodeName&&s.nodeName.toLowerCase();return o&&(o==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||o==="textarea"||s.contentEditable==="true")}var dE=es&&"documentMode"in document&&11>=document.documentMode,ua=null,fh=null,Eo=null,mh=!1;function Bx(s,o,f){var g=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;mh||ua==null||ua!==rc(g)||(g=ua,"selectionStart"in g&&hh(g)?g={start:g.selectionStart,end:g.selectionEnd}:(g=(g.ownerDocument&&g.ownerDocument.defaultView||window).getSelection(),g={anchorNode:g.anchorNode,anchorOffset:g.anchorOffset,focusNode:g.focusNode,focusOffset:g.focusOffset}),Eo&&ko(Eo,g)||(Eo=g,g=Jc(fh,"onSelect"),0<g.length&&(o=new lc("onSelect","select",null,o,f),s.push({event:o,listeners:g}),o.target=ua)))}function gi(s,o){var f={};return f[s.toLowerCase()]=o.toLowerCase(),f["Webkit"+s]="webkit"+o,f["Moz"+s]="moz"+o,f}var da={animationend:gi("Animation","AnimationEnd"),animationiteration:gi("Animation","AnimationIteration"),animationstart:gi("Animation","AnimationStart"),transitionrun:gi("Transition","TransitionRun"),transitionstart:gi("Transition","TransitionStart"),transitioncancel:gi("Transition","TransitionCancel"),transitionend:gi("Transition","TransitionEnd")},ph={},$x={};es&&($x=document.createElement("div").style,"AnimationEvent"in window||(delete da.animationend.animation,delete da.animationiteration.animation,delete da.animationstart.animation),"TransitionEvent"in window||delete da.transitionend.transition);function xi(s){if(ph[s])return ph[s];if(!da[s])return s;var o=da[s],f;for(f in o)if(o.hasOwnProperty(f)&&f in $x)return ph[s]=o[f];return s}var zx=xi("animationend"),Hx=xi("animationiteration"),Ux=xi("animationstart"),hE=xi("transitionrun"),fE=xi("transitionstart"),mE=xi("transitioncancel"),Fx=xi("transitionend"),Vx=new Map,gh="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");gh.push("scrollEnd");function jr(s,o){Vx.set(s,o),mi(o,[s])}var dc=typeof reportError=="function"?reportError:function(s){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var o=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof s=="object"&&s!==null&&typeof s.message=="string"?String(s.message):String(s),error:s});if(!window.dispatchEvent(o))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",s);return}console.error(s)},fr=[],ha=0,xh=0;function hc(){for(var s=ha,o=xh=ha=0;o<s;){var f=fr[o];fr[o++]=null;var g=fr[o];fr[o++]=null;var k=fr[o];fr[o++]=null;var A=fr[o];if(fr[o++]=null,g!==null&&k!==null){var F=g.pending;F===null?k.next=k:(k.next=F.next,F.next=k),g.pending=k}A!==0&&Gx(f,k,A)}}function fc(s,o,f,g){fr[ha++]=s,fr[ha++]=o,fr[ha++]=f,fr[ha++]=g,xh|=g,s.lanes|=g,s=s.alternate,s!==null&&(s.lanes|=g)}function yh(s,o,f,g){return fc(s,o,f,g),mc(s)}function yi(s,o){return fc(s,null,null,o),mc(s)}function Gx(s,o,f){s.lanes|=f;var g=s.alternate;g!==null&&(g.lanes|=f);for(var k=!1,A=s.return;A!==null;)A.childLanes|=f,g=A.alternate,g!==null&&(g.childLanes|=f),A.tag===22&&(s=A.stateNode,s===null||s._visibility&1||(k=!0)),s=A,A=A.return;return s.tag===3?(A=s.stateNode,k&&o!==null&&(k=31-dt(f),s=A.hiddenUpdates,g=s[k],g===null?s[k]=[o]:g.push(o),o.lane=f|536870912),A):null}function mc(s){if(50<Ko)throw Ko=0,Nf=null,Error(r(185));for(var o=s.return;o!==null;)s=o,o=s.return;return s.tag===3?s.stateNode:null}var fa={};function pE(s,o,f,g){this.tag=s,this.key=f,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=o,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=g,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function nr(s,o,f,g){return new pE(s,o,f,g)}function bh(s){return s=s.prototype,!(!s||!s.isReactComponent)}function ts(s,o){var f=s.alternate;return f===null?(f=nr(s.tag,o,s.key,s.mode),f.elementType=s.elementType,f.type=s.type,f.stateNode=s.stateNode,f.alternate=s,s.alternate=f):(f.pendingProps=o,f.type=s.type,f.flags=0,f.subtreeFlags=0,f.deletions=null),f.flags=s.flags&65011712,f.childLanes=s.childLanes,f.lanes=s.lanes,f.child=s.child,f.memoizedProps=s.memoizedProps,f.memoizedState=s.memoizedState,f.updateQueue=s.updateQueue,o=s.dependencies,f.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext},f.sibling=s.sibling,f.index=s.index,f.ref=s.ref,f.refCleanup=s.refCleanup,f}function Wx(s,o){s.flags&=65011714;var f=s.alternate;return f===null?(s.childLanes=0,s.lanes=o,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=f.childLanes,s.lanes=f.lanes,s.child=f.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=f.memoizedProps,s.memoizedState=f.memoizedState,s.updateQueue=f.updateQueue,s.type=f.type,o=f.dependencies,s.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext}),s}function pc(s,o,f,g,k,A){var F=0;if(g=s,typeof s=="function")bh(s)&&(F=1);else if(typeof s=="string")F=vj(s,f,ee.current)?26:s==="html"||s==="head"||s==="body"?27:5;else e:switch(s){case I:return s=nr(31,f,o,k),s.elementType=I,s.lanes=A,s;case C:return bi(f.children,k,A,o);case _:F=8,k|=24;break;case S:return s=nr(12,f,o,k|2),s.elementType=S,s.lanes=A,s;case j:return s=nr(13,f,o,k),s.elementType=j,s.lanes=A,s;case T:return s=nr(19,f,o,k),s.elementType=T,s.lanes=A,s;default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case b:F=10;break e;case v:F=9;break e;case E:F=11;break e;case D:F=14;break e;case L:F=16,g=null;break e}F=29,f=Error(r(130,s===null?"null":typeof s,"")),g=null}return o=nr(F,f,o,k),o.elementType=s,o.type=g,o.lanes=A,o}function bi(s,o,f,g){return s=nr(7,s,g,o),s.lanes=f,s}function vh(s,o,f){return s=nr(6,s,null,o),s.lanes=f,s}function qx(s){var o=nr(18,null,null,0);return o.stateNode=s,o}function _h(s,o,f){return o=nr(4,s.children!==null?s.children:[],s.key,o),o.lanes=f,o.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},o}var Kx=new WeakMap;function mr(s,o){if(typeof s=="object"&&s!==null){var f=Kx.get(s);return f!==void 0?f:(o={value:s,source:o,stack:rt(o)},Kx.set(s,o),o)}return{value:s,source:o,stack:rt(o)}}var ma=[],pa=0,gc=null,jo=0,pr=[],gr=0,As=null,$r=1,zr="";function ns(s,o){ma[pa++]=jo,ma[pa++]=gc,gc=s,jo=o}function Yx(s,o,f){pr[gr++]=$r,pr[gr++]=zr,pr[gr++]=As,As=s;var g=$r;s=zr;var k=32-dt(g)-1;g&=~(1<<k),f+=1;var A=32-dt(o)+k;if(30<A){var F=k-k%5;A=(g&(1<<F)-1).toString(32),g>>=F,k-=F,$r=1<<32-dt(o)+k|f<<k|g,zr=A+s}else $r=1<<A|f<<k|g,zr=s}function Sh(s){s.return!==null&&(ns(s,1),Yx(s,1,0))}function wh(s){for(;s===gc;)gc=ma[--pa],ma[pa]=null,jo=ma[--pa],ma[pa]=null;for(;s===As;)As=pr[--gr],pr[gr]=null,zr=pr[--gr],pr[gr]=null,$r=pr[--gr],pr[gr]=null}function Xx(s,o){pr[gr++]=$r,pr[gr++]=zr,pr[gr++]=As,$r=o.id,zr=o.overflow,As=s}var En=null,Vt=null,vt=!1,Ls=null,xr=!1,Ch=Error(r(519));function Ds(s){var o=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw No(mr(o,s)),Ch}function Qx(s){var o=s.stateNode,f=s.type,g=s.memoizedProps;switch(o[an]=s,o[Fn]=g,f){case"dialog":ft("cancel",o),ft("close",o);break;case"iframe":case"object":case"embed":ft("load",o);break;case"video":case"audio":for(f=0;f<Xo.length;f++)ft(Xo[f],o);break;case"source":ft("error",o);break;case"img":case"image":case"link":ft("error",o),ft("load",o);break;case"details":ft("toggle",o);break;case"input":ft("invalid",o),ux(o,g.value,g.defaultValue,g.checked,g.defaultChecked,g.type,g.name,!0);break;case"select":ft("invalid",o);break;case"textarea":ft("invalid",o),hx(o,g.value,g.defaultValue,g.children)}f=g.children,typeof f!="string"&&typeof f!="number"&&typeof f!="bigint"||o.textContent===""+f||g.suppressHydrationWarning===!0||mv(o.textContent,f)?(g.popover!=null&&(ft("beforetoggle",o),ft("toggle",o)),g.onScroll!=null&&ft("scroll",o),g.onScrollEnd!=null&&ft("scrollend",o),g.onClick!=null&&(o.onclick=Zr),o=!0):o=!1,o||Ds(s,!0)}function Jx(s){for(En=s.return;En;)switch(En.tag){case 5:case 31:case 13:xr=!1;return;case 27:case 3:xr=!0;return;default:En=En.return}}function ga(s){if(s!==En)return!1;if(!vt)return Jx(s),vt=!0,!1;var o=s.tag,f;if((f=o!==3&&o!==27)&&((f=o===5)&&(f=s.type,f=!(f!=="form"&&f!=="button")||Ff(s.type,s.memoizedProps)),f=!f),f&&Vt&&Ds(s),Jx(s),o===13){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Vt=wv(s)}else if(o===31){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Vt=wv(s)}else o===27?(o=Vt,Ws(s.type)?(s=Kf,Kf=null,Vt=s):Vt=o):Vt=En?br(s.stateNode.nextSibling):null;return!0}function vi(){Vt=En=null,vt=!1}function kh(){var s=Ls;return s!==null&&(Kn===null?Kn=s:Kn.push.apply(Kn,s),Ls=null),s}function No(s){Ls===null?Ls=[s]:Ls.push(s)}var Eh=M(null),_i=null,rs=null;function Rs(s,o,f){z(Eh,o._currentValue),o._currentValue=f}function ss(s){s._currentValue=Eh.current,q(Eh)}function jh(s,o,f){for(;s!==null;){var g=s.alternate;if((s.childLanes&o)!==o?(s.childLanes|=o,g!==null&&(g.childLanes|=o)):g!==null&&(g.childLanes&o)!==o&&(g.childLanes|=o),s===f)break;s=s.return}}function Nh(s,o,f,g){var k=s.child;for(k!==null&&(k.return=s);k!==null;){var A=k.dependencies;if(A!==null){var F=k.child;A=A.firstContext;e:for(;A!==null;){var Y=A;A=k;for(var ie=0;ie<o.length;ie++)if(Y.context===o[ie]){A.lanes|=f,Y=A.alternate,Y!==null&&(Y.lanes|=f),jh(A.return,f,s),g||(F=null);break e}A=Y.next}}else if(k.tag===18){if(F=k.return,F===null)throw Error(r(341));F.lanes|=f,A=F.alternate,A!==null&&(A.lanes|=f),jh(F,f,s),F=null}else F=k.child;if(F!==null)F.return=k;else for(F=k;F!==null;){if(F===s){F=null;break}if(k=F.sibling,k!==null){k.return=F.return,F=k;break}F=F.return}k=F}}function xa(s,o,f,g){s=null;for(var k=o,A=!1;k!==null;){if(!A){if((k.flags&524288)!==0)A=!0;else if((k.flags&262144)!==0)break}if(k.tag===10){var F=k.alternate;if(F===null)throw Error(r(387));if(F=F.memoizedProps,F!==null){var Y=k.type;tr(k.pendingProps.value,F.value)||(s!==null?s.push(Y):s=[Y])}}else if(k===K.current){if(F=k.alternate,F===null)throw Error(r(387));F.memoizedState.memoizedState!==k.memoizedState.memoizedState&&(s!==null?s.push(tl):s=[tl])}k=k.return}s!==null&&Nh(o,s,f,g),o.flags|=262144}function xc(s){for(s=s.firstContext;s!==null;){if(!tr(s.context._currentValue,s.memoizedValue))return!0;s=s.next}return!1}function Si(s){_i=s,rs=null,s=s.dependencies,s!==null&&(s.firstContext=null)}function jn(s){return Zx(_i,s)}function yc(s,o){return _i===null&&Si(s),Zx(s,o)}function Zx(s,o){var f=o._currentValue;if(o={context:o,memoizedValue:f,next:null},rs===null){if(s===null)throw Error(r(308));rs=o,s.dependencies={lanes:0,firstContext:o},s.flags|=524288}else rs=rs.next=o;return f}var gE=typeof AbortController<"u"?AbortController:function(){var s=[],o=this.signal={aborted:!1,addEventListener:function(f,g){s.push(g)}};this.abort=function(){o.aborted=!0,s.forEach(function(f){return f()})}},xE=e.unstable_scheduleCallback,yE=e.unstable_NormalPriority,on={$$typeof:b,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Th(){return{controller:new gE,data:new Map,refCount:0}}function To(s){s.refCount--,s.refCount===0&&xE(yE,function(){s.controller.abort()})}var Ao=null,Ah=0,ya=0,ba=null;function bE(s,o){if(Ao===null){var f=Ao=[];Ah=0,ya=Of(),ba={status:"pending",value:void 0,then:function(g){f.push(g)}}}return Ah++,o.then(ey,ey),o}function ey(){if(--Ah===0&&Ao!==null){ba!==null&&(ba.status="fulfilled");var s=Ao;Ao=null,ya=0,ba=null;for(var o=0;o<s.length;o++)(0,s[o])()}}function vE(s,o){var f=[],g={status:"pending",value:null,reason:null,then:function(k){f.push(k)}};return s.then(function(){g.status="fulfilled",g.value=o;for(var k=0;k<f.length;k++)(0,f[k])(o)},function(k){for(g.status="rejected",g.reason=k,k=0;k<f.length;k++)(0,f[k])(void 0)}),g}var ty=G.S;G.S=function(s,o){Bb=De(),typeof o=="object"&&o!==null&&typeof o.then=="function"&&bE(s,o),ty!==null&&ty(s,o)};var wi=M(null);function Lh(){var s=wi.current;return s!==null?s:Mt.pooledCache}function bc(s,o){o===null?z(wi,wi.current):z(wi,o.pool)}function ny(){var s=Lh();return s===null?null:{parent:on._currentValue,pool:s}}var va=Error(r(460)),Dh=Error(r(474)),vc=Error(r(542)),_c={then:function(){}};function ry(s){return s=s.status,s==="fulfilled"||s==="rejected"}function sy(s,o,f){switch(f=s[f],f===void 0?s.push(o):f!==o&&(o.then(Zr,Zr),o=f),o.status){case"fulfilled":return o.value;case"rejected":throw s=o.reason,ay(s),s;default:if(typeof o.status=="string")o.then(Zr,Zr);else{if(s=Mt,s!==null&&100<s.shellSuspendCounter)throw Error(r(482));s=o,s.status="pending",s.then(function(g){if(o.status==="pending"){var k=o;k.status="fulfilled",k.value=g}},function(g){if(o.status==="pending"){var k=o;k.status="rejected",k.reason=g}})}switch(o.status){case"fulfilled":return o.value;case"rejected":throw s=o.reason,ay(s),s}throw ki=o,va}}function Ci(s){try{var o=s._init;return o(s._payload)}catch(f){throw f!==null&&typeof f=="object"&&typeof f.then=="function"?(ki=f,va):f}}var ki=null;function iy(){if(ki===null)throw Error(r(459));var s=ki;return ki=null,s}function ay(s){if(s===va||s===vc)throw Error(r(483))}var _a=null,Lo=0;function Sc(s){var o=Lo;return Lo+=1,_a===null&&(_a=[]),sy(_a,s,o)}function Do(s,o){o=o.props.ref,s.ref=o!==void 0?o:null}function wc(s,o){throw o.$$typeof===x?Error(r(525)):(s=Object.prototype.toString.call(o),Error(r(31,s==="[object Object]"?"object with keys {"+Object.keys(o).join(", ")+"}":s)))}function oy(s){function o(ue,le){if(s){var pe=ue.deletions;pe===null?(ue.deletions=[le],ue.flags|=16):pe.push(le)}}function f(ue,le){if(!s)return null;for(;le!==null;)o(ue,le),le=le.sibling;return null}function g(ue){for(var le=new Map;ue!==null;)ue.key!==null?le.set(ue.key,ue):le.set(ue.index,ue),ue=ue.sibling;return le}function k(ue,le){return ue=ts(ue,le),ue.index=0,ue.sibling=null,ue}function A(ue,le,pe){return ue.index=pe,s?(pe=ue.alternate,pe!==null?(pe=pe.index,pe<le?(ue.flags|=67108866,le):pe):(ue.flags|=67108866,le)):(ue.flags|=1048576,le)}function F(ue){return s&&ue.alternate===null&&(ue.flags|=67108866),ue}function Y(ue,le,pe,Ee){return le===null||le.tag!==6?(le=vh(pe,ue.mode,Ee),le.return=ue,le):(le=k(le,pe),le.return=ue,le)}function ie(ue,le,pe,Ee){var Xe=pe.type;return Xe===C?ke(ue,le,pe.props.children,Ee,pe.key):le!==null&&(le.elementType===Xe||typeof Xe=="object"&&Xe!==null&&Xe.$$typeof===L&&Ci(Xe)===le.type)?(le=k(le,pe.props),Do(le,pe),le.return=ue,le):(le=pc(pe.type,pe.key,pe.props,null,ue.mode,Ee),Do(le,pe),le.return=ue,le)}function ge(ue,le,pe,Ee){return le===null||le.tag!==4||le.stateNode.containerInfo!==pe.containerInfo||le.stateNode.implementation!==pe.implementation?(le=_h(pe,ue.mode,Ee),le.return=ue,le):(le=k(le,pe.children||[]),le.return=ue,le)}function ke(ue,le,pe,Ee,Xe){return le===null||le.tag!==7?(le=bi(pe,ue.mode,Ee,Xe),le.return=ue,le):(le=k(le,pe),le.return=ue,le)}function Ae(ue,le,pe){if(typeof le=="string"&&le!==""||typeof le=="number"||typeof le=="bigint")return le=vh(""+le,ue.mode,pe),le.return=ue,le;if(typeof le=="object"&&le!==null){switch(le.$$typeof){case y:return pe=pc(le.type,le.key,le.props,null,ue.mode,pe),Do(pe,le),pe.return=ue,pe;case w:return le=_h(le,ue.mode,pe),le.return=ue,le;case L:return le=Ci(le),Ae(ue,le,pe)}if(V(le)||H(le))return le=bi(le,ue.mode,pe,null),le.return=ue,le;if(typeof le.then=="function")return Ae(ue,Sc(le),pe);if(le.$$typeof===b)return Ae(ue,yc(ue,le),pe);wc(ue,le)}return null}function ye(ue,le,pe,Ee){var Xe=le!==null?le.key:null;if(typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint")return Xe!==null?null:Y(ue,le,""+pe,Ee);if(typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case y:return pe.key===Xe?ie(ue,le,pe,Ee):null;case w:return pe.key===Xe?ge(ue,le,pe,Ee):null;case L:return pe=Ci(pe),ye(ue,le,pe,Ee)}if(V(pe)||H(pe))return Xe!==null?null:ke(ue,le,pe,Ee,null);if(typeof pe.then=="function")return ye(ue,le,Sc(pe),Ee);if(pe.$$typeof===b)return ye(ue,le,yc(ue,pe),Ee);wc(ue,pe)}return null}function be(ue,le,pe,Ee,Xe){if(typeof Ee=="string"&&Ee!==""||typeof Ee=="number"||typeof Ee=="bigint")return ue=ue.get(pe)||null,Y(le,ue,""+Ee,Xe);if(typeof Ee=="object"&&Ee!==null){switch(Ee.$$typeof){case y:return ue=ue.get(Ee.key===null?pe:Ee.key)||null,ie(le,ue,Ee,Xe);case w:return ue=ue.get(Ee.key===null?pe:Ee.key)||null,ge(le,ue,Ee,Xe);case L:return Ee=Ci(Ee),be(ue,le,pe,Ee,Xe)}if(V(Ee)||H(Ee))return ue=ue.get(pe)||null,ke(le,ue,Ee,Xe,null);if(typeof Ee.then=="function")return be(ue,le,pe,Sc(Ee),Xe);if(Ee.$$typeof===b)return be(ue,le,pe,yc(le,Ee),Xe);wc(le,Ee)}return null}function Ge(ue,le,pe,Ee){for(var Xe=null,Ct=null,We=le,lt=le=0,bt=null;We!==null&&lt<pe.length;lt++){We.index>lt?(bt=We,We=null):bt=We.sibling;var kt=ye(ue,We,pe[lt],Ee);if(kt===null){We===null&&(We=bt);break}s&&We&&kt.alternate===null&&o(ue,We),le=A(kt,le,lt),Ct===null?Xe=kt:Ct.sibling=kt,Ct=kt,We=bt}if(lt===pe.length)return f(ue,We),vt&&ns(ue,lt),Xe;if(We===null){for(;lt<pe.length;lt++)We=Ae(ue,pe[lt],Ee),We!==null&&(le=A(We,le,lt),Ct===null?Xe=We:Ct.sibling=We,Ct=We);return vt&&ns(ue,lt),Xe}for(We=g(We);lt<pe.length;lt++)bt=be(We,ue,lt,pe[lt],Ee),bt!==null&&(s&&bt.alternate!==null&&We.delete(bt.key===null?lt:bt.key),le=A(bt,le,lt),Ct===null?Xe=bt:Ct.sibling=bt,Ct=bt);return s&&We.forEach(function(Qs){return o(ue,Qs)}),vt&&ns(ue,lt),Xe}function et(ue,le,pe,Ee){if(pe==null)throw Error(r(151));for(var Xe=null,Ct=null,We=le,lt=le=0,bt=null,kt=pe.next();We!==null&&!kt.done;lt++,kt=pe.next()){We.index>lt?(bt=We,We=null):bt=We.sibling;var Qs=ye(ue,We,kt.value,Ee);if(Qs===null){We===null&&(We=bt);break}s&&We&&Qs.alternate===null&&o(ue,We),le=A(Qs,le,lt),Ct===null?Xe=Qs:Ct.sibling=Qs,Ct=Qs,We=bt}if(kt.done)return f(ue,We),vt&&ns(ue,lt),Xe;if(We===null){for(;!kt.done;lt++,kt=pe.next())kt=Ae(ue,kt.value,Ee),kt!==null&&(le=A(kt,le,lt),Ct===null?Xe=kt:Ct.sibling=kt,Ct=kt);return vt&&ns(ue,lt),Xe}for(We=g(We);!kt.done;lt++,kt=pe.next())kt=be(We,ue,lt,kt.value,Ee),kt!==null&&(s&&kt.alternate!==null&&We.delete(kt.key===null?lt:kt.key),le=A(kt,le,lt),Ct===null?Xe=kt:Ct.sibling=kt,Ct=kt);return s&&We.forEach(function(Lj){return o(ue,Lj)}),vt&&ns(ue,lt),Xe}function Dt(ue,le,pe,Ee){if(typeof pe=="object"&&pe!==null&&pe.type===C&&pe.key===null&&(pe=pe.props.children),typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case y:e:{for(var Xe=pe.key;le!==null;){if(le.key===Xe){if(Xe=pe.type,Xe===C){if(le.tag===7){f(ue,le.sibling),Ee=k(le,pe.props.children),Ee.return=ue,ue=Ee;break e}}else if(le.elementType===Xe||typeof Xe=="object"&&Xe!==null&&Xe.$$typeof===L&&Ci(Xe)===le.type){f(ue,le.sibling),Ee=k(le,pe.props),Do(Ee,pe),Ee.return=ue,ue=Ee;break e}f(ue,le);break}else o(ue,le);le=le.sibling}pe.type===C?(Ee=bi(pe.props.children,ue.mode,Ee,pe.key),Ee.return=ue,ue=Ee):(Ee=pc(pe.type,pe.key,pe.props,null,ue.mode,Ee),Do(Ee,pe),Ee.return=ue,ue=Ee)}return F(ue);case w:e:{for(Xe=pe.key;le!==null;){if(le.key===Xe)if(le.tag===4&&le.stateNode.containerInfo===pe.containerInfo&&le.stateNode.implementation===pe.implementation){f(ue,le.sibling),Ee=k(le,pe.children||[]),Ee.return=ue,ue=Ee;break e}else{f(ue,le);break}else o(ue,le);le=le.sibling}Ee=_h(pe,ue.mode,Ee),Ee.return=ue,ue=Ee}return F(ue);case L:return pe=Ci(pe),Dt(ue,le,pe,Ee)}if(V(pe))return Ge(ue,le,pe,Ee);if(H(pe)){if(Xe=H(pe),typeof Xe!="function")throw Error(r(150));return pe=Xe.call(pe),et(ue,le,pe,Ee)}if(typeof pe.then=="function")return Dt(ue,le,Sc(pe),Ee);if(pe.$$typeof===b)return Dt(ue,le,yc(ue,pe),Ee);wc(ue,pe)}return typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint"?(pe=""+pe,le!==null&&le.tag===6?(f(ue,le.sibling),Ee=k(le,pe),Ee.return=ue,ue=Ee):(f(ue,le),Ee=vh(pe,ue.mode,Ee),Ee.return=ue,ue=Ee),F(ue)):f(ue,le)}return function(ue,le,pe,Ee){try{Lo=0;var Xe=Dt(ue,le,pe,Ee);return _a=null,Xe}catch(We){if(We===va||We===vc)throw We;var Ct=nr(29,We,null,ue.mode);return Ct.lanes=Ee,Ct.return=ue,Ct}finally{}}}var Ei=oy(!0),ly=oy(!1),Os=!1;function Rh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Oh(s,o){s=s.updateQueue,o.updateQueue===s&&(o.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function Is(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function Ms(s,o,f){var g=s.updateQueue;if(g===null)return null;if(g=g.shared,(Et&2)!==0){var k=g.pending;return k===null?o.next=o:(o.next=k.next,k.next=o),g.pending=o,o=mc(s),Gx(s,null,f),o}return fc(s,g,o,f),mc(s)}function Ro(s,o,f){if(o=o.updateQueue,o!==null&&(o=o.shared,(f&4194048)!==0)){var g=o.lanes;g&=s.pendingLanes,f|=g,o.lanes=f,Ye(s,f)}}function Ih(s,o){var f=s.updateQueue,g=s.alternate;if(g!==null&&(g=g.updateQueue,f===g)){var k=null,A=null;if(f=f.firstBaseUpdate,f!==null){do{var F={lane:f.lane,tag:f.tag,payload:f.payload,callback:null,next:null};A===null?k=A=F:A=A.next=F,f=f.next}while(f!==null);A===null?k=A=o:A=A.next=o}else k=A=o;f={baseState:g.baseState,firstBaseUpdate:k,lastBaseUpdate:A,shared:g.shared,callbacks:g.callbacks},s.updateQueue=f;return}s=f.lastBaseUpdate,s===null?f.firstBaseUpdate=o:s.next=o,f.lastBaseUpdate=o}var Mh=!1;function Oo(){if(Mh){var s=ba;if(s!==null)throw s}}function Io(s,o,f,g){Mh=!1;var k=s.updateQueue;Os=!1;var A=k.firstBaseUpdate,F=k.lastBaseUpdate,Y=k.shared.pending;if(Y!==null){k.shared.pending=null;var ie=Y,ge=ie.next;ie.next=null,F===null?A=ge:F.next=ge,F=ie;var ke=s.alternate;ke!==null&&(ke=ke.updateQueue,Y=ke.lastBaseUpdate,Y!==F&&(Y===null?ke.firstBaseUpdate=ge:Y.next=ge,ke.lastBaseUpdate=ie))}if(A!==null){var Ae=k.baseState;F=0,ke=ge=ie=null,Y=A;do{var ye=Y.lane&-536870913,be=ye!==Y.lane;if(be?(yt&ye)===ye:(g&ye)===ye){ye!==0&&ye===ya&&(Mh=!0),ke!==null&&(ke=ke.next={lane:0,tag:Y.tag,payload:Y.payload,callback:null,next:null});e:{var Ge=s,et=Y;ye=o;var Dt=f;switch(et.tag){case 1:if(Ge=et.payload,typeof Ge=="function"){Ae=Ge.call(Dt,Ae,ye);break e}Ae=Ge;break e;case 3:Ge.flags=Ge.flags&-65537|128;case 0:if(Ge=et.payload,ye=typeof Ge=="function"?Ge.call(Dt,Ae,ye):Ge,ye==null)break e;Ae=m({},Ae,ye);break e;case 2:Os=!0}}ye=Y.callback,ye!==null&&(s.flags|=64,be&&(s.flags|=8192),be=k.callbacks,be===null?k.callbacks=[ye]:be.push(ye))}else be={lane:ye,tag:Y.tag,payload:Y.payload,callback:Y.callback,next:null},ke===null?(ge=ke=be,ie=Ae):ke=ke.next=be,F|=ye;if(Y=Y.next,Y===null){if(Y=k.shared.pending,Y===null)break;be=Y,Y=be.next,be.next=null,k.lastBaseUpdate=be,k.shared.pending=null}}while(!0);ke===null&&(ie=Ae),k.baseState=ie,k.firstBaseUpdate=ge,k.lastBaseUpdate=ke,A===null&&(k.shared.lanes=0),Hs|=F,s.lanes=F,s.memoizedState=Ae}}function cy(s,o){if(typeof s!="function")throw Error(r(191,s));s.call(o)}function uy(s,o){var f=s.callbacks;if(f!==null)for(s.callbacks=null,s=0;s<f.length;s++)cy(f[s],o)}var Sa=M(null),Cc=M(0);function dy(s,o){s=fs,z(Cc,s),z(Sa,o),fs=s|o.baseLanes}function Ph(){z(Cc,fs),z(Sa,Sa.current)}function Bh(){fs=Cc.current,q(Sa),q(Cc)}var rr=M(null),yr=null;function Ps(s){var o=s.alternate;z(en,en.current&1),z(rr,s),yr===null&&(o===null||Sa.current!==null||o.memoizedState!==null)&&(yr=s)}function $h(s){z(en,en.current),z(rr,s),yr===null&&(yr=s)}function hy(s){s.tag===22?(z(en,en.current),z(rr,s),yr===null&&(yr=s)):Bs()}function Bs(){z(en,en.current),z(rr,rr.current)}function sr(s){q(rr),yr===s&&(yr=null),q(en)}var en=M(0);function kc(s){for(var o=s;o!==null;){if(o.tag===13){var f=o.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||Wf(f)||qf(f)))return o}else if(o.tag===19&&(o.memoizedProps.revealOrder==="forwards"||o.memoizedProps.revealOrder==="backwards"||o.memoizedProps.revealOrder==="unstable_legacy-backwards"||o.memoizedProps.revealOrder==="together")){if((o.flags&128)!==0)return o}else if(o.child!==null){o.child.return=o,o=o.child;continue}if(o===s)break;for(;o.sibling===null;){if(o.return===null||o.return===s)return null;o=o.return}o.sibling.return=o.return,o=o.sibling}return null}var is=0,at=null,At=null,ln=null,Ec=!1,wa=!1,ji=!1,jc=0,Mo=0,Ca=null,_E=0;function Yt(){throw Error(r(321))}function zh(s,o){if(o===null)return!1;for(var f=0;f<o.length&&f<s.length;f++)if(!tr(s[f],o[f]))return!1;return!0}function Hh(s,o,f,g,k,A){return is=A,at=o,o.memoizedState=null,o.updateQueue=null,o.lanes=0,G.H=s===null||s.memoizedState===null?Yy:nf,ji=!1,A=f(g,k),ji=!1,wa&&(A=my(o,f,g,k)),fy(s),A}function fy(s){G.H=$o;var o=At!==null&&At.next!==null;if(is=0,ln=At=at=null,Ec=!1,Mo=0,Ca=null,o)throw Error(r(300));s===null||cn||(s=s.dependencies,s!==null&&xc(s)&&(cn=!0))}function my(s,o,f,g){at=s;var k=0;do{if(wa&&(Ca=null),Mo=0,wa=!1,25<=k)throw Error(r(301));if(k+=1,ln=At=null,s.updateQueue!=null){var A=s.updateQueue;A.lastEffect=null,A.events=null,A.stores=null,A.memoCache!=null&&(A.memoCache.index=0)}G.H=Xy,A=o(f,g)}while(wa);return A}function SE(){var s=G.H,o=s.useState()[0];return o=typeof o.then=="function"?Po(o):o,s=s.useState()[0],(At!==null?At.memoizedState:null)!==s&&(at.flags|=1024),o}function Uh(){var s=jc!==0;return jc=0,s}function Fh(s,o,f){o.updateQueue=s.updateQueue,o.flags&=-2053,s.lanes&=~f}function Vh(s){if(Ec){for(s=s.memoizedState;s!==null;){var o=s.queue;o!==null&&(o.pending=null),s=s.next}Ec=!1}is=0,ln=At=at=null,wa=!1,Mo=jc=0,Ca=null}function Bn(){var s={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ln===null?at.memoizedState=ln=s:ln=ln.next=s,ln}function tn(){if(At===null){var s=at.alternate;s=s!==null?s.memoizedState:null}else s=At.next;var o=ln===null?at.memoizedState:ln.next;if(o!==null)ln=o,At=s;else{if(s===null)throw at.alternate===null?Error(r(467)):Error(r(310));At=s,s={memoizedState:At.memoizedState,baseState:At.baseState,baseQueue:At.baseQueue,queue:At.queue,next:null},ln===null?at.memoizedState=ln=s:ln=ln.next=s}return ln}function Nc(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Po(s){var o=Mo;return Mo+=1,Ca===null&&(Ca=[]),s=sy(Ca,s,o),o=at,(ln===null?o.memoizedState:ln.next)===null&&(o=o.alternate,G.H=o===null||o.memoizedState===null?Yy:nf),s}function Tc(s){if(s!==null&&typeof s=="object"){if(typeof s.then=="function")return Po(s);if(s.$$typeof===b)return jn(s)}throw Error(r(438,String(s)))}function Gh(s){var o=null,f=at.updateQueue;if(f!==null&&(o=f.memoCache),o==null){var g=at.alternate;g!==null&&(g=g.updateQueue,g!==null&&(g=g.memoCache,g!=null&&(o={data:g.data.map(function(k){return k.slice()}),index:0})))}if(o==null&&(o={data:[],index:0}),f===null&&(f=Nc(),at.updateQueue=f),f.memoCache=o,f=o.data[o.index],f===void 0)for(f=o.data[o.index]=Array(s),g=0;g<s;g++)f[g]=P;return o.index++,f}function as(s,o){return typeof o=="function"?o(s):o}function Ac(s){var o=tn();return Wh(o,At,s)}function Wh(s,o,f){var g=s.queue;if(g===null)throw Error(r(311));g.lastRenderedReducer=f;var k=s.baseQueue,A=g.pending;if(A!==null){if(k!==null){var F=k.next;k.next=A.next,A.next=F}o.baseQueue=k=A,g.pending=null}if(A=s.baseState,k===null)s.memoizedState=A;else{o=k.next;var Y=F=null,ie=null,ge=o,ke=!1;do{var Ae=ge.lane&-536870913;if(Ae!==ge.lane?(yt&Ae)===Ae:(is&Ae)===Ae){var ye=ge.revertLane;if(ye===0)ie!==null&&(ie=ie.next={lane:0,revertLane:0,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null}),Ae===ya&&(ke=!0);else if((is&ye)===ye){ge=ge.next,ye===ya&&(ke=!0);continue}else Ae={lane:0,revertLane:ge.revertLane,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},ie===null?(Y=ie=Ae,F=A):ie=ie.next=Ae,at.lanes|=ye,Hs|=ye;Ae=ge.action,ji&&f(A,Ae),A=ge.hasEagerState?ge.eagerState:f(A,Ae)}else ye={lane:Ae,revertLane:ge.revertLane,gesture:ge.gesture,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},ie===null?(Y=ie=ye,F=A):ie=ie.next=ye,at.lanes|=Ae,Hs|=Ae;ge=ge.next}while(ge!==null&&ge!==o);if(ie===null?F=A:ie.next=Y,!tr(A,s.memoizedState)&&(cn=!0,ke&&(f=ba,f!==null)))throw f;s.memoizedState=A,s.baseState=F,s.baseQueue=ie,g.lastRenderedState=A}return k===null&&(g.lanes=0),[s.memoizedState,g.dispatch]}function qh(s){var o=tn(),f=o.queue;if(f===null)throw Error(r(311));f.lastRenderedReducer=s;var g=f.dispatch,k=f.pending,A=o.memoizedState;if(k!==null){f.pending=null;var F=k=k.next;do A=s(A,F.action),F=F.next;while(F!==k);tr(A,o.memoizedState)||(cn=!0),o.memoizedState=A,o.baseQueue===null&&(o.baseState=A),f.lastRenderedState=A}return[A,g]}function py(s,o,f){var g=at,k=tn(),A=vt;if(A){if(f===void 0)throw Error(r(407));f=f()}else f=o();var F=!tr((At||k).memoizedState,f);if(F&&(k.memoizedState=f,cn=!0),k=k.queue,Xh(yy.bind(null,g,k,s),[s]),k.getSnapshot!==o||F||ln!==null&&ln.memoizedState.tag&1){if(g.flags|=2048,ka(9,{destroy:void 0},xy.bind(null,g,k,f,o),null),Mt===null)throw Error(r(349));A||(is&127)!==0||gy(g,o,f)}return f}function gy(s,o,f){s.flags|=16384,s={getSnapshot:o,value:f},o=at.updateQueue,o===null?(o=Nc(),at.updateQueue=o,o.stores=[s]):(f=o.stores,f===null?o.stores=[s]:f.push(s))}function xy(s,o,f,g){o.value=f,o.getSnapshot=g,by(o)&&vy(s)}function yy(s,o,f){return f(function(){by(o)&&vy(s)})}function by(s){var o=s.getSnapshot;s=s.value;try{var f=o();return!tr(s,f)}catch{return!0}}function vy(s){var o=yi(s,2);o!==null&&Yn(o,s,2)}function Kh(s){var o=Bn();if(typeof s=="function"){var f=s;if(s=f(),ji){Kt(!0);try{f()}finally{Kt(!1)}}}return o.memoizedState=o.baseState=s,o.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:s},o}function _y(s,o,f,g){return s.baseState=f,Wh(s,At,typeof g=="function"?g:as)}function wE(s,o,f,g,k){if(Rc(s))throw Error(r(485));if(s=o.action,s!==null){var A={payload:k,action:s,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(F){A.listeners.push(F)}};G.T!==null?f(!0):A.isTransition=!1,g(A),f=o.pending,f===null?(A.next=o.pending=A,Sy(o,A)):(A.next=f.next,o.pending=f.next=A)}}function Sy(s,o){var f=o.action,g=o.payload,k=s.state;if(o.isTransition){var A=G.T,F={};G.T=F;try{var Y=f(k,g),ie=G.S;ie!==null&&ie(F,Y),wy(s,o,Y)}catch(ge){Yh(s,o,ge)}finally{A!==null&&F.types!==null&&(A.types=F.types),G.T=A}}else try{A=f(k,g),wy(s,o,A)}catch(ge){Yh(s,o,ge)}}function wy(s,o,f){f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(function(g){Cy(s,o,g)},function(g){return Yh(s,o,g)}):Cy(s,o,f)}function Cy(s,o,f){o.status="fulfilled",o.value=f,ky(o),s.state=f,o=s.pending,o!==null&&(f=o.next,f===o?s.pending=null:(f=f.next,o.next=f,Sy(s,f)))}function Yh(s,o,f){var g=s.pending;if(s.pending=null,g!==null){g=g.next;do o.status="rejected",o.reason=f,ky(o),o=o.next;while(o!==g)}s.action=null}function ky(s){s=s.listeners;for(var o=0;o<s.length;o++)(0,s[o])()}function Ey(s,o){return o}function jy(s,o){if(vt){var f=Mt.formState;if(f!==null){e:{var g=at;if(vt){if(Vt){t:{for(var k=Vt,A=xr;k.nodeType!==8;){if(!A){k=null;break t}if(k=br(k.nextSibling),k===null){k=null;break t}}A=k.data,k=A==="F!"||A==="F"?k:null}if(k){Vt=br(k.nextSibling),g=k.data==="F!";break e}}Ds(g)}g=!1}g&&(o=f[0])}}return f=Bn(),f.memoizedState=f.baseState=o,g={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ey,lastRenderedState:o},f.queue=g,f=Wy.bind(null,at,g),g.dispatch=f,g=Kh(!1),A=tf.bind(null,at,!1,g.queue),g=Bn(),k={state:o,dispatch:null,action:s,pending:null},g.queue=k,f=wE.bind(null,at,k,A,f),k.dispatch=f,g.memoizedState=s,[o,f,!1]}function Ny(s){var o=tn();return Ty(o,At,s)}function Ty(s,o,f){if(o=Wh(s,o,Ey)[0],s=Ac(as)[0],typeof o=="object"&&o!==null&&typeof o.then=="function")try{var g=Po(o)}catch(F){throw F===va?vc:F}else g=o;o=tn();var k=o.queue,A=k.dispatch;return f!==o.memoizedState&&(at.flags|=2048,ka(9,{destroy:void 0},CE.bind(null,k,f),null)),[g,A,s]}function CE(s,o){s.action=o}function Ay(s){var o=tn(),f=At;if(f!==null)return Ty(o,f,s);tn(),o=o.memoizedState,f=tn();var g=f.queue.dispatch;return f.memoizedState=s,[o,g,!1]}function ka(s,o,f,g){return s={tag:s,create:f,deps:g,inst:o,next:null},o=at.updateQueue,o===null&&(o=Nc(),at.updateQueue=o),f=o.lastEffect,f===null?o.lastEffect=s.next=s:(g=f.next,f.next=s,s.next=g,o.lastEffect=s),s}function Ly(){return tn().memoizedState}function Lc(s,o,f,g){var k=Bn();at.flags|=s,k.memoizedState=ka(1|o,{destroy:void 0},f,g===void 0?null:g)}function Dc(s,o,f,g){var k=tn();g=g===void 0?null:g;var A=k.memoizedState.inst;At!==null&&g!==null&&zh(g,At.memoizedState.deps)?k.memoizedState=ka(o,A,f,g):(at.flags|=s,k.memoizedState=ka(1|o,A,f,g))}function Dy(s,o){Lc(8390656,8,s,o)}function Xh(s,o){Dc(2048,8,s,o)}function kE(s){at.flags|=4;var o=at.updateQueue;if(o===null)o=Nc(),at.updateQueue=o,o.events=[s];else{var f=o.events;f===null?o.events=[s]:f.push(s)}}function Ry(s){var o=tn().memoizedState;return kE({ref:o,nextImpl:s}),function(){if((Et&2)!==0)throw Error(r(440));return o.impl.apply(void 0,arguments)}}function Oy(s,o){return Dc(4,2,s,o)}function Iy(s,o){return Dc(4,4,s,o)}function My(s,o){if(typeof o=="function"){s=s();var f=o(s);return function(){typeof f=="function"?f():o(null)}}if(o!=null)return s=s(),o.current=s,function(){o.current=null}}function Py(s,o,f){f=f!=null?f.concat([s]):null,Dc(4,4,My.bind(null,o,s),f)}function Qh(){}function By(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;return o!==null&&zh(o,g[1])?g[0]:(f.memoizedState=[s,o],s)}function $y(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;if(o!==null&&zh(o,g[1]))return g[0];if(g=s(),ji){Kt(!0);try{s()}finally{Kt(!1)}}return f.memoizedState=[g,o],g}function Jh(s,o,f){return f===void 0||(is&1073741824)!==0&&(yt&261930)===0?s.memoizedState=o:(s.memoizedState=f,s=zb(),at.lanes|=s,Hs|=s,f)}function zy(s,o,f,g){return tr(f,o)?f:Sa.current!==null?(s=Jh(s,f,g),tr(s,o)||(cn=!0),s):(is&42)===0||(is&1073741824)!==0&&(yt&261930)===0?(cn=!0,s.memoizedState=f):(s=zb(),at.lanes|=s,Hs|=s,o)}function Hy(s,o,f,g,k){var A=Z.p;Z.p=A!==0&&8>A?A:8;var F=G.T,Y={};G.T=Y,tf(s,!1,o,f);try{var ie=k(),ge=G.S;if(ge!==null&&ge(Y,ie),ie!==null&&typeof ie=="object"&&typeof ie.then=="function"){var ke=vE(ie,g);Bo(s,o,ke,or(s))}else Bo(s,o,g,or(s))}catch(Ae){Bo(s,o,{then:function(){},status:"rejected",reason:Ae},or())}finally{Z.p=A,F!==null&&Y.types!==null&&(F.types=Y.types),G.T=F}}function EE(){}function Zh(s,o,f,g){if(s.tag!==5)throw Error(r(476));var k=Uy(s).queue;Hy(s,k,o,X,f===null?EE:function(){return Fy(s),f(g)})}function Uy(s){var o=s.memoizedState;if(o!==null)return o;o={memoizedState:X,baseState:X,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:X},next:null};var f={};return o.next={memoizedState:f,baseState:f,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:f},next:null},s.memoizedState=o,s=s.alternate,s!==null&&(s.memoizedState=o),o}function Fy(s){var o=Uy(s);o.next===null&&(o=s.alternate.memoizedState),Bo(s,o.next.queue,{},or())}function ef(){return jn(tl)}function Vy(){return tn().memoizedState}function Gy(){return tn().memoizedState}function jE(s){for(var o=s.return;o!==null;){switch(o.tag){case 24:case 3:var f=or();s=Is(f);var g=Ms(o,s,f);g!==null&&(Yn(g,o,f),Ro(g,o,f)),o={cache:Th()},s.payload=o;return}o=o.return}}function NE(s,o,f){var g=or();f={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null},Rc(s)?qy(o,f):(f=yh(s,o,f,g),f!==null&&(Yn(f,s,g),Ky(f,o,g)))}function Wy(s,o,f){var g=or();Bo(s,o,f,g)}function Bo(s,o,f,g){var k={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null};if(Rc(s))qy(o,k);else{var A=s.alternate;if(s.lanes===0&&(A===null||A.lanes===0)&&(A=o.lastRenderedReducer,A!==null))try{var F=o.lastRenderedState,Y=A(F,f);if(k.hasEagerState=!0,k.eagerState=Y,tr(Y,F))return fc(s,o,k,0),Mt===null&&hc(),!1}catch{}finally{}if(f=yh(s,o,k,g),f!==null)return Yn(f,s,g),Ky(f,o,g),!0}return!1}function tf(s,o,f,g){if(g={lane:2,revertLane:Of(),gesture:null,action:g,hasEagerState:!1,eagerState:null,next:null},Rc(s)){if(o)throw Error(r(479))}else o=yh(s,f,g,2),o!==null&&Yn(o,s,2)}function Rc(s){var o=s.alternate;return s===at||o!==null&&o===at}function qy(s,o){wa=Ec=!0;var f=s.pending;f===null?o.next=o:(o.next=f.next,f.next=o),s.pending=o}function Ky(s,o,f){if((f&4194048)!==0){var g=o.lanes;g&=s.pendingLanes,f|=g,o.lanes=f,Ye(s,f)}}var $o={readContext:jn,use:Tc,useCallback:Yt,useContext:Yt,useEffect:Yt,useImperativeHandle:Yt,useLayoutEffect:Yt,useInsertionEffect:Yt,useMemo:Yt,useReducer:Yt,useRef:Yt,useState:Yt,useDebugValue:Yt,useDeferredValue:Yt,useTransition:Yt,useSyncExternalStore:Yt,useId:Yt,useHostTransitionStatus:Yt,useFormState:Yt,useActionState:Yt,useOptimistic:Yt,useMemoCache:Yt,useCacheRefresh:Yt};$o.useEffectEvent=Yt;var Yy={readContext:jn,use:Tc,useCallback:function(s,o){return Bn().memoizedState=[s,o===void 0?null:o],s},useContext:jn,useEffect:Dy,useImperativeHandle:function(s,o,f){f=f!=null?f.concat([s]):null,Lc(4194308,4,My.bind(null,o,s),f)},useLayoutEffect:function(s,o){return Lc(4194308,4,s,o)},useInsertionEffect:function(s,o){Lc(4,2,s,o)},useMemo:function(s,o){var f=Bn();o=o===void 0?null:o;var g=s();if(ji){Kt(!0);try{s()}finally{Kt(!1)}}return f.memoizedState=[g,o],g},useReducer:function(s,o,f){var g=Bn();if(f!==void 0){var k=f(o);if(ji){Kt(!0);try{f(o)}finally{Kt(!1)}}}else k=o;return g.memoizedState=g.baseState=k,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:k},g.queue=s,s=s.dispatch=NE.bind(null,at,s),[g.memoizedState,s]},useRef:function(s){var o=Bn();return s={current:s},o.memoizedState=s},useState:function(s){s=Kh(s);var o=s.queue,f=Wy.bind(null,at,o);return o.dispatch=f,[s.memoizedState,f]},useDebugValue:Qh,useDeferredValue:function(s,o){var f=Bn();return Jh(f,s,o)},useTransition:function(){var s=Kh(!1);return s=Hy.bind(null,at,s.queue,!0,!1),Bn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,o,f){var g=at,k=Bn();if(vt){if(f===void 0)throw Error(r(407));f=f()}else{if(f=o(),Mt===null)throw Error(r(349));(yt&127)!==0||gy(g,o,f)}k.memoizedState=f;var A={value:f,getSnapshot:o};return k.queue=A,Dy(yy.bind(null,g,A,s),[s]),g.flags|=2048,ka(9,{destroy:void 0},xy.bind(null,g,A,f,o),null),f},useId:function(){var s=Bn(),o=Mt.identifierPrefix;if(vt){var f=zr,g=$r;f=(g&~(1<<32-dt(g)-1)).toString(32)+f,o="_"+o+"R_"+f,f=jc++,0<f&&(o+="H"+f.toString(32)),o+="_"}else f=_E++,o="_"+o+"r_"+f.toString(32)+"_";return s.memoizedState=o},useHostTransitionStatus:ef,useFormState:jy,useActionState:jy,useOptimistic:function(s){var o=Bn();o.memoizedState=o.baseState=s;var f={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return o.queue=f,o=tf.bind(null,at,!0,f),f.dispatch=o,[s,o]},useMemoCache:Gh,useCacheRefresh:function(){return Bn().memoizedState=jE.bind(null,at)},useEffectEvent:function(s){var o=Bn(),f={impl:s};return o.memoizedState=f,function(){if((Et&2)!==0)throw Error(r(440));return f.impl.apply(void 0,arguments)}}},nf={readContext:jn,use:Tc,useCallback:By,useContext:jn,useEffect:Xh,useImperativeHandle:Py,useInsertionEffect:Oy,useLayoutEffect:Iy,useMemo:$y,useReducer:Ac,useRef:Ly,useState:function(){return Ac(as)},useDebugValue:Qh,useDeferredValue:function(s,o){var f=tn();return zy(f,At.memoizedState,s,o)},useTransition:function(){var s=Ac(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:Po(s),o]},useSyncExternalStore:py,useId:Vy,useHostTransitionStatus:ef,useFormState:Ny,useActionState:Ny,useOptimistic:function(s,o){var f=tn();return _y(f,At,s,o)},useMemoCache:Gh,useCacheRefresh:Gy};nf.useEffectEvent=Ry;var Xy={readContext:jn,use:Tc,useCallback:By,useContext:jn,useEffect:Xh,useImperativeHandle:Py,useInsertionEffect:Oy,useLayoutEffect:Iy,useMemo:$y,useReducer:qh,useRef:Ly,useState:function(){return qh(as)},useDebugValue:Qh,useDeferredValue:function(s,o){var f=tn();return At===null?Jh(f,s,o):zy(f,At.memoizedState,s,o)},useTransition:function(){var s=qh(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:Po(s),o]},useSyncExternalStore:py,useId:Vy,useHostTransitionStatus:ef,useFormState:Ay,useActionState:Ay,useOptimistic:function(s,o){var f=tn();return At!==null?_y(f,At,s,o):(f.baseState=s,[s,f.queue.dispatch])},useMemoCache:Gh,useCacheRefresh:Gy};Xy.useEffectEvent=Ry;function rf(s,o,f,g){o=s.memoizedState,f=f(g,o),f=f==null?o:m({},o,f),s.memoizedState=f,s.lanes===0&&(s.updateQueue.baseState=f)}var sf={enqueueSetState:function(s,o,f){s=s._reactInternals;var g=or(),k=Is(g);k.payload=o,f!=null&&(k.callback=f),o=Ms(s,k,g),o!==null&&(Yn(o,s,g),Ro(o,s,g))},enqueueReplaceState:function(s,o,f){s=s._reactInternals;var g=or(),k=Is(g);k.tag=1,k.payload=o,f!=null&&(k.callback=f),o=Ms(s,k,g),o!==null&&(Yn(o,s,g),Ro(o,s,g))},enqueueForceUpdate:function(s,o){s=s._reactInternals;var f=or(),g=Is(f);g.tag=2,o!=null&&(g.callback=o),o=Ms(s,g,f),o!==null&&(Yn(o,s,f),Ro(o,s,f))}};function Qy(s,o,f,g,k,A,F){return s=s.stateNode,typeof s.shouldComponentUpdate=="function"?s.shouldComponentUpdate(g,A,F):o.prototype&&o.prototype.isPureReactComponent?!ko(f,g)||!ko(k,A):!0}function Jy(s,o,f,g){s=o.state,typeof o.componentWillReceiveProps=="function"&&o.componentWillReceiveProps(f,g),typeof o.UNSAFE_componentWillReceiveProps=="function"&&o.UNSAFE_componentWillReceiveProps(f,g),o.state!==s&&sf.enqueueReplaceState(o,o.state,null)}function Ni(s,o){var f=o;if("ref"in o){f={};for(var g in o)g!=="ref"&&(f[g]=o[g])}if(s=s.defaultProps){f===o&&(f=m({},f));for(var k in s)f[k]===void 0&&(f[k]=s[k])}return f}function Zy(s){dc(s)}function eb(s){console.error(s)}function tb(s){dc(s)}function Oc(s,o){try{var f=s.onUncaughtError;f(o.value,{componentStack:o.stack})}catch(g){setTimeout(function(){throw g})}}function nb(s,o,f){try{var g=s.onCaughtError;g(f.value,{componentStack:f.stack,errorBoundary:o.tag===1?o.stateNode:null})}catch(k){setTimeout(function(){throw k})}}function af(s,o,f){return f=Is(f),f.tag=3,f.payload={element:null},f.callback=function(){Oc(s,o)},f}function rb(s){return s=Is(s),s.tag=3,s}function sb(s,o,f,g){var k=f.type.getDerivedStateFromError;if(typeof k=="function"){var A=g.value;s.payload=function(){return k(A)},s.callback=function(){nb(o,f,g)}}var F=f.stateNode;F!==null&&typeof F.componentDidCatch=="function"&&(s.callback=function(){nb(o,f,g),typeof k!="function"&&(Us===null?Us=new Set([this]):Us.add(this));var Y=g.stack;this.componentDidCatch(g.value,{componentStack:Y!==null?Y:""})})}function TE(s,o,f,g,k){if(f.flags|=32768,g!==null&&typeof g=="object"&&typeof g.then=="function"){if(o=f.alternate,o!==null&&xa(o,f,k,!0),f=rr.current,f!==null){switch(f.tag){case 31:case 13:return yr===null?Wc():f.alternate===null&&Xt===0&&(Xt=3),f.flags&=-257,f.flags|=65536,f.lanes=k,g===_c?f.flags|=16384:(o=f.updateQueue,o===null?f.updateQueue=new Set([g]):o.add(g),Lf(s,g,k)),!1;case 22:return f.flags|=65536,g===_c?f.flags|=16384:(o=f.updateQueue,o===null?(o={transitions:null,markerInstances:null,retryQueue:new Set([g])},f.updateQueue=o):(f=o.retryQueue,f===null?o.retryQueue=new Set([g]):f.add(g)),Lf(s,g,k)),!1}throw Error(r(435,f.tag))}return Lf(s,g,k),Wc(),!1}if(vt)return o=rr.current,o!==null?((o.flags&65536)===0&&(o.flags|=256),o.flags|=65536,o.lanes=k,g!==Ch&&(s=Error(r(422),{cause:g}),No(mr(s,f)))):(g!==Ch&&(o=Error(r(423),{cause:g}),No(mr(o,f))),s=s.current.alternate,s.flags|=65536,k&=-k,s.lanes|=k,g=mr(g,f),k=af(s.stateNode,g,k),Ih(s,k),Xt!==4&&(Xt=2)),!1;var A=Error(r(520),{cause:g});if(A=mr(A,f),qo===null?qo=[A]:qo.push(A),Xt!==4&&(Xt=2),o===null)return!0;g=mr(g,f),f=o;do{switch(f.tag){case 3:return f.flags|=65536,s=k&-k,f.lanes|=s,s=af(f.stateNode,g,s),Ih(f,s),!1;case 1:if(o=f.type,A=f.stateNode,(f.flags&128)===0&&(typeof o.getDerivedStateFromError=="function"||A!==null&&typeof A.componentDidCatch=="function"&&(Us===null||!Us.has(A))))return f.flags|=65536,k&=-k,f.lanes|=k,k=rb(k),sb(k,s,f,g),Ih(f,k),!1}f=f.return}while(f!==null);return!1}var of=Error(r(461)),cn=!1;function Nn(s,o,f,g){o.child=s===null?ly(o,null,f,g):Ei(o,s.child,f,g)}function ib(s,o,f,g,k){f=f.render;var A=o.ref;if("ref"in g){var F={};for(var Y in g)Y!=="ref"&&(F[Y]=g[Y])}else F=g;return Si(o),g=Hh(s,o,f,F,A,k),Y=Uh(),s!==null&&!cn?(Fh(s,o,k),os(s,o,k)):(vt&&Y&&Sh(o),o.flags|=1,Nn(s,o,g,k),o.child)}function ab(s,o,f,g,k){if(s===null){var A=f.type;return typeof A=="function"&&!bh(A)&&A.defaultProps===void 0&&f.compare===null?(o.tag=15,o.type=A,ob(s,o,A,g,k)):(s=pc(f.type,null,g,o,o.mode,k),s.ref=o.ref,s.return=o,o.child=s)}if(A=s.child,!pf(s,k)){var F=A.memoizedProps;if(f=f.compare,f=f!==null?f:ko,f(F,g)&&s.ref===o.ref)return os(s,o,k)}return o.flags|=1,s=ts(A,g),s.ref=o.ref,s.return=o,o.child=s}function ob(s,o,f,g,k){if(s!==null){var A=s.memoizedProps;if(ko(A,g)&&s.ref===o.ref)if(cn=!1,o.pendingProps=g=A,pf(s,k))(s.flags&131072)!==0&&(cn=!0);else return o.lanes=s.lanes,os(s,o,k)}return lf(s,o,f,g,k)}function lb(s,o,f,g){var k=g.children,A=s!==null?s.memoizedState:null;if(s===null&&o.stateNode===null&&(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),g.mode==="hidden"){if((o.flags&128)!==0){if(A=A!==null?A.baseLanes|f:f,s!==null){for(g=o.child=s.child,k=0;g!==null;)k=k|g.lanes|g.childLanes,g=g.sibling;g=k&~A}else g=0,o.child=null;return cb(s,o,A,f,g)}if((f&536870912)!==0)o.memoizedState={baseLanes:0,cachePool:null},s!==null&&bc(o,A!==null?A.cachePool:null),A!==null?dy(o,A):Ph(),hy(o);else return g=o.lanes=536870912,cb(s,o,A!==null?A.baseLanes|f:f,f,g)}else A!==null?(bc(o,A.cachePool),dy(o,A),Bs(),o.memoizedState=null):(s!==null&&bc(o,null),Ph(),Bs());return Nn(s,o,k,f),o.child}function zo(s,o){return s!==null&&s.tag===22||o.stateNode!==null||(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.sibling}function cb(s,o,f,g,k){var A=Lh();return A=A===null?null:{parent:on._currentValue,pool:A},o.memoizedState={baseLanes:f,cachePool:A},s!==null&&bc(o,null),Ph(),hy(o),s!==null&&xa(s,o,g,!0),o.childLanes=k,null}function Ic(s,o){return o=Pc({mode:o.mode,children:o.children},s.mode),o.ref=s.ref,s.child=o,o.return=s,o}function ub(s,o,f){return Ei(o,s.child,null,f),s=Ic(o,o.pendingProps),s.flags|=2,sr(o),o.memoizedState=null,s}function AE(s,o,f){var g=o.pendingProps,k=(o.flags&128)!==0;if(o.flags&=-129,s===null){if(vt){if(g.mode==="hidden")return s=Ic(o,g),o.lanes=536870912,zo(null,s);if($h(o),(s=Vt)?(s=Sv(s,xr),s=s!==null&&s.data==="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:As!==null?{id:$r,overflow:zr}:null,retryLane:536870912,hydrationErrors:null},f=qx(s),f.return=o,o.child=f,En=o,Vt=null)):s=null,s===null)throw Ds(o);return o.lanes=536870912,null}return Ic(o,g)}var A=s.memoizedState;if(A!==null){var F=A.dehydrated;if($h(o),k)if(o.flags&256)o.flags&=-257,o=ub(s,o,f);else if(o.memoizedState!==null)o.child=s.child,o.flags|=128,o=null;else throw Error(r(558));else if(cn||xa(s,o,f,!1),k=(f&s.childLanes)!==0,cn||k){if(g=Mt,g!==null&&(F=ot(g,f),F!==0&&F!==A.retryLane))throw A.retryLane=F,yi(s,F),Yn(g,s,F),of;Wc(),o=ub(s,o,f)}else s=A.treeContext,Vt=br(F.nextSibling),En=o,vt=!0,Ls=null,xr=!1,s!==null&&Xx(o,s),o=Ic(o,g),o.flags|=4096;return o}return s=ts(s.child,{mode:g.mode,children:g.children}),s.ref=o.ref,o.child=s,s.return=o,s}function Mc(s,o){var f=o.ref;if(f===null)s!==null&&s.ref!==null&&(o.flags|=4194816);else{if(typeof f!="function"&&typeof f!="object")throw Error(r(284));(s===null||s.ref!==f)&&(o.flags|=4194816)}}function lf(s,o,f,g,k){return Si(o),f=Hh(s,o,f,g,void 0,k),g=Uh(),s!==null&&!cn?(Fh(s,o,k),os(s,o,k)):(vt&&g&&Sh(o),o.flags|=1,Nn(s,o,f,k),o.child)}function db(s,o,f,g,k,A){return Si(o),o.updateQueue=null,f=my(o,g,f,k),fy(s),g=Uh(),s!==null&&!cn?(Fh(s,o,A),os(s,o,A)):(vt&&g&&Sh(o),o.flags|=1,Nn(s,o,f,A),o.child)}function hb(s,o,f,g,k){if(Si(o),o.stateNode===null){var A=fa,F=f.contextType;typeof F=="object"&&F!==null&&(A=jn(F)),A=new f(g,A),o.memoizedState=A.state!==null&&A.state!==void 0?A.state:null,A.updater=sf,o.stateNode=A,A._reactInternals=o,A=o.stateNode,A.props=g,A.state=o.memoizedState,A.refs={},Rh(o),F=f.contextType,A.context=typeof F=="object"&&F!==null?jn(F):fa,A.state=o.memoizedState,F=f.getDerivedStateFromProps,typeof F=="function"&&(rf(o,f,F,g),A.state=o.memoizedState),typeof f.getDerivedStateFromProps=="function"||typeof A.getSnapshotBeforeUpdate=="function"||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(F=A.state,typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount(),F!==A.state&&sf.enqueueReplaceState(A,A.state,null),Io(o,g,A,k),Oo(),A.state=o.memoizedState),typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!0}else if(s===null){A=o.stateNode;var Y=o.memoizedProps,ie=Ni(f,Y);A.props=ie;var ge=A.context,ke=f.contextType;F=fa,typeof ke=="object"&&ke!==null&&(F=jn(ke));var Ae=f.getDerivedStateFromProps;ke=typeof Ae=="function"||typeof A.getSnapshotBeforeUpdate=="function",Y=o.pendingProps!==Y,ke||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(Y||ge!==F)&&Jy(o,A,g,F),Os=!1;var ye=o.memoizedState;A.state=ye,Io(o,g,A,k),Oo(),ge=o.memoizedState,Y||ye!==ge||Os?(typeof Ae=="function"&&(rf(o,f,Ae,g),ge=o.memoizedState),(ie=Os||Qy(o,f,ie,g,ye,ge,F))?(ke||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount()),typeof A.componentDidMount=="function"&&(o.flags|=4194308)):(typeof A.componentDidMount=="function"&&(o.flags|=4194308),o.memoizedProps=g,o.memoizedState=ge),A.props=g,A.state=ge,A.context=F,g=ie):(typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!1)}else{A=o.stateNode,Oh(s,o),F=o.memoizedProps,ke=Ni(f,F),A.props=ke,Ae=o.pendingProps,ye=A.context,ge=f.contextType,ie=fa,typeof ge=="object"&&ge!==null&&(ie=jn(ge)),Y=f.getDerivedStateFromProps,(ge=typeof Y=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(F!==Ae||ye!==ie)&&Jy(o,A,g,ie),Os=!1,ye=o.memoizedState,A.state=ye,Io(o,g,A,k),Oo();var be=o.memoizedState;F!==Ae||ye!==be||Os||s!==null&&s.dependencies!==null&&xc(s.dependencies)?(typeof Y=="function"&&(rf(o,f,Y,g),be=o.memoizedState),(ke=Os||Qy(o,f,ke,g,ye,be,ie)||s!==null&&s.dependencies!==null&&xc(s.dependencies))?(ge||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(g,be,ie),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(g,be,ie)),typeof A.componentDidUpdate=="function"&&(o.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(o.flags|=1024)):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=1024),o.memoizedProps=g,o.memoizedState=be),A.props=g,A.state=be,A.context=ie,g=ke):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=1024),g=!1)}return A=g,Mc(s,o),g=(o.flags&128)!==0,A||g?(A=o.stateNode,f=g&&typeof f.getDerivedStateFromError!="function"?null:A.render(),o.flags|=1,s!==null&&g?(o.child=Ei(o,s.child,null,k),o.child=Ei(o,null,f,k)):Nn(s,o,f,k),o.memoizedState=A.state,s=o.child):s=os(s,o,k),s}function fb(s,o,f,g){return vi(),o.flags|=256,Nn(s,o,f,g),o.child}var cf={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function uf(s){return{baseLanes:s,cachePool:ny()}}function df(s,o,f){return s=s!==null?s.childLanes&~f:0,o&&(s|=ar),s}function mb(s,o,f){var g=o.pendingProps,k=!1,A=(o.flags&128)!==0,F;if((F=A)||(F=s!==null&&s.memoizedState===null?!1:(en.current&2)!==0),F&&(k=!0,o.flags&=-129),F=(o.flags&32)!==0,o.flags&=-33,s===null){if(vt){if(k?Ps(o):Bs(),(s=Vt)?(s=Sv(s,xr),s=s!==null&&s.data!=="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:As!==null?{id:$r,overflow:zr}:null,retryLane:536870912,hydrationErrors:null},f=qx(s),f.return=o,o.child=f,En=o,Vt=null)):s=null,s===null)throw Ds(o);return qf(s)?o.lanes=32:o.lanes=536870912,null}var Y=g.children;return g=g.fallback,k?(Bs(),k=o.mode,Y=Pc({mode:"hidden",children:Y},k),g=bi(g,k,f,null),Y.return=o,g.return=o,Y.sibling=g,o.child=Y,g=o.child,g.memoizedState=uf(f),g.childLanes=df(s,F,f),o.memoizedState=cf,zo(null,g)):(Ps(o),hf(o,Y))}var ie=s.memoizedState;if(ie!==null&&(Y=ie.dehydrated,Y!==null)){if(A)o.flags&256?(Ps(o),o.flags&=-257,o=ff(s,o,f)):o.memoizedState!==null?(Bs(),o.child=s.child,o.flags|=128,o=null):(Bs(),Y=g.fallback,k=o.mode,g=Pc({mode:"visible",children:g.children},k),Y=bi(Y,k,f,null),Y.flags|=2,g.return=o,Y.return=o,g.sibling=Y,o.child=g,Ei(o,s.child,null,f),g=o.child,g.memoizedState=uf(f),g.childLanes=df(s,F,f),o.memoizedState=cf,o=zo(null,g));else if(Ps(o),qf(Y)){if(F=Y.nextSibling&&Y.nextSibling.dataset,F)var ge=F.dgst;F=ge,g=Error(r(419)),g.stack="",g.digest=F,No({value:g,source:null,stack:null}),o=ff(s,o,f)}else if(cn||xa(s,o,f,!1),F=(f&s.childLanes)!==0,cn||F){if(F=Mt,F!==null&&(g=ot(F,f),g!==0&&g!==ie.retryLane))throw ie.retryLane=g,yi(s,g),Yn(F,s,g),of;Wf(Y)||Wc(),o=ff(s,o,f)}else Wf(Y)?(o.flags|=192,o.child=s.child,o=null):(s=ie.treeContext,Vt=br(Y.nextSibling),En=o,vt=!0,Ls=null,xr=!1,s!==null&&Xx(o,s),o=hf(o,g.children),o.flags|=4096);return o}return k?(Bs(),Y=g.fallback,k=o.mode,ie=s.child,ge=ie.sibling,g=ts(ie,{mode:"hidden",children:g.children}),g.subtreeFlags=ie.subtreeFlags&65011712,ge!==null?Y=ts(ge,Y):(Y=bi(Y,k,f,null),Y.flags|=2),Y.return=o,g.return=o,g.sibling=Y,o.child=g,zo(null,g),g=o.child,Y=s.child.memoizedState,Y===null?Y=uf(f):(k=Y.cachePool,k!==null?(ie=on._currentValue,k=k.parent!==ie?{parent:ie,pool:ie}:k):k=ny(),Y={baseLanes:Y.baseLanes|f,cachePool:k}),g.memoizedState=Y,g.childLanes=df(s,F,f),o.memoizedState=cf,zo(s.child,g)):(Ps(o),f=s.child,s=f.sibling,f=ts(f,{mode:"visible",children:g.children}),f.return=o,f.sibling=null,s!==null&&(F=o.deletions,F===null?(o.deletions=[s],o.flags|=16):F.push(s)),o.child=f,o.memoizedState=null,f)}function hf(s,o){return o=Pc({mode:"visible",children:o},s.mode),o.return=s,s.child=o}function Pc(s,o){return s=nr(22,s,null,o),s.lanes=0,s}function ff(s,o,f){return Ei(o,s.child,null,f),s=hf(o,o.pendingProps.children),s.flags|=2,o.memoizedState=null,s}function pb(s,o,f){s.lanes|=o;var g=s.alternate;g!==null&&(g.lanes|=o),jh(s.return,o,f)}function mf(s,o,f,g,k,A){var F=s.memoizedState;F===null?s.memoizedState={isBackwards:o,rendering:null,renderingStartTime:0,last:g,tail:f,tailMode:k,treeForkCount:A}:(F.isBackwards=o,F.rendering=null,F.renderingStartTime=0,F.last=g,F.tail=f,F.tailMode=k,F.treeForkCount=A)}function gb(s,o,f){var g=o.pendingProps,k=g.revealOrder,A=g.tail;g=g.children;var F=en.current,Y=(F&2)!==0;if(Y?(F=F&1|2,o.flags|=128):F&=1,z(en,F),Nn(s,o,g,f),g=vt?jo:0,!Y&&s!==null&&(s.flags&128)!==0)e:for(s=o.child;s!==null;){if(s.tag===13)s.memoizedState!==null&&pb(s,f,o);else if(s.tag===19)pb(s,f,o);else if(s.child!==null){s.child.return=s,s=s.child;continue}if(s===o)break e;for(;s.sibling===null;){if(s.return===null||s.return===o)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}switch(k){case"forwards":for(f=o.child,k=null;f!==null;)s=f.alternate,s!==null&&kc(s)===null&&(k=f),f=f.sibling;f=k,f===null?(k=o.child,o.child=null):(k=f.sibling,f.sibling=null),mf(o,!1,k,f,A,g);break;case"backwards":case"unstable_legacy-backwards":for(f=null,k=o.child,o.child=null;k!==null;){if(s=k.alternate,s!==null&&kc(s)===null){o.child=k;break}s=k.sibling,k.sibling=f,f=k,k=s}mf(o,!0,f,null,A,g);break;case"together":mf(o,!1,null,null,void 0,g);break;default:o.memoizedState=null}return o.child}function os(s,o,f){if(s!==null&&(o.dependencies=s.dependencies),Hs|=o.lanes,(f&o.childLanes)===0)if(s!==null){if(xa(s,o,f,!1),(f&o.childLanes)===0)return null}else return null;if(s!==null&&o.child!==s.child)throw Error(r(153));if(o.child!==null){for(s=o.child,f=ts(s,s.pendingProps),o.child=f,f.return=o;s.sibling!==null;)s=s.sibling,f=f.sibling=ts(s,s.pendingProps),f.return=o;f.sibling=null}return o.child}function pf(s,o){return(s.lanes&o)!==0?!0:(s=s.dependencies,!!(s!==null&&xc(s)))}function LE(s,o,f){switch(o.tag){case 3:B(o,o.stateNode.containerInfo),Rs(o,on,s.memoizedState.cache),vi();break;case 27:case 5:se(o);break;case 4:B(o,o.stateNode.containerInfo);break;case 10:Rs(o,o.type,o.memoizedProps.value);break;case 31:if(o.memoizedState!==null)return o.flags|=128,$h(o),null;break;case 13:var g=o.memoizedState;if(g!==null)return g.dehydrated!==null?(Ps(o),o.flags|=128,null):(f&o.child.childLanes)!==0?mb(s,o,f):(Ps(o),s=os(s,o,f),s!==null?s.sibling:null);Ps(o);break;case 19:var k=(s.flags&128)!==0;if(g=(f&o.childLanes)!==0,g||(xa(s,o,f,!1),g=(f&o.childLanes)!==0),k){if(g)return gb(s,o,f);o.flags|=128}if(k=o.memoizedState,k!==null&&(k.rendering=null,k.tail=null,k.lastEffect=null),z(en,en.current),g)break;return null;case 22:return o.lanes=0,lb(s,o,f,o.pendingProps);case 24:Rs(o,on,s.memoizedState.cache)}return os(s,o,f)}function xb(s,o,f){if(s!==null)if(s.memoizedProps!==o.pendingProps)cn=!0;else{if(!pf(s,f)&&(o.flags&128)===0)return cn=!1,LE(s,o,f);cn=(s.flags&131072)!==0}else cn=!1,vt&&(o.flags&1048576)!==0&&Yx(o,jo,o.index);switch(o.lanes=0,o.tag){case 16:e:{var g=o.pendingProps;if(s=Ci(o.elementType),o.type=s,typeof s=="function")bh(s)?(g=Ni(s,g),o.tag=1,o=hb(null,o,s,g,f)):(o.tag=0,o=lf(null,o,s,g,f));else{if(s!=null){var k=s.$$typeof;if(k===E){o.tag=11,o=ib(null,o,s,g,f);break e}else if(k===D){o.tag=14,o=ab(null,o,s,g,f);break e}}throw o=U(s)||s,Error(r(306,o,""))}}return o;case 0:return lf(s,o,o.type,o.pendingProps,f);case 1:return g=o.type,k=Ni(g,o.pendingProps),hb(s,o,g,k,f);case 3:e:{if(B(o,o.stateNode.containerInfo),s===null)throw Error(r(387));g=o.pendingProps;var A=o.memoizedState;k=A.element,Oh(s,o),Io(o,g,null,f);var F=o.memoizedState;if(g=F.cache,Rs(o,on,g),g!==A.cache&&Nh(o,[on],f,!0),Oo(),g=F.element,A.isDehydrated)if(A={element:g,isDehydrated:!1,cache:F.cache},o.updateQueue.baseState=A,o.memoizedState=A,o.flags&256){o=fb(s,o,g,f);break e}else if(g!==k){k=mr(Error(r(424)),o),No(k),o=fb(s,o,g,f);break e}else{switch(s=o.stateNode.containerInfo,s.nodeType){case 9:s=s.body;break;default:s=s.nodeName==="HTML"?s.ownerDocument.body:s}for(Vt=br(s.firstChild),En=o,vt=!0,Ls=null,xr=!0,f=ly(o,null,g,f),o.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling}else{if(vi(),g===k){o=os(s,o,f);break e}Nn(s,o,g,f)}o=o.child}return o;case 26:return Mc(s,o),s===null?(f=Nv(o.type,null,o.pendingProps,null))?o.memoizedState=f:vt||(f=o.type,s=o.pendingProps,g=Zc(ne.current).createElement(f),g[an]=o,g[Fn]=s,Tn(g,f,s),_n(g),o.stateNode=g):o.memoizedState=Nv(o.type,s.memoizedProps,o.pendingProps,s.memoizedState),null;case 27:return se(o),s===null&&vt&&(g=o.stateNode=kv(o.type,o.pendingProps,ne.current),En=o,xr=!0,k=Vt,Ws(o.type)?(Kf=k,Vt=br(g.firstChild)):Vt=k),Nn(s,o,o.pendingProps.children,f),Mc(s,o),s===null&&(o.flags|=4194304),o.child;case 5:return s===null&&vt&&((k=g=Vt)&&(g=oj(g,o.type,o.pendingProps,xr),g!==null?(o.stateNode=g,En=o,Vt=br(g.firstChild),xr=!1,k=!0):k=!1),k||Ds(o)),se(o),k=o.type,A=o.pendingProps,F=s!==null?s.memoizedProps:null,g=A.children,Ff(k,A)?g=null:F!==null&&Ff(k,F)&&(o.flags|=32),o.memoizedState!==null&&(k=Hh(s,o,SE,null,null,f),tl._currentValue=k),Mc(s,o),Nn(s,o,g,f),o.child;case 6:return s===null&&vt&&((s=f=Vt)&&(f=lj(f,o.pendingProps,xr),f!==null?(o.stateNode=f,En=o,Vt=null,s=!0):s=!1),s||Ds(o)),null;case 13:return mb(s,o,f);case 4:return B(o,o.stateNode.containerInfo),g=o.pendingProps,s===null?o.child=Ei(o,null,g,f):Nn(s,o,g,f),o.child;case 11:return ib(s,o,o.type,o.pendingProps,f);case 7:return Nn(s,o,o.pendingProps,f),o.child;case 8:return Nn(s,o,o.pendingProps.children,f),o.child;case 12:return Nn(s,o,o.pendingProps.children,f),o.child;case 10:return g=o.pendingProps,Rs(o,o.type,g.value),Nn(s,o,g.children,f),o.child;case 9:return k=o.type._context,g=o.pendingProps.children,Si(o),k=jn(k),g=g(k),o.flags|=1,Nn(s,o,g,f),o.child;case 14:return ab(s,o,o.type,o.pendingProps,f);case 15:return ob(s,o,o.type,o.pendingProps,f);case 19:return gb(s,o,f);case 31:return AE(s,o,f);case 22:return lb(s,o,f,o.pendingProps);case 24:return Si(o),g=jn(on),s===null?(k=Lh(),k===null&&(k=Mt,A=Th(),k.pooledCache=A,A.refCount++,A!==null&&(k.pooledCacheLanes|=f),k=A),o.memoizedState={parent:g,cache:k},Rh(o),Rs(o,on,k)):((s.lanes&f)!==0&&(Oh(s,o),Io(o,null,null,f),Oo()),k=s.memoizedState,A=o.memoizedState,k.parent!==g?(k={parent:g,cache:g},o.memoizedState=k,o.lanes===0&&(o.memoizedState=o.updateQueue.baseState=k),Rs(o,on,g)):(g=A.cache,Rs(o,on,g),g!==k.cache&&Nh(o,[on],f,!0))),Nn(s,o,o.pendingProps.children,f),o.child;case 29:throw o.pendingProps}throw Error(r(156,o.tag))}function ls(s){s.flags|=4}function gf(s,o,f,g,k){if((o=(s.mode&32)!==0)&&(o=!1),o){if(s.flags|=16777216,(k&335544128)===k)if(s.stateNode.complete)s.flags|=8192;else if(Vb())s.flags|=8192;else throw ki=_c,Dh}else s.flags&=-16777217}function yb(s,o){if(o.type!=="stylesheet"||(o.state.loading&4)!==0)s.flags&=-16777217;else if(s.flags|=16777216,!Rv(o))if(Vb())s.flags|=8192;else throw ki=_c,Dh}function Bc(s,o){o!==null&&(s.flags|=4),s.flags&16384&&(o=s.tag!==22?vn():536870912,s.lanes|=o,Ta|=o)}function Ho(s,o){if(!vt)switch(s.tailMode){case"hidden":o=s.tail;for(var f=null;o!==null;)o.alternate!==null&&(f=o),o=o.sibling;f===null?s.tail=null:f.sibling=null;break;case"collapsed":f=s.tail;for(var g=null;f!==null;)f.alternate!==null&&(g=f),f=f.sibling;g===null?o||s.tail===null?s.tail=null:s.tail.sibling=null:g.sibling=null}}function Gt(s){var o=s.alternate!==null&&s.alternate.child===s.child,f=0,g=0;if(o)for(var k=s.child;k!==null;)f|=k.lanes|k.childLanes,g|=k.subtreeFlags&65011712,g|=k.flags&65011712,k.return=s,k=k.sibling;else for(k=s.child;k!==null;)f|=k.lanes|k.childLanes,g|=k.subtreeFlags,g|=k.flags,k.return=s,k=k.sibling;return s.subtreeFlags|=g,s.childLanes=f,o}function DE(s,o,f){var g=o.pendingProps;switch(wh(o),o.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Gt(o),null;case 1:return Gt(o),null;case 3:return f=o.stateNode,g=null,s!==null&&(g=s.memoizedState.cache),o.memoizedState.cache!==g&&(o.flags|=2048),ss(on),te(),f.pendingContext&&(f.context=f.pendingContext,f.pendingContext=null),(s===null||s.child===null)&&(ga(o)?ls(o):s===null||s.memoizedState.isDehydrated&&(o.flags&256)===0||(o.flags|=1024,kh())),Gt(o),null;case 26:var k=o.type,A=o.memoizedState;return s===null?(ls(o),A!==null?(Gt(o),yb(o,A)):(Gt(o),gf(o,k,null,g,f))):A?A!==s.memoizedState?(ls(o),Gt(o),yb(o,A)):(Gt(o),o.flags&=-16777217):(s=s.memoizedProps,s!==g&&ls(o),Gt(o),gf(o,k,s,g,f)),null;case 27:if(xe(o),f=ne.current,k=o.type,s!==null&&o.stateNode!=null)s.memoizedProps!==g&&ls(o);else{if(!g){if(o.stateNode===null)throw Error(r(166));return Gt(o),null}s=ee.current,ga(o)?Qx(o):(s=kv(k,g,f),o.stateNode=s,ls(o))}return Gt(o),null;case 5:if(xe(o),k=o.type,s!==null&&o.stateNode!=null)s.memoizedProps!==g&&ls(o);else{if(!g){if(o.stateNode===null)throw Error(r(166));return Gt(o),null}if(A=ee.current,ga(o))Qx(o);else{var F=Zc(ne.current);switch(A){case 1:A=F.createElementNS("http://www.w3.org/2000/svg",k);break;case 2:A=F.createElementNS("http://www.w3.org/1998/Math/MathML",k);break;default:switch(k){case"svg":A=F.createElementNS("http://www.w3.org/2000/svg",k);break;case"math":A=F.createElementNS("http://www.w3.org/1998/Math/MathML",k);break;case"script":A=F.createElement("div"),A.innerHTML="<script><\/script>",A=A.removeChild(A.firstChild);break;case"select":A=typeof g.is=="string"?F.createElement("select",{is:g.is}):F.createElement("select"),g.multiple?A.multiple=!0:g.size&&(A.size=g.size);break;default:A=typeof g.is=="string"?F.createElement(k,{is:g.is}):F.createElement(k)}}A[an]=o,A[Fn]=g;e:for(F=o.child;F!==null;){if(F.tag===5||F.tag===6)A.appendChild(F.stateNode);else if(F.tag!==4&&F.tag!==27&&F.child!==null){F.child.return=F,F=F.child;continue}if(F===o)break e;for(;F.sibling===null;){if(F.return===null||F.return===o)break e;F=F.return}F.sibling.return=F.return,F=F.sibling}o.stateNode=A;e:switch(Tn(A,k,g),k){case"button":case"input":case"select":case"textarea":g=!!g.autoFocus;break e;case"img":g=!0;break e;default:g=!1}g&&ls(o)}}return Gt(o),gf(o,o.type,s===null?null:s.memoizedProps,o.pendingProps,f),null;case 6:if(s&&o.stateNode!=null)s.memoizedProps!==g&&ls(o);else{if(typeof g!="string"&&o.stateNode===null)throw Error(r(166));if(s=ne.current,ga(o)){if(s=o.stateNode,f=o.memoizedProps,g=null,k=En,k!==null)switch(k.tag){case 27:case 5:g=k.memoizedProps}s[an]=o,s=!!(s.nodeValue===f||g!==null&&g.suppressHydrationWarning===!0||mv(s.nodeValue,f)),s||Ds(o,!0)}else s=Zc(s).createTextNode(g),s[an]=o,o.stateNode=s}return Gt(o),null;case 31:if(f=o.memoizedState,s===null||s.memoizedState!==null){if(g=ga(o),f!==null){if(s===null){if(!g)throw Error(r(318));if(s=o.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[an]=o}else vi(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;Gt(o),s=!1}else f=kh(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=f),s=!0;if(!s)return o.flags&256?(sr(o),o):(sr(o),null);if((o.flags&128)!==0)throw Error(r(558))}return Gt(o),null;case 13:if(g=o.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(k=ga(o),g!==null&&g.dehydrated!==null){if(s===null){if(!k)throw Error(r(318));if(k=o.memoizedState,k=k!==null?k.dehydrated:null,!k)throw Error(r(317));k[an]=o}else vi(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;Gt(o),k=!1}else k=kh(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=k),k=!0;if(!k)return o.flags&256?(sr(o),o):(sr(o),null)}return sr(o),(o.flags&128)!==0?(o.lanes=f,o):(f=g!==null,s=s!==null&&s.memoizedState!==null,f&&(g=o.child,k=null,g.alternate!==null&&g.alternate.memoizedState!==null&&g.alternate.memoizedState.cachePool!==null&&(k=g.alternate.memoizedState.cachePool.pool),A=null,g.memoizedState!==null&&g.memoizedState.cachePool!==null&&(A=g.memoizedState.cachePool.pool),A!==k&&(g.flags|=2048)),f!==s&&f&&(o.child.flags|=8192),Bc(o,o.updateQueue),Gt(o),null);case 4:return te(),s===null&&Bf(o.stateNode.containerInfo),Gt(o),null;case 10:return ss(o.type),Gt(o),null;case 19:if(q(en),g=o.memoizedState,g===null)return Gt(o),null;if(k=(o.flags&128)!==0,A=g.rendering,A===null)if(k)Ho(g,!1);else{if(Xt!==0||s!==null&&(s.flags&128)!==0)for(s=o.child;s!==null;){if(A=kc(s),A!==null){for(o.flags|=128,Ho(g,!1),s=A.updateQueue,o.updateQueue=s,Bc(o,s),o.subtreeFlags=0,s=f,f=o.child;f!==null;)Wx(f,s),f=f.sibling;return z(en,en.current&1|2),vt&&ns(o,g.treeForkCount),o.child}s=s.sibling}g.tail!==null&&De()>Fc&&(o.flags|=128,k=!0,Ho(g,!1),o.lanes=4194304)}else{if(!k)if(s=kc(A),s!==null){if(o.flags|=128,k=!0,s=s.updateQueue,o.updateQueue=s,Bc(o,s),Ho(g,!0),g.tail===null&&g.tailMode==="hidden"&&!A.alternate&&!vt)return Gt(o),null}else 2*De()-g.renderingStartTime>Fc&&f!==536870912&&(o.flags|=128,k=!0,Ho(g,!1),o.lanes=4194304);g.isBackwards?(A.sibling=o.child,o.child=A):(s=g.last,s!==null?s.sibling=A:o.child=A,g.last=A)}return g.tail!==null?(s=g.tail,g.rendering=s,g.tail=s.sibling,g.renderingStartTime=De(),s.sibling=null,f=en.current,z(en,k?f&1|2:f&1),vt&&ns(o,g.treeForkCount),s):(Gt(o),null);case 22:case 23:return sr(o),Bh(),g=o.memoizedState!==null,s!==null?s.memoizedState!==null!==g&&(o.flags|=8192):g&&(o.flags|=8192),g?(f&536870912)!==0&&(o.flags&128)===0&&(Gt(o),o.subtreeFlags&6&&(o.flags|=8192)):Gt(o),f=o.updateQueue,f!==null&&Bc(o,f.retryQueue),f=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(f=s.memoizedState.cachePool.pool),g=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(g=o.memoizedState.cachePool.pool),g!==f&&(o.flags|=2048),s!==null&&q(wi),null;case 24:return f=null,s!==null&&(f=s.memoizedState.cache),o.memoizedState.cache!==f&&(o.flags|=2048),ss(on),Gt(o),null;case 25:return null;case 30:return null}throw Error(r(156,o.tag))}function RE(s,o){switch(wh(o),o.tag){case 1:return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 3:return ss(on),te(),s=o.flags,(s&65536)!==0&&(s&128)===0?(o.flags=s&-65537|128,o):null;case 26:case 27:case 5:return xe(o),null;case 31:if(o.memoizedState!==null){if(sr(o),o.alternate===null)throw Error(r(340));vi()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 13:if(sr(o),s=o.memoizedState,s!==null&&s.dehydrated!==null){if(o.alternate===null)throw Error(r(340));vi()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 19:return q(en),null;case 4:return te(),null;case 10:return ss(o.type),null;case 22:case 23:return sr(o),Bh(),s!==null&&q(wi),s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 24:return ss(on),null;case 25:return null;default:return null}}function bb(s,o){switch(wh(o),o.tag){case 3:ss(on),te();break;case 26:case 27:case 5:xe(o);break;case 4:te();break;case 31:o.memoizedState!==null&&sr(o);break;case 13:sr(o);break;case 19:q(en);break;case 10:ss(o.type);break;case 22:case 23:sr(o),Bh(),s!==null&&q(wi);break;case 24:ss(on)}}function Uo(s,o){try{var f=o.updateQueue,g=f!==null?f.lastEffect:null;if(g!==null){var k=g.next;f=k;do{if((f.tag&s)===s){g=void 0;var A=f.create,F=f.inst;g=A(),F.destroy=g}f=f.next}while(f!==k)}}catch(Y){Tt(o,o.return,Y)}}function $s(s,o,f){try{var g=o.updateQueue,k=g!==null?g.lastEffect:null;if(k!==null){var A=k.next;g=A;do{if((g.tag&s)===s){var F=g.inst,Y=F.destroy;if(Y!==void 0){F.destroy=void 0,k=o;var ie=f,ge=Y;try{ge()}catch(ke){Tt(k,ie,ke)}}}g=g.next}while(g!==A)}}catch(ke){Tt(o,o.return,ke)}}function vb(s){var o=s.updateQueue;if(o!==null){var f=s.stateNode;try{uy(o,f)}catch(g){Tt(s,s.return,g)}}}function _b(s,o,f){f.props=Ni(s.type,s.memoizedProps),f.state=s.memoizedState;try{f.componentWillUnmount()}catch(g){Tt(s,o,g)}}function Fo(s,o){try{var f=s.ref;if(f!==null){switch(s.tag){case 26:case 27:case 5:var g=s.stateNode;break;case 30:g=s.stateNode;break;default:g=s.stateNode}typeof f=="function"?s.refCleanup=f(g):f.current=g}}catch(k){Tt(s,o,k)}}function Hr(s,o){var f=s.ref,g=s.refCleanup;if(f!==null)if(typeof g=="function")try{g()}catch(k){Tt(s,o,k)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof f=="function")try{f(null)}catch(k){Tt(s,o,k)}else f.current=null}function Sb(s){var o=s.type,f=s.memoizedProps,g=s.stateNode;try{e:switch(o){case"button":case"input":case"select":case"textarea":f.autoFocus&&g.focus();break e;case"img":f.src?g.src=f.src:f.srcSet&&(g.srcset=f.srcSet)}}catch(k){Tt(s,s.return,k)}}function xf(s,o,f){try{var g=s.stateNode;tj(g,s.type,f,o),g[Fn]=o}catch(k){Tt(s,s.return,k)}}function wb(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&Ws(s.type)||s.tag===4}function yf(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||wb(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&Ws(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function bf(s,o,f){var g=s.tag;if(g===5||g===6)s=s.stateNode,o?(f.nodeType===9?f.body:f.nodeName==="HTML"?f.ownerDocument.body:f).insertBefore(s,o):(o=f.nodeType===9?f.body:f.nodeName==="HTML"?f.ownerDocument.body:f,o.appendChild(s),f=f._reactRootContainer,f!=null||o.onclick!==null||(o.onclick=Zr));else if(g!==4&&(g===27&&Ws(s.type)&&(f=s.stateNode,o=null),s=s.child,s!==null))for(bf(s,o,f),s=s.sibling;s!==null;)bf(s,o,f),s=s.sibling}function $c(s,o,f){var g=s.tag;if(g===5||g===6)s=s.stateNode,o?f.insertBefore(s,o):f.appendChild(s);else if(g!==4&&(g===27&&Ws(s.type)&&(f=s.stateNode),s=s.child,s!==null))for($c(s,o,f),s=s.sibling;s!==null;)$c(s,o,f),s=s.sibling}function Cb(s){var o=s.stateNode,f=s.memoizedProps;try{for(var g=s.type,k=o.attributes;k.length;)o.removeAttributeNode(k[0]);Tn(o,g,f),o[an]=s,o[Fn]=f}catch(A){Tt(s,s.return,A)}}var cs=!1,un=!1,vf=!1,kb=typeof WeakSet=="function"?WeakSet:Set,Sn=null;function OE(s,o){if(s=s.containerInfo,Hf=au,s=Px(s),hh(s)){if("selectionStart"in s)var f={start:s.selectionStart,end:s.selectionEnd};else e:{f=(f=s.ownerDocument)&&f.defaultView||window;var g=f.getSelection&&f.getSelection();if(g&&g.rangeCount!==0){f=g.anchorNode;var k=g.anchorOffset,A=g.focusNode;g=g.focusOffset;try{f.nodeType,A.nodeType}catch{f=null;break e}var F=0,Y=-1,ie=-1,ge=0,ke=0,Ae=s,ye=null;t:for(;;){for(var be;Ae!==f||k!==0&&Ae.nodeType!==3||(Y=F+k),Ae!==A||g!==0&&Ae.nodeType!==3||(ie=F+g),Ae.nodeType===3&&(F+=Ae.nodeValue.length),(be=Ae.firstChild)!==null;)ye=Ae,Ae=be;for(;;){if(Ae===s)break t;if(ye===f&&++ge===k&&(Y=F),ye===A&&++ke===g&&(ie=F),(be=Ae.nextSibling)!==null)break;Ae=ye,ye=Ae.parentNode}Ae=be}f=Y===-1||ie===-1?null:{start:Y,end:ie}}else f=null}f=f||{start:0,end:0}}else f=null;for(Uf={focusedElem:s,selectionRange:f},au=!1,Sn=o;Sn!==null;)if(o=Sn,s=o.child,(o.subtreeFlags&1028)!==0&&s!==null)s.return=o,Sn=s;else for(;Sn!==null;){switch(o=Sn,A=o.alternate,s=o.flags,o.tag){case 0:if((s&4)!==0&&(s=o.updateQueue,s=s!==null?s.events:null,s!==null))for(f=0;f<s.length;f++)k=s[f],k.ref.impl=k.nextImpl;break;case 11:case 15:break;case 1:if((s&1024)!==0&&A!==null){s=void 0,f=o,k=A.memoizedProps,A=A.memoizedState,g=f.stateNode;try{var Ge=Ni(f.type,k);s=g.getSnapshotBeforeUpdate(Ge,A),g.__reactInternalSnapshotBeforeUpdate=s}catch(et){Tt(f,f.return,et)}}break;case 3:if((s&1024)!==0){if(s=o.stateNode.containerInfo,f=s.nodeType,f===9)Gf(s);else if(f===1)switch(s.nodeName){case"HEAD":case"HTML":case"BODY":Gf(s);break;default:s.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((s&1024)!==0)throw Error(r(163))}if(s=o.sibling,s!==null){s.return=o.return,Sn=s;break}Sn=o.return}}function Eb(s,o,f){var g=f.flags;switch(f.tag){case 0:case 11:case 15:ds(s,f),g&4&&Uo(5,f);break;case 1:if(ds(s,f),g&4)if(s=f.stateNode,o===null)try{s.componentDidMount()}catch(F){Tt(f,f.return,F)}else{var k=Ni(f.type,o.memoizedProps);o=o.memoizedState;try{s.componentDidUpdate(k,o,s.__reactInternalSnapshotBeforeUpdate)}catch(F){Tt(f,f.return,F)}}g&64&&vb(f),g&512&&Fo(f,f.return);break;case 3:if(ds(s,f),g&64&&(s=f.updateQueue,s!==null)){if(o=null,f.child!==null)switch(f.child.tag){case 27:case 5:o=f.child.stateNode;break;case 1:o=f.child.stateNode}try{uy(s,o)}catch(F){Tt(f,f.return,F)}}break;case 27:o===null&&g&4&&Cb(f);case 26:case 5:ds(s,f),o===null&&g&4&&Sb(f),g&512&&Fo(f,f.return);break;case 12:ds(s,f);break;case 31:ds(s,f),g&4&&Tb(s,f);break;case 13:ds(s,f),g&4&&Ab(s,f),g&64&&(s=f.memoizedState,s!==null&&(s=s.dehydrated,s!==null&&(f=FE.bind(null,f),cj(s,f))));break;case 22:if(g=f.memoizedState!==null||cs,!g){o=o!==null&&o.memoizedState!==null||un,k=cs;var A=un;cs=g,(un=o)&&!A?hs(s,f,(f.subtreeFlags&8772)!==0):ds(s,f),cs=k,un=A}break;case 30:break;default:ds(s,f)}}function jb(s){var o=s.alternate;o!==null&&(s.alternate=null,jb(o)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(o=s.stateNode,o!==null&&Yd(o)),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}var Wt=null,Gn=!1;function us(s,o,f){for(f=f.child;f!==null;)Nb(s,o,f),f=f.sibling}function Nb(s,o,f){if(It&&typeof It.onCommitFiberUnmount=="function")try{It.onCommitFiberUnmount(_t,f)}catch{}switch(f.tag){case 26:un||Hr(f,o),us(s,o,f),f.memoizedState?f.memoizedState.count--:f.stateNode&&(f=f.stateNode,f.parentNode.removeChild(f));break;case 27:un||Hr(f,o);var g=Wt,k=Gn;Ws(f.type)&&(Wt=f.stateNode,Gn=!1),us(s,o,f),Jo(f.stateNode),Wt=g,Gn=k;break;case 5:un||Hr(f,o);case 6:if(g=Wt,k=Gn,Wt=null,us(s,o,f),Wt=g,Gn=k,Wt!==null)if(Gn)try{(Wt.nodeType===9?Wt.body:Wt.nodeName==="HTML"?Wt.ownerDocument.body:Wt).removeChild(f.stateNode)}catch(A){Tt(f,o,A)}else try{Wt.removeChild(f.stateNode)}catch(A){Tt(f,o,A)}break;case 18:Wt!==null&&(Gn?(s=Wt,vv(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,f.stateNode),Pa(s)):vv(Wt,f.stateNode));break;case 4:g=Wt,k=Gn,Wt=f.stateNode.containerInfo,Gn=!0,us(s,o,f),Wt=g,Gn=k;break;case 0:case 11:case 14:case 15:$s(2,f,o),un||$s(4,f,o),us(s,o,f);break;case 1:un||(Hr(f,o),g=f.stateNode,typeof g.componentWillUnmount=="function"&&_b(f,o,g)),us(s,o,f);break;case 21:us(s,o,f);break;case 22:un=(g=un)||f.memoizedState!==null,us(s,o,f),un=g;break;default:us(s,o,f)}}function Tb(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null))){s=s.dehydrated;try{Pa(s)}catch(f){Tt(o,o.return,f)}}}function Ab(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null&&(s=s.dehydrated,s!==null))))try{Pa(s)}catch(f){Tt(o,o.return,f)}}function IE(s){switch(s.tag){case 31:case 13:case 19:var o=s.stateNode;return o===null&&(o=s.stateNode=new kb),o;case 22:return s=s.stateNode,o=s._retryCache,o===null&&(o=s._retryCache=new kb),o;default:throw Error(r(435,s.tag))}}function zc(s,o){var f=IE(s);o.forEach(function(g){if(!f.has(g)){f.add(g);var k=VE.bind(null,s,g);g.then(k,k)}})}function Wn(s,o){var f=o.deletions;if(f!==null)for(var g=0;g<f.length;g++){var k=f[g],A=s,F=o,Y=F;e:for(;Y!==null;){switch(Y.tag){case 27:if(Ws(Y.type)){Wt=Y.stateNode,Gn=!1;break e}break;case 5:Wt=Y.stateNode,Gn=!1;break e;case 3:case 4:Wt=Y.stateNode.containerInfo,Gn=!0;break e}Y=Y.return}if(Wt===null)throw Error(r(160));Nb(A,F,k),Wt=null,Gn=!1,A=k.alternate,A!==null&&(A.return=null),k.return=null}if(o.subtreeFlags&13886)for(o=o.child;o!==null;)Lb(o,s),o=o.sibling}var Nr=null;function Lb(s,o){var f=s.alternate,g=s.flags;switch(s.tag){case 0:case 11:case 14:case 15:Wn(o,s),qn(s),g&4&&($s(3,s,s.return),Uo(3,s),$s(5,s,s.return));break;case 1:Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),g&64&&cs&&(s=s.updateQueue,s!==null&&(g=s.callbacks,g!==null&&(f=s.shared.hiddenCallbacks,s.shared.hiddenCallbacks=f===null?g:f.concat(g))));break;case 26:var k=Nr;if(Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),g&4){var A=f!==null?f.memoizedState:null;if(g=s.memoizedState,f===null)if(g===null)if(s.stateNode===null){e:{g=s.type,f=s.memoizedProps,k=k.ownerDocument||k;t:switch(g){case"title":A=k.getElementsByTagName("title")[0],(!A||A[go]||A[an]||A.namespaceURI==="http://www.w3.org/2000/svg"||A.hasAttribute("itemprop"))&&(A=k.createElement(g),k.head.insertBefore(A,k.querySelector("head > title"))),Tn(A,g,f),A[an]=s,_n(A),g=A;break e;case"link":var F=Lv("link","href",k).get(g+(f.href||""));if(F){for(var Y=0;Y<F.length;Y++)if(A=F[Y],A.getAttribute("href")===(f.href==null||f.href===""?null:f.href)&&A.getAttribute("rel")===(f.rel==null?null:f.rel)&&A.getAttribute("title")===(f.title==null?null:f.title)&&A.getAttribute("crossorigin")===(f.crossOrigin==null?null:f.crossOrigin)){F.splice(Y,1);break t}}A=k.createElement(g),Tn(A,g,f),k.head.appendChild(A);break;case"meta":if(F=Lv("meta","content",k).get(g+(f.content||""))){for(Y=0;Y<F.length;Y++)if(A=F[Y],A.getAttribute("content")===(f.content==null?null:""+f.content)&&A.getAttribute("name")===(f.name==null?null:f.name)&&A.getAttribute("property")===(f.property==null?null:f.property)&&A.getAttribute("http-equiv")===(f.httpEquiv==null?null:f.httpEquiv)&&A.getAttribute("charset")===(f.charSet==null?null:f.charSet)){F.splice(Y,1);break t}}A=k.createElement(g),Tn(A,g,f),k.head.appendChild(A);break;default:throw Error(r(468,g))}A[an]=s,_n(A),g=A}s.stateNode=g}else Dv(k,s.type,s.stateNode);else s.stateNode=Av(k,g,s.memoizedProps);else A!==g?(A===null?f.stateNode!==null&&(f=f.stateNode,f.parentNode.removeChild(f)):A.count--,g===null?Dv(k,s.type,s.stateNode):Av(k,g,s.memoizedProps)):g===null&&s.stateNode!==null&&xf(s,s.memoizedProps,f.memoizedProps)}break;case 27:Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),f!==null&&g&4&&xf(s,s.memoizedProps,f.memoizedProps);break;case 5:if(Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),s.flags&32){k=s.stateNode;try{aa(k,"")}catch(Ge){Tt(s,s.return,Ge)}}g&4&&s.stateNode!=null&&(k=s.memoizedProps,xf(s,k,f!==null?f.memoizedProps:k)),g&1024&&(vf=!0);break;case 6:if(Wn(o,s),qn(s),g&4){if(s.stateNode===null)throw Error(r(162));g=s.memoizedProps,f=s.stateNode;try{f.nodeValue=g}catch(Ge){Tt(s,s.return,Ge)}}break;case 3:if(nu=null,k=Nr,Nr=eu(o.containerInfo),Wn(o,s),Nr=k,qn(s),g&4&&f!==null&&f.memoizedState.isDehydrated)try{Pa(o.containerInfo)}catch(Ge){Tt(s,s.return,Ge)}vf&&(vf=!1,Db(s));break;case 4:g=Nr,Nr=eu(s.stateNode.containerInfo),Wn(o,s),qn(s),Nr=g;break;case 12:Wn(o,s),qn(s);break;case 31:Wn(o,s),qn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,zc(s,g)));break;case 13:Wn(o,s),qn(s),s.child.flags&8192&&s.memoizedState!==null!=(f!==null&&f.memoizedState!==null)&&(Uc=De()),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,zc(s,g)));break;case 22:k=s.memoizedState!==null;var ie=f!==null&&f.memoizedState!==null,ge=cs,ke=un;if(cs=ge||k,un=ke||ie,Wn(o,s),un=ke,cs=ge,qn(s),g&8192)e:for(o=s.stateNode,o._visibility=k?o._visibility&-2:o._visibility|1,k&&(f===null||ie||cs||un||Ti(s)),f=null,o=s;;){if(o.tag===5||o.tag===26){if(f===null){ie=f=o;try{if(A=ie.stateNode,k)F=A.style,typeof F.setProperty=="function"?F.setProperty("display","none","important"):F.display="none";else{Y=ie.stateNode;var Ae=ie.memoizedProps.style,ye=Ae!=null&&Ae.hasOwnProperty("display")?Ae.display:null;Y.style.display=ye==null||typeof ye=="boolean"?"":(""+ye).trim()}}catch(Ge){Tt(ie,ie.return,Ge)}}}else if(o.tag===6){if(f===null){ie=o;try{ie.stateNode.nodeValue=k?"":ie.memoizedProps}catch(Ge){Tt(ie,ie.return,Ge)}}}else if(o.tag===18){if(f===null){ie=o;try{var be=ie.stateNode;k?_v(be,!0):_v(ie.stateNode,!1)}catch(Ge){Tt(ie,ie.return,Ge)}}}else if((o.tag!==22&&o.tag!==23||o.memoizedState===null||o===s)&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===s)break e;for(;o.sibling===null;){if(o.return===null||o.return===s)break e;f===o&&(f=null),o=o.return}f===o&&(f=null),o.sibling.return=o.return,o=o.sibling}g&4&&(g=s.updateQueue,g!==null&&(f=g.retryQueue,f!==null&&(g.retryQueue=null,zc(s,f))));break;case 19:Wn(o,s),qn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,zc(s,g)));break;case 30:break;case 21:break;default:Wn(o,s),qn(s)}}function qn(s){var o=s.flags;if(o&2){try{for(var f,g=s.return;g!==null;){if(wb(g)){f=g;break}g=g.return}if(f==null)throw Error(r(160));switch(f.tag){case 27:var k=f.stateNode,A=yf(s);$c(s,A,k);break;case 5:var F=f.stateNode;f.flags&32&&(aa(F,""),f.flags&=-33);var Y=yf(s);$c(s,Y,F);break;case 3:case 4:var ie=f.stateNode.containerInfo,ge=yf(s);bf(s,ge,ie);break;default:throw Error(r(161))}}catch(ke){Tt(s,s.return,ke)}s.flags&=-3}o&4096&&(s.flags&=-4097)}function Db(s){if(s.subtreeFlags&1024)for(s=s.child;s!==null;){var o=s;Db(o),o.tag===5&&o.flags&1024&&o.stateNode.reset(),s=s.sibling}}function ds(s,o){if(o.subtreeFlags&8772)for(o=o.child;o!==null;)Eb(s,o.alternate,o),o=o.sibling}function Ti(s){for(s=s.child;s!==null;){var o=s;switch(o.tag){case 0:case 11:case 14:case 15:$s(4,o,o.return),Ti(o);break;case 1:Hr(o,o.return);var f=o.stateNode;typeof f.componentWillUnmount=="function"&&_b(o,o.return,f),Ti(o);break;case 27:Jo(o.stateNode);case 26:case 5:Hr(o,o.return),Ti(o);break;case 22:o.memoizedState===null&&Ti(o);break;case 30:Ti(o);break;default:Ti(o)}s=s.sibling}}function hs(s,o,f){for(f=f&&(o.subtreeFlags&8772)!==0,o=o.child;o!==null;){var g=o.alternate,k=s,A=o,F=A.flags;switch(A.tag){case 0:case 11:case 15:hs(k,A,f),Uo(4,A);break;case 1:if(hs(k,A,f),g=A,k=g.stateNode,typeof k.componentDidMount=="function")try{k.componentDidMount()}catch(ge){Tt(g,g.return,ge)}if(g=A,k=g.updateQueue,k!==null){var Y=g.stateNode;try{var ie=k.shared.hiddenCallbacks;if(ie!==null)for(k.shared.hiddenCallbacks=null,k=0;k<ie.length;k++)cy(ie[k],Y)}catch(ge){Tt(g,g.return,ge)}}f&&F&64&&vb(A),Fo(A,A.return);break;case 27:Cb(A);case 26:case 5:hs(k,A,f),f&&g===null&&F&4&&Sb(A),Fo(A,A.return);break;case 12:hs(k,A,f);break;case 31:hs(k,A,f),f&&F&4&&Tb(k,A);break;case 13:hs(k,A,f),f&&F&4&&Ab(k,A);break;case 22:A.memoizedState===null&&hs(k,A,f),Fo(A,A.return);break;case 30:break;default:hs(k,A,f)}o=o.sibling}}function _f(s,o){var f=null;s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(f=s.memoizedState.cachePool.pool),s=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(s=o.memoizedState.cachePool.pool),s!==f&&(s!=null&&s.refCount++,f!=null&&To(f))}function Sf(s,o){s=null,o.alternate!==null&&(s=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==s&&(o.refCount++,s!=null&&To(s))}function Tr(s,o,f,g){if(o.subtreeFlags&10256)for(o=o.child;o!==null;)Rb(s,o,f,g),o=o.sibling}function Rb(s,o,f,g){var k=o.flags;switch(o.tag){case 0:case 11:case 15:Tr(s,o,f,g),k&2048&&Uo(9,o);break;case 1:Tr(s,o,f,g);break;case 3:Tr(s,o,f,g),k&2048&&(s=null,o.alternate!==null&&(s=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==s&&(o.refCount++,s!=null&&To(s)));break;case 12:if(k&2048){Tr(s,o,f,g),s=o.stateNode;try{var A=o.memoizedProps,F=A.id,Y=A.onPostCommit;typeof Y=="function"&&Y(F,o.alternate===null?"mount":"update",s.passiveEffectDuration,-0)}catch(ie){Tt(o,o.return,ie)}}else Tr(s,o,f,g);break;case 31:Tr(s,o,f,g);break;case 13:Tr(s,o,f,g);break;case 23:break;case 22:A=o.stateNode,F=o.alternate,o.memoizedState!==null?A._visibility&2?Tr(s,o,f,g):Vo(s,o):A._visibility&2?Tr(s,o,f,g):(A._visibility|=2,Ea(s,o,f,g,(o.subtreeFlags&10256)!==0||!1)),k&2048&&_f(F,o);break;case 24:Tr(s,o,f,g),k&2048&&Sf(o.alternate,o);break;default:Tr(s,o,f,g)}}function Ea(s,o,f,g,k){for(k=k&&((o.subtreeFlags&10256)!==0||!1),o=o.child;o!==null;){var A=s,F=o,Y=f,ie=g,ge=F.flags;switch(F.tag){case 0:case 11:case 15:Ea(A,F,Y,ie,k),Uo(8,F);break;case 23:break;case 22:var ke=F.stateNode;F.memoizedState!==null?ke._visibility&2?Ea(A,F,Y,ie,k):Vo(A,F):(ke._visibility|=2,Ea(A,F,Y,ie,k)),k&&ge&2048&&_f(F.alternate,F);break;case 24:Ea(A,F,Y,ie,k),k&&ge&2048&&Sf(F.alternate,F);break;default:Ea(A,F,Y,ie,k)}o=o.sibling}}function Vo(s,o){if(o.subtreeFlags&10256)for(o=o.child;o!==null;){var f=s,g=o,k=g.flags;switch(g.tag){case 22:Vo(f,g),k&2048&&_f(g.alternate,g);break;case 24:Vo(f,g),k&2048&&Sf(g.alternate,g);break;default:Vo(f,g)}o=o.sibling}}var Go=8192;function ja(s,o,f){if(s.subtreeFlags&Go)for(s=s.child;s!==null;)Ob(s,o,f),s=s.sibling}function Ob(s,o,f){switch(s.tag){case 26:ja(s,o,f),s.flags&Go&&s.memoizedState!==null&&_j(f,Nr,s.memoizedState,s.memoizedProps);break;case 5:ja(s,o,f);break;case 3:case 4:var g=Nr;Nr=eu(s.stateNode.containerInfo),ja(s,o,f),Nr=g;break;case 22:s.memoizedState===null&&(g=s.alternate,g!==null&&g.memoizedState!==null?(g=Go,Go=16777216,ja(s,o,f),Go=g):ja(s,o,f));break;default:ja(s,o,f)}}function Ib(s){var o=s.alternate;if(o!==null&&(s=o.child,s!==null)){o.child=null;do o=s.sibling,s.sibling=null,s=o;while(s!==null)}}function Wo(s){var o=s.deletions;if((s.flags&16)!==0){if(o!==null)for(var f=0;f<o.length;f++){var g=o[f];Sn=g,Pb(g,s)}Ib(s)}if(s.subtreeFlags&10256)for(s=s.child;s!==null;)Mb(s),s=s.sibling}function Mb(s){switch(s.tag){case 0:case 11:case 15:Wo(s),s.flags&2048&&$s(9,s,s.return);break;case 3:Wo(s);break;case 12:Wo(s);break;case 22:var o=s.stateNode;s.memoizedState!==null&&o._visibility&2&&(s.return===null||s.return.tag!==13)?(o._visibility&=-3,Hc(s)):Wo(s);break;default:Wo(s)}}function Hc(s){var o=s.deletions;if((s.flags&16)!==0){if(o!==null)for(var f=0;f<o.length;f++){var g=o[f];Sn=g,Pb(g,s)}Ib(s)}for(s=s.child;s!==null;){switch(o=s,o.tag){case 0:case 11:case 15:$s(8,o,o.return),Hc(o);break;case 22:f=o.stateNode,f._visibility&2&&(f._visibility&=-3,Hc(o));break;default:Hc(o)}s=s.sibling}}function Pb(s,o){for(;Sn!==null;){var f=Sn;switch(f.tag){case 0:case 11:case 15:$s(8,f,o);break;case 23:case 22:if(f.memoizedState!==null&&f.memoizedState.cachePool!==null){var g=f.memoizedState.cachePool.pool;g!=null&&g.refCount++}break;case 24:To(f.memoizedState.cache)}if(g=f.child,g!==null)g.return=f,Sn=g;else e:for(f=s;Sn!==null;){g=Sn;var k=g.sibling,A=g.return;if(jb(g),g===f){Sn=null;break e}if(k!==null){k.return=A,Sn=k;break e}Sn=A}}}var ME={getCacheForType:function(s){var o=jn(on),f=o.data.get(s);return f===void 0&&(f=s(),o.data.set(s,f)),f},cacheSignal:function(){return jn(on).controller.signal}},PE=typeof WeakMap=="function"?WeakMap:Map,Et=0,Mt=null,ht=null,yt=0,Nt=0,ir=null,zs=!1,Na=!1,wf=!1,fs=0,Xt=0,Hs=0,Ai=0,Cf=0,ar=0,Ta=0,qo=null,Kn=null,kf=!1,Uc=0,Bb=0,Fc=1/0,Vc=null,Us=null,pn=0,Fs=null,Aa=null,ms=0,Ef=0,jf=null,$b=null,Ko=0,Nf=null;function or(){return(Et&2)!==0&&yt!==0?yt&-yt:G.T!==null?Of():sn()}function zb(){if(ar===0)if((yt&536870912)===0||vt){var s=ve;ve<<=1,(ve&3932160)===0&&(ve=262144),ar=s}else ar=536870912;return s=rr.current,s!==null&&(s.flags|=32),ar}function Yn(s,o,f){(s===Mt&&(Nt===2||Nt===9)||s.cancelPendingCommit!==null)&&(La(s,0),Vs(s,yt,ar,!1)),Ce(s,f),((Et&2)===0||s!==Mt)&&(s===Mt&&((Et&2)===0&&(Ai|=f),Xt===4&&Vs(s,yt,ar,!1)),Ur(s))}function Hb(s,o,f){if((Et&6)!==0)throw Error(r(327));var g=!f&&(o&127)===0&&(o&s.expiredLanes)===0||Ie(s,o),k=g?zE(s,o):Af(s,o,!0),A=g;do{if(k===0){Na&&!g&&Vs(s,o,0,!1);break}else{if(f=s.current.alternate,A&&!BE(f)){k=Af(s,o,!1),A=!1;continue}if(k===2){if(A=o,s.errorRecoveryDisabledLanes&A)var F=0;else F=s.pendingLanes&-536870913,F=F!==0?F:F&536870912?536870912:0;if(F!==0){o=F;e:{var Y=s;k=qo;var ie=Y.current.memoizedState.isDehydrated;if(ie&&(La(Y,F).flags|=256),F=Af(Y,F,!1),F!==2){if(wf&&!ie){Y.errorRecoveryDisabledLanes|=A,Ai|=A,k=4;break e}A=Kn,Kn=k,A!==null&&(Kn===null?Kn=A:Kn.push.apply(Kn,A))}k=F}if(A=!1,k!==2)continue}}if(k===1){La(s,0),Vs(s,o,0,!0);break}e:{switch(g=s,A=k,A){case 0:case 1:throw Error(r(345));case 4:if((o&4194048)!==o)break;case 6:Vs(g,o,ar,!zs);break e;case 2:Kn=null;break;case 3:case 5:break;default:throw Error(r(329))}if((o&62914560)===o&&(k=Uc+300-De(),10<k)){if(Vs(g,o,ar,!zs),me(g,0,!0)!==0)break e;ms=o,g.timeoutHandle=yv(Ub.bind(null,g,f,Kn,Vc,kf,o,ar,Ai,Ta,zs,A,"Throttled",-0,0),k);break e}Ub(g,f,Kn,Vc,kf,o,ar,Ai,Ta,zs,A,null,-0,0)}}break}while(!0);Ur(s)}function Ub(s,o,f,g,k,A,F,Y,ie,ge,ke,Ae,ye,be){if(s.timeoutHandle=-1,Ae=o.subtreeFlags,Ae&8192||(Ae&16785408)===16785408){Ae={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Zr},Ob(o,A,Ae);var Ge=(A&62914560)===A?Uc-De():(A&4194048)===A?Bb-De():0;if(Ge=Sj(Ae,Ge),Ge!==null){ms=A,s.cancelPendingCommit=Ge(Xb.bind(null,s,o,A,f,g,k,F,Y,ie,ke,Ae,null,ye,be)),Vs(s,A,F,!ge);return}}Xb(s,o,A,f,g,k,F,Y,ie)}function BE(s){for(var o=s;;){var f=o.tag;if((f===0||f===11||f===15)&&o.flags&16384&&(f=o.updateQueue,f!==null&&(f=f.stores,f!==null)))for(var g=0;g<f.length;g++){var k=f[g],A=k.getSnapshot;k=k.value;try{if(!tr(A(),k))return!1}catch{return!1}}if(f=o.child,o.subtreeFlags&16384&&f!==null)f.return=o,o=f;else{if(o===s)break;for(;o.sibling===null;){if(o.return===null||o.return===s)return!0;o=o.return}o.sibling.return=o.return,o=o.sibling}}return!0}function Vs(s,o,f,g){o&=~Cf,o&=~Ai,s.suspendedLanes|=o,s.pingedLanes&=~o,g&&(s.warmLanes|=o),g=s.expirationTimes;for(var k=o;0<k;){var A=31-dt(k),F=1<<A;g[A]=-1,k&=~F}f!==0&&Fe(s,f,o)}function Gc(){return(Et&6)===0?(Yo(0),!1):!0}function Tf(){if(ht!==null){if(Nt===0)var s=ht.return;else s=ht,rs=_i=null,Vh(s),_a=null,Lo=0,s=ht;for(;s!==null;)bb(s.alternate,s),s=s.return;ht=null}}function La(s,o){var f=s.timeoutHandle;f!==-1&&(s.timeoutHandle=-1,sj(f)),f=s.cancelPendingCommit,f!==null&&(s.cancelPendingCommit=null,f()),ms=0,Tf(),Mt=s,ht=f=ts(s.current,null),yt=o,Nt=0,ir=null,zs=!1,Na=Ie(s,o),wf=!1,Ta=ar=Cf=Ai=Hs=Xt=0,Kn=qo=null,kf=!1,(o&8)!==0&&(o|=o&32);var g=s.entangledLanes;if(g!==0)for(s=s.entanglements,g&=o;0<g;){var k=31-dt(g),A=1<<k;o|=s[k],g&=~A}return fs=o,hc(),f}function Fb(s,o){at=null,G.H=$o,o===va||o===vc?(o=iy(),Nt=3):o===Dh?(o=iy(),Nt=4):Nt=o===of?8:o!==null&&typeof o=="object"&&typeof o.then=="function"?6:1,ir=o,ht===null&&(Xt=1,Oc(s,mr(o,s.current)))}function Vb(){var s=rr.current;return s===null?!0:(yt&4194048)===yt?yr===null:(yt&62914560)===yt||(yt&536870912)!==0?s===yr:!1}function Gb(){var s=G.H;return G.H=$o,s===null?$o:s}function Wb(){var s=G.A;return G.A=ME,s}function Wc(){Xt=4,zs||(yt&4194048)!==yt&&rr.current!==null||(Na=!0),(Hs&134217727)===0&&(Ai&134217727)===0||Mt===null||Vs(Mt,yt,ar,!1)}function Af(s,o,f){var g=Et;Et|=2;var k=Gb(),A=Wb();(Mt!==s||yt!==o)&&(Vc=null,La(s,o)),o=!1;var F=Xt;e:do try{if(Nt!==0&&ht!==null){var Y=ht,ie=ir;switch(Nt){case 8:Tf(),F=6;break e;case 3:case 2:case 9:case 6:rr.current===null&&(o=!0);var ge=Nt;if(Nt=0,ir=null,Da(s,Y,ie,ge),f&&Na){F=0;break e}break;default:ge=Nt,Nt=0,ir=null,Da(s,Y,ie,ge)}}$E(),F=Xt;break}catch(ke){Fb(s,ke)}while(!0);return o&&s.shellSuspendCounter++,rs=_i=null,Et=g,G.H=k,G.A=A,ht===null&&(Mt=null,yt=0,hc()),F}function $E(){for(;ht!==null;)qb(ht)}function zE(s,o){var f=Et;Et|=2;var g=Gb(),k=Wb();Mt!==s||yt!==o?(Vc=null,Fc=De()+500,La(s,o)):Na=Ie(s,o);e:do try{if(Nt!==0&&ht!==null){o=ht;var A=ir;t:switch(Nt){case 1:Nt=0,ir=null,Da(s,o,A,1);break;case 2:case 9:if(ry(A)){Nt=0,ir=null,Kb(o);break}o=function(){Nt!==2&&Nt!==9||Mt!==s||(Nt=7),Ur(s)},A.then(o,o);break e;case 3:Nt=7;break e;case 4:Nt=5;break e;case 7:ry(A)?(Nt=0,ir=null,Kb(o)):(Nt=0,ir=null,Da(s,o,A,7));break;case 5:var F=null;switch(ht.tag){case 26:F=ht.memoizedState;case 5:case 27:var Y=ht;if(F?Rv(F):Y.stateNode.complete){Nt=0,ir=null;var ie=Y.sibling;if(ie!==null)ht=ie;else{var ge=Y.return;ge!==null?(ht=ge,qc(ge)):ht=null}break t}}Nt=0,ir=null,Da(s,o,A,5);break;case 6:Nt=0,ir=null,Da(s,o,A,6);break;case 8:Tf(),Xt=6;break e;default:throw Error(r(462))}}HE();break}catch(ke){Fb(s,ke)}while(!0);return rs=_i=null,G.H=g,G.A=k,Et=f,ht!==null?0:(Mt=null,yt=0,hc(),Xt)}function HE(){for(;ht!==null&&!de();)qb(ht)}function qb(s){var o=xb(s.alternate,s,fs);s.memoizedProps=s.pendingProps,o===null?qc(s):ht=o}function Kb(s){var o=s,f=o.alternate;switch(o.tag){case 15:case 0:o=db(f,o,o.pendingProps,o.type,void 0,yt);break;case 11:o=db(f,o,o.pendingProps,o.type.render,o.ref,yt);break;case 5:Vh(o);default:bb(f,o),o=ht=Wx(o,fs),o=xb(f,o,fs)}s.memoizedProps=s.pendingProps,o===null?qc(s):ht=o}function Da(s,o,f,g){rs=_i=null,Vh(o),_a=null,Lo=0;var k=o.return;try{if(TE(s,k,o,f,yt)){Xt=1,Oc(s,mr(f,s.current)),ht=null;return}}catch(A){if(k!==null)throw ht=k,A;Xt=1,Oc(s,mr(f,s.current)),ht=null;return}o.flags&32768?(vt||g===1?s=!0:Na||(yt&536870912)!==0?s=!1:(zs=s=!0,(g===2||g===9||g===3||g===6)&&(g=rr.current,g!==null&&g.tag===13&&(g.flags|=16384))),Yb(o,s)):qc(o)}function qc(s){var o=s;do{if((o.flags&32768)!==0){Yb(o,zs);return}s=o.return;var f=DE(o.alternate,o,fs);if(f!==null){ht=f;return}if(o=o.sibling,o!==null){ht=o;return}ht=o=s}while(o!==null);Xt===0&&(Xt=5)}function Yb(s,o){do{var f=RE(s.alternate,s);if(f!==null){f.flags&=32767,ht=f;return}if(f=s.return,f!==null&&(f.flags|=32768,f.subtreeFlags=0,f.deletions=null),!o&&(s=s.sibling,s!==null)){ht=s;return}ht=s=f}while(s!==null);Xt=6,ht=null}function Xb(s,o,f,g,k,A,F,Y,ie){s.cancelPendingCommit=null;do Kc();while(pn!==0);if((Et&6)!==0)throw Error(r(327));if(o!==null){if(o===s.current)throw Error(r(177));if(A=o.lanes|o.childLanes,A|=xh,Ne(s,f,A,F,Y,ie),s===Mt&&(ht=Mt=null,yt=0),Aa=o,Fs=s,ms=f,Ef=A,jf=k,$b=g,(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?(s.callbackNode=null,s.callbackPriority=0,GE(Le,function(){return tv(),null})):(s.callbackNode=null,s.callbackPriority=0),g=(o.flags&13878)!==0,(o.subtreeFlags&13878)!==0||g){g=G.T,G.T=null,k=Z.p,Z.p=2,F=Et,Et|=4;try{OE(s,o,f)}finally{Et=F,Z.p=k,G.T=g}}pn=1,Qb(),Jb(),Zb()}}function Qb(){if(pn===1){pn=0;var s=Fs,o=Aa,f=(o.flags&13878)!==0;if((o.subtreeFlags&13878)!==0||f){f=G.T,G.T=null;var g=Z.p;Z.p=2;var k=Et;Et|=4;try{Lb(o,s);var A=Uf,F=Px(s.containerInfo),Y=A.focusedElem,ie=A.selectionRange;if(F!==Y&&Y&&Y.ownerDocument&&Mx(Y.ownerDocument.documentElement,Y)){if(ie!==null&&hh(Y)){var ge=ie.start,ke=ie.end;if(ke===void 0&&(ke=ge),"selectionStart"in Y)Y.selectionStart=ge,Y.selectionEnd=Math.min(ke,Y.value.length);else{var Ae=Y.ownerDocument||document,ye=Ae&&Ae.defaultView||window;if(ye.getSelection){var be=ye.getSelection(),Ge=Y.textContent.length,et=Math.min(ie.start,Ge),Dt=ie.end===void 0?et:Math.min(ie.end,Ge);!be.extend&&et>Dt&&(F=Dt,Dt=et,et=F);var ue=Ix(Y,et),le=Ix(Y,Dt);if(ue&&le&&(be.rangeCount!==1||be.anchorNode!==ue.node||be.anchorOffset!==ue.offset||be.focusNode!==le.node||be.focusOffset!==le.offset)){var pe=Ae.createRange();pe.setStart(ue.node,ue.offset),be.removeAllRanges(),et>Dt?(be.addRange(pe),be.extend(le.node,le.offset)):(pe.setEnd(le.node,le.offset),be.addRange(pe))}}}}for(Ae=[],be=Y;be=be.parentNode;)be.nodeType===1&&Ae.push({element:be,left:be.scrollLeft,top:be.scrollTop});for(typeof Y.focus=="function"&&Y.focus(),Y=0;Y<Ae.length;Y++){var Ee=Ae[Y];Ee.element.scrollLeft=Ee.left,Ee.element.scrollTop=Ee.top}}au=!!Hf,Uf=Hf=null}finally{Et=k,Z.p=g,G.T=f}}s.current=o,pn=2}}function Jb(){if(pn===2){pn=0;var s=Fs,o=Aa,f=(o.flags&8772)!==0;if((o.subtreeFlags&8772)!==0||f){f=G.T,G.T=null;var g=Z.p;Z.p=2;var k=Et;Et|=4;try{Eb(s,o.alternate,o)}finally{Et=k,Z.p=g,G.T=f}}pn=3}}function Zb(){if(pn===4||pn===3){pn=0,he();var s=Fs,o=Aa,f=ms,g=$b;(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?pn=5:(pn=0,Aa=Fs=null,ev(s,s.pendingLanes));var k=s.pendingLanes;if(k===0&&(Us=null),xt(f),o=o.stateNode,It&&typeof It.onCommitFiberRoot=="function")try{It.onCommitFiberRoot(_t,o,void 0,(o.current.flags&128)===128)}catch{}if(g!==null){o=G.T,k=Z.p,Z.p=2,G.T=null;try{for(var A=s.onRecoverableError,F=0;F<g.length;F++){var Y=g[F];A(Y.value,{componentStack:Y.stack})}}finally{G.T=o,Z.p=k}}(ms&3)!==0&&Kc(),Ur(s),k=s.pendingLanes,(f&261930)!==0&&(k&42)!==0?s===Nf?Ko++:(Ko=0,Nf=s):Ko=0,Yo(0)}}function ev(s,o){(s.pooledCacheLanes&=o)===0&&(o=s.pooledCache,o!=null&&(s.pooledCache=null,To(o)))}function Kc(){return Qb(),Jb(),Zb(),tv()}function tv(){if(pn!==5)return!1;var s=Fs,o=Ef;Ef=0;var f=xt(ms),g=G.T,k=Z.p;try{Z.p=32>f?32:f,G.T=null,f=jf,jf=null;var A=Fs,F=ms;if(pn=0,Aa=Fs=null,ms=0,(Et&6)!==0)throw Error(r(331));var Y=Et;if(Et|=4,Mb(A.current),Rb(A,A.current,F,f),Et=Y,Yo(0,!1),It&&typeof It.onPostCommitFiberRoot=="function")try{It.onPostCommitFiberRoot(_t,A)}catch{}return!0}finally{Z.p=k,G.T=g,ev(s,o)}}function nv(s,o,f){o=mr(f,o),o=af(s.stateNode,o,2),s=Ms(s,o,2),s!==null&&(Ce(s,2),Ur(s))}function Tt(s,o,f){if(s.tag===3)nv(s,s,f);else for(;o!==null;){if(o.tag===3){nv(o,s,f);break}else if(o.tag===1){var g=o.stateNode;if(typeof o.type.getDerivedStateFromError=="function"||typeof g.componentDidCatch=="function"&&(Us===null||!Us.has(g))){s=mr(f,s),f=rb(2),g=Ms(o,f,2),g!==null&&(sb(f,g,o,s),Ce(g,2),Ur(g));break}}o=o.return}}function Lf(s,o,f){var g=s.pingCache;if(g===null){g=s.pingCache=new PE;var k=new Set;g.set(o,k)}else k=g.get(o),k===void 0&&(k=new Set,g.set(o,k));k.has(f)||(wf=!0,k.add(f),s=UE.bind(null,s,o,f),o.then(s,s))}function UE(s,o,f){var g=s.pingCache;g!==null&&g.delete(o),s.pingedLanes|=s.suspendedLanes&f,s.warmLanes&=~f,Mt===s&&(yt&f)===f&&(Xt===4||Xt===3&&(yt&62914560)===yt&&300>De()-Uc?(Et&2)===0&&La(s,0):Cf|=f,Ta===yt&&(Ta=0)),Ur(s)}function rv(s,o){o===0&&(o=vn()),s=yi(s,o),s!==null&&(Ce(s,o),Ur(s))}function FE(s){var o=s.memoizedState,f=0;o!==null&&(f=o.retryLane),rv(s,f)}function VE(s,o){var f=0;switch(s.tag){case 31:case 13:var g=s.stateNode,k=s.memoizedState;k!==null&&(f=k.retryLane);break;case 19:g=s.stateNode;break;case 22:g=s.stateNode._retryCache;break;default:throw Error(r(314))}g!==null&&g.delete(o),rv(s,f)}function GE(s,o){return fe(s,o)}var Yc=null,Ra=null,Df=!1,Xc=!1,Rf=!1,Gs=0;function Ur(s){s!==Ra&&s.next===null&&(Ra===null?Yc=Ra=s:Ra=Ra.next=s),Xc=!0,Df||(Df=!0,qE())}function Yo(s,o){if(!Rf&&Xc){Rf=!0;do for(var f=!1,g=Yc;g!==null;){if(s!==0){var k=g.pendingLanes;if(k===0)var A=0;else{var F=g.suspendedLanes,Y=g.pingedLanes;A=(1<<31-dt(42|s)+1)-1,A&=k&~(F&~Y),A=A&201326741?A&201326741|1:A?A|2:0}A!==0&&(f=!0,ov(g,A))}else A=yt,A=me(g,g===Mt?A:0,g.cancelPendingCommit!==null||g.timeoutHandle!==-1),(A&3)===0||Ie(g,A)||(f=!0,ov(g,A));g=g.next}while(f);Rf=!1}}function WE(){sv()}function sv(){Xc=Df=!1;var s=0;Gs!==0&&rj()&&(s=Gs);for(var o=De(),f=null,g=Yc;g!==null;){var k=g.next,A=iv(g,o);A===0?(g.next=null,f===null?Yc=k:f.next=k,k===null&&(Ra=f)):(f=g,(s!==0||(A&3)!==0)&&(Xc=!0)),g=k}pn!==0&&pn!==5||Yo(s),Gs!==0&&(Gs=0)}function iv(s,o){for(var f=s.suspendedLanes,g=s.pingedLanes,k=s.expirationTimes,A=s.pendingLanes&-62914561;0<A;){var F=31-dt(A),Y=1<<F,ie=k[F];ie===-1?((Y&f)===0||(Y&g)!==0)&&(k[F]=gt(Y,o)):ie<=o&&(s.expiredLanes|=Y),A&=~Y}if(o=Mt,f=yt,f=me(s,s===o?f:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g=s.callbackNode,f===0||s===o&&(Nt===2||Nt===9)||s.cancelPendingCommit!==null)return g!==null&&g!==null&&ce(g),s.callbackNode=null,s.callbackPriority=0;if((f&3)===0||Ie(s,f)){if(o=f&-f,o===s.callbackPriority)return o;switch(g!==null&&ce(g),xt(f)){case 2:case 8:f=_e;break;case 32:f=Le;break;case 268435456:f=qe;break;default:f=Le}return g=av.bind(null,s),f=fe(f,g),s.callbackPriority=o,s.callbackNode=f,o}return g!==null&&g!==null&&ce(g),s.callbackPriority=2,s.callbackNode=null,2}function av(s,o){if(pn!==0&&pn!==5)return s.callbackNode=null,s.callbackPriority=0,null;var f=s.callbackNode;if(Kc()&&s.callbackNode!==f)return null;var g=yt;return g=me(s,s===Mt?g:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g===0?null:(Hb(s,g,o),iv(s,De()),s.callbackNode!=null&&s.callbackNode===f?av.bind(null,s):null)}function ov(s,o){if(Kc())return null;Hb(s,o,!0)}function qE(){ij(function(){(Et&6)!==0?fe(re,WE):sv()})}function Of(){if(Gs===0){var s=ya;s===0&&(s=Br,Br<<=1,(Br&261888)===0&&(Br=256)),Gs=s}return Gs}function lv(s){return s==null||typeof s=="symbol"||typeof s=="boolean"?null:typeof s=="function"?s:sc(""+s)}function cv(s,o){var f=o.ownerDocument.createElement("input");return f.name=o.name,f.value=o.value,s.id&&f.setAttribute("form",s.id),o.parentNode.insertBefore(f,o),s=new FormData(s),f.parentNode.removeChild(f),s}function KE(s,o,f,g,k){if(o==="submit"&&f&&f.stateNode===k){var A=lv((k[Fn]||null).action),F=g.submitter;F&&(o=(o=F[Fn]||null)?lv(o.formAction):F.getAttribute("formAction"),o!==null&&(A=o,F=null));var Y=new lc("action","action",null,g,k);s.push({event:Y,listeners:[{instance:null,listener:function(){if(g.defaultPrevented){if(Gs!==0){var ie=F?cv(k,F):new FormData(k);Zh(f,{pending:!0,data:ie,method:k.method,action:A},null,ie)}}else typeof A=="function"&&(Y.preventDefault(),ie=F?cv(k,F):new FormData(k),Zh(f,{pending:!0,data:ie,method:k.method,action:A},A,ie))},currentTarget:k}]})}}for(var If=0;If<gh.length;If++){var Mf=gh[If],YE=Mf.toLowerCase(),XE=Mf[0].toUpperCase()+Mf.slice(1);jr(YE,"on"+XE)}jr(zx,"onAnimationEnd"),jr(Hx,"onAnimationIteration"),jr(Ux,"onAnimationStart"),jr("dblclick","onDoubleClick"),jr("focusin","onFocus"),jr("focusout","onBlur"),jr(hE,"onTransitionRun"),jr(fE,"onTransitionStart"),jr(mE,"onTransitionCancel"),jr(Fx,"onTransitionEnd"),sa("onMouseEnter",["mouseout","mouseover"]),sa("onMouseLeave",["mouseout","mouseover"]),sa("onPointerEnter",["pointerout","pointerover"]),sa("onPointerLeave",["pointerout","pointerover"]),mi("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),mi("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),mi("onBeforeInput",["compositionend","keypress","textInput","paste"]),mi("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),mi("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),mi("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Xo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),QE=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Xo));function uv(s,o){o=(o&4)!==0;for(var f=0;f<s.length;f++){var g=s[f],k=g.event;g=g.listeners;e:{var A=void 0;if(o)for(var F=g.length-1;0<=F;F--){var Y=g[F],ie=Y.instance,ge=Y.currentTarget;if(Y=Y.listener,ie!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){dc(ke)}k.currentTarget=null,A=ie}else for(F=0;F<g.length;F++){if(Y=g[F],ie=Y.instance,ge=Y.currentTarget,Y=Y.listener,ie!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){dc(ke)}k.currentTarget=null,A=ie}}}}function ft(s,o){var f=o[Kd];f===void 0&&(f=o[Kd]=new Set);var g=s+"__bubble";f.has(g)||(dv(o,s,2,!1),f.add(g))}function Pf(s,o,f){var g=0;o&&(g|=4),dv(f,s,g,o)}var Qc="_reactListening"+Math.random().toString(36).slice(2);function Bf(s){if(!s[Qc]){s[Qc]=!0,sx.forEach(function(f){f!=="selectionchange"&&(QE.has(f)||Pf(f,!1,s),Pf(f,!0,s))});var o=s.nodeType===9?s:s.ownerDocument;o===null||o[Qc]||(o[Qc]=!0,Pf("selectionchange",!1,o))}}function dv(s,o,f,g){switch(zv(o)){case 2:var k=kj;break;case 8:k=Ej;break;default:k=Zf}f=k.bind(null,o,f,s),k=void 0,!rh||o!=="touchstart"&&o!=="touchmove"&&o!=="wheel"||(k=!0),g?k!==void 0?s.addEventListener(o,f,{capture:!0,passive:k}):s.addEventListener(o,f,!0):k!==void 0?s.addEventListener(o,f,{passive:k}):s.addEventListener(o,f,!1)}function $f(s,o,f,g,k){var A=g;if((o&1)===0&&(o&2)===0&&g!==null)e:for(;;){if(g===null)return;var F=g.tag;if(F===3||F===4){var Y=g.stateNode.containerInfo;if(Y===k)break;if(F===4)for(F=g.return;F!==null;){var ie=F.tag;if((ie===3||ie===4)&&F.stateNode.containerInfo===k)return;F=F.return}for(;Y!==null;){if(F=ta(Y),F===null)return;if(ie=F.tag,ie===5||ie===6||ie===26||ie===27){g=A=F;continue e}Y=Y.parentNode}}g=g.return}gx(function(){var ge=A,ke=th(f),Ae=[];e:{var ye=Vx.get(s);if(ye!==void 0){var be=lc,Ge=s;switch(s){case"keypress":if(ac(f)===0)break e;case"keydown":case"keyup":be=V2;break;case"focusin":Ge="focus",be=oh;break;case"focusout":Ge="blur",be=oh;break;case"beforeblur":case"afterblur":be=oh;break;case"click":if(f.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":be=bx;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":be=D2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":be=q2;break;case zx:case Hx:case Ux:be=I2;break;case Fx:be=Y2;break;case"scroll":case"scrollend":be=A2;break;case"wheel":be=Q2;break;case"copy":case"cut":case"paste":be=P2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":be=_x;break;case"toggle":case"beforetoggle":be=Z2}var et=(o&4)!==0,Dt=!et&&(s==="scroll"||s==="scrollend"),ue=et?ye!==null?ye+"Capture":null:ye;et=[];for(var le=ge,pe;le!==null;){var Ee=le;if(pe=Ee.stateNode,Ee=Ee.tag,Ee!==5&&Ee!==26&&Ee!==27||pe===null||ue===null||(Ee=yo(le,ue),Ee!=null&&et.push(Qo(le,Ee,pe))),Dt)break;le=le.return}0<et.length&&(ye=new be(ye,Ge,null,f,ke),Ae.push({event:ye,listeners:et}))}}if((o&7)===0){e:{if(ye=s==="mouseover"||s==="pointerover",be=s==="mouseout"||s==="pointerout",ye&&f!==eh&&(Ge=f.relatedTarget||f.fromElement)&&(ta(Ge)||Ge[ea]))break e;if((be||ye)&&(ye=ke.window===ke?ke:(ye=ke.ownerDocument)?ye.defaultView||ye.parentWindow:window,be?(Ge=f.relatedTarget||f.toElement,be=ge,Ge=Ge?ta(Ge):null,Ge!==null&&(Dt=l(Ge),et=Ge.tag,Ge!==Dt||et!==5&&et!==27&&et!==6)&&(Ge=null)):(be=null,Ge=ge),be!==Ge)){if(et=bx,Ee="onMouseLeave",ue="onMouseEnter",le="mouse",(s==="pointerout"||s==="pointerover")&&(et=_x,Ee="onPointerLeave",ue="onPointerEnter",le="pointer"),Dt=be==null?ye:xo(be),pe=Ge==null?ye:xo(Ge),ye=new et(Ee,le+"leave",be,f,ke),ye.target=Dt,ye.relatedTarget=pe,Ee=null,ta(ke)===ge&&(et=new et(ue,le+"enter",Ge,f,ke),et.target=pe,et.relatedTarget=Dt,Ee=et),Dt=Ee,be&&Ge)t:{for(et=JE,ue=be,le=Ge,pe=0,Ee=ue;Ee;Ee=et(Ee))pe++;Ee=0;for(var Xe=le;Xe;Xe=et(Xe))Ee++;for(;0<pe-Ee;)ue=et(ue),pe--;for(;0<Ee-pe;)le=et(le),Ee--;for(;pe--;){if(ue===le||le!==null&&ue===le.alternate){et=ue;break t}ue=et(ue),le=et(le)}et=null}else et=null;be!==null&&hv(Ae,ye,be,et,!1),Ge!==null&&Dt!==null&&hv(Ae,Dt,Ge,et,!0)}}e:{if(ye=ge?xo(ge):window,be=ye.nodeName&&ye.nodeName.toLowerCase(),be==="select"||be==="input"&&ye.type==="file")var Ct=Tx;else if(jx(ye))if(Ax)Ct=cE;else{Ct=oE;var We=aE}else be=ye.nodeName,!be||be.toLowerCase()!=="input"||ye.type!=="checkbox"&&ye.type!=="radio"?ge&&Zd(ge.elementType)&&(Ct=Tx):Ct=lE;if(Ct&&(Ct=Ct(s,ge))){Nx(Ae,Ct,f,ke);break e}We&&We(s,ye,ge),s==="focusout"&&ge&&ye.type==="number"&&ge.memoizedProps.value!=null&&Jd(ye,"number",ye.value)}switch(We=ge?xo(ge):window,s){case"focusin":(jx(We)||We.contentEditable==="true")&&(ua=We,fh=ge,Eo=null);break;case"focusout":Eo=fh=ua=null;break;case"mousedown":mh=!0;break;case"contextmenu":case"mouseup":case"dragend":mh=!1,Bx(Ae,f,ke);break;case"selectionchange":if(dE)break;case"keydown":case"keyup":Bx(Ae,f,ke)}var lt;if(ch)e:{switch(s){case"compositionstart":var bt="onCompositionStart";break e;case"compositionend":bt="onCompositionEnd";break e;case"compositionupdate":bt="onCompositionUpdate";break e}bt=void 0}else ca?kx(s,f)&&(bt="onCompositionEnd"):s==="keydown"&&f.keyCode===229&&(bt="onCompositionStart");bt&&(Sx&&f.locale!=="ko"&&(ca||bt!=="onCompositionStart"?bt==="onCompositionEnd"&&ca&&(lt=xx()):(Ts=ke,sh="value"in Ts?Ts.value:Ts.textContent,ca=!0)),We=Jc(ge,bt),0<We.length&&(bt=new vx(bt,s,null,f,ke),Ae.push({event:bt,listeners:We}),lt?bt.data=lt:(lt=Ex(f),lt!==null&&(bt.data=lt)))),(lt=tE?nE(s,f):rE(s,f))&&(bt=Jc(ge,"onBeforeInput"),0<bt.length&&(We=new vx("onBeforeInput","beforeinput",null,f,ke),Ae.push({event:We,listeners:bt}),We.data=lt)),KE(Ae,s,ge,f,ke)}uv(Ae,o)})}function Qo(s,o,f){return{instance:s,listener:o,currentTarget:f}}function Jc(s,o){for(var f=o+"Capture",g=[];s!==null;){var k=s,A=k.stateNode;if(k=k.tag,k!==5&&k!==26&&k!==27||A===null||(k=yo(s,f),k!=null&&g.unshift(Qo(s,k,A)),k=yo(s,o),k!=null&&g.push(Qo(s,k,A))),s.tag===3)return g;s=s.return}return[]}function JE(s){if(s===null)return null;do s=s.return;while(s&&s.tag!==5&&s.tag!==27);return s||null}function hv(s,o,f,g,k){for(var A=o._reactName,F=[];f!==null&&f!==g;){var Y=f,ie=Y.alternate,ge=Y.stateNode;if(Y=Y.tag,ie!==null&&ie===g)break;Y!==5&&Y!==26&&Y!==27||ge===null||(ie=ge,k?(ge=yo(f,A),ge!=null&&F.unshift(Qo(f,ge,ie))):k||(ge=yo(f,A),ge!=null&&F.push(Qo(f,ge,ie)))),f=f.return}F.length!==0&&s.push({event:o,listeners:F})}var ZE=/\r\n?/g,ej=/\u0000|\uFFFD/g;function fv(s){return(typeof s=="string"?s:""+s).replace(ZE,`
49
+ `+g.stack}}var Qe=Object.prototype.hasOwnProperty,fe=e.unstable_scheduleCallback,ce=e.unstable_cancelCallback,de=e.unstable_shouldYield,he=e.unstable_requestPaint,De=e.unstable_now,Ue=e.unstable_getCurrentPriorityLevel,re=e.unstable_ImmediatePriority,_e=e.unstable_UserBlockingPriority,Le=e.unstable_NormalPriority,He=e.unstable_LowPriority,qe=e.unstable_IdlePriority,Ke=e.log,tt=e.unstable_setDisableYieldValue,_t=null,It=null;function Yt(s){if(typeof Ke=="function"&&tt(s),It&&typeof It.setStrictMode=="function")try{It.setStrictMode(_t,s)}catch{}}var dt=Math.clz32?Math.clz32:Jt,kn=Math.log,jt=Math.LN2;function Jt(s){return s>>>=0,s===0?32:31-(kn(s)/jt|0)|0}var Br=256,ve=262144,Ve=4194304;function ae(s){var o=s&42;if(o!==0)return o;switch(s&-s){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:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function me(s,o,f){var g=s.pendingLanes;if(g===0)return 0;var k=0,A=s.suspendedLanes,F=s.pingedLanes;s=s.warmLanes;var Y=g&134217727;return Y!==0?(g=Y&~A,g!==0?k=ae(g):(F&=Y,F!==0?k=ae(F):f||(f=Y&~s,f!==0&&(k=ae(f))))):(Y=g&~A,Y!==0?k=ae(Y):F!==0?k=ae(F):f||(f=g&~s,f!==0&&(k=ae(f)))),k===0?0:o!==0&&o!==k&&(o&A)===0&&(A=k&-k,f=o&-o,A>=f||A===32&&(f&4194048)!==0)?o:k}function Ie(s,o){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&o)===0}function gt(s,o){switch(s){case 1:case 2:case 4:case 8:case 64:return o+250;case 16:case 32: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 o+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function vn(){var s=Ve;return Ve<<=1,(Ve&62914560)===0&&(Ve=4194304),s}function rn(s){for(var o=[],f=0;31>f;f++)o.push(s);return o}function Ce(s,o){s.pendingLanes|=o,o!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function Ne(s,o,f,g,k,A){var F=s.pendingLanes;s.pendingLanes=f,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=f,s.entangledLanes&=f,s.errorRecoveryDisabledLanes&=f,s.shellSuspendCounter=0;var Y=s.entanglements,ie=s.expirationTimes,ge=s.hiddenUpdates;for(f=F&~f;0<f;){var ke=31-dt(f),Ae=1<<ke;Y[ke]=0,ie[ke]=-1;var ye=ge[ke];if(ye!==null)for(ge[ke]=null,ke=0;ke<ye.length;ke++){var be=ye[ke];be!==null&&(be.lane&=-536870913)}f&=~Ae}g!==0&&Fe(s,g,0),A!==0&&k===0&&s.tag!==0&&(s.suspendedLanes|=A&~(F&~o))}function Fe(s,o,f){s.pendingLanes|=o,s.suspendedLanes&=~o;var g=31-dt(o);s.entangledLanes|=o,s.entanglements[g]=s.entanglements[g]|1073741824|f&261930}function Ye(s,o){var f=s.entangledLanes|=o;for(s=s.entanglements;f;){var g=31-dt(f),k=1<<g;k&o|s[g]&o&&(s[g]|=o),f&=~k}}function ot(s,o){var f=o&-o;return f=(f&42)!==0?1:nt(f),(f&(s.suspendedLanes|o))!==0?0:f}function nt(s){switch(s){case 2:s=1;break;case 8:s=4;break;case 32:s=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:s=128;break;case 268435456:s=134217728;break;default:s=0}return s}function xt(s){return s&=-s,2<s?8<s?(s&134217727)!==0?32:268435456:8:2}function sn(){var s=Z.p;return s!==0?s:(s=window.event,s===void 0?32:zv(s.type))}function Zt(s,o){var f=Z.p;try{return Z.p=s,o()}finally{Z.p=f}}var qt=Math.random().toString(36).slice(2),an="__reactFiber$"+qt,Fn="__reactProps$"+qt,ea="__reactContainer$"+qt,Kd="__reactEvents$"+qt,_2="__reactListeners$"+qt,S2="__reactHandles$"+qt,rx="__reactResources$"+qt,go="__reactMarker$"+qt;function Yd(s){delete s[an],delete s[Fn],delete s[Kd],delete s[_2],delete s[S2]}function ta(s){var o=s[an];if(o)return o;for(var f=s.parentNode;f;){if(o=f[ea]||f[an]){if(f=o.alternate,o.child!==null||f!==null&&f.child!==null)for(s=Cv(s);s!==null;){if(f=s[an])return f;s=Cv(s)}return o}s=f,f=s.parentNode}return null}function na(s){if(s=s[an]||s[ea]){var o=s.tag;if(o===5||o===6||o===13||o===31||o===26||o===27||o===3)return s}return null}function xo(s){var o=s.tag;if(o===5||o===26||o===27||o===6)return s.stateNode;throw Error(r(33))}function ra(s){var o=s[rx];return o||(o=s[rx]={hoistableStyles:new Map,hoistableScripts:new Map}),o}function _n(s){s[go]=!0}var sx=new Set,ix={};function mi(s,o){sa(s,o),sa(s+"Capture",o)}function sa(s,o){for(ix[s]=o,s=0;s<o.length;s++)sx.add(o[s])}var w2=RegExp("^[: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]*$"),ax={},ox={};function C2(s){return Qe.call(ox,s)?!0:Qe.call(ax,s)?!1:w2.test(s)?ox[s]=!0:(ax[s]=!0,!1)}function tc(s,o,f){if(C2(o))if(f===null)s.removeAttribute(o);else{switch(typeof f){case"undefined":case"function":case"symbol":s.removeAttribute(o);return;case"boolean":var g=o.toLowerCase().slice(0,5);if(g!=="data-"&&g!=="aria-"){s.removeAttribute(o);return}}s.setAttribute(o,""+f)}}function nc(s,o,f){if(f===null)s.removeAttribute(o);else{switch(typeof f){case"undefined":case"function":case"symbol":case"boolean":s.removeAttribute(o);return}s.setAttribute(o,""+f)}}function Jr(s,o,f,g){if(g===null)s.removeAttribute(f);else{switch(typeof g){case"undefined":case"function":case"symbol":case"boolean":s.removeAttribute(f);return}s.setAttributeNS(o,f,""+g)}}function dr(s){switch(typeof s){case"bigint":case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function lx(s){var o=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(o==="checkbox"||o==="radio")}function k2(s,o,f){var g=Object.getOwnPropertyDescriptor(s.constructor.prototype,o);if(!s.hasOwnProperty(o)&&typeof g<"u"&&typeof g.get=="function"&&typeof g.set=="function"){var k=g.get,A=g.set;return Object.defineProperty(s,o,{configurable:!0,get:function(){return k.call(this)},set:function(F){f=""+F,A.call(this,F)}}),Object.defineProperty(s,o,{enumerable:g.enumerable}),{getValue:function(){return f},setValue:function(F){f=""+F},stopTracking:function(){s._valueTracker=null,delete s[o]}}}}function Xd(s){if(!s._valueTracker){var o=lx(s)?"checked":"value";s._valueTracker=k2(s,o,""+s[o])}}function cx(s){if(!s)return!1;var o=s._valueTracker;if(!o)return!0;var f=o.getValue(),g="";return s&&(g=lx(s)?s.checked?"true":"false":s.value),s=g,s!==f?(o.setValue(s),!0):!1}function rc(s){if(s=s||(typeof document<"u"?document:void 0),typeof s>"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var E2=/[\n"\\]/g;function hr(s){return s.replace(E2,function(o){return"\\"+o.charCodeAt(0).toString(16)+" "})}function Qd(s,o,f,g,k,A,F,Y){s.name="",F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"?s.type=F:s.removeAttribute("type"),o!=null?F==="number"?(o===0&&s.value===""||s.value!=o)&&(s.value=""+dr(o)):s.value!==""+dr(o)&&(s.value=""+dr(o)):F!=="submit"&&F!=="reset"||s.removeAttribute("value"),o!=null?Jd(s,F,dr(o)):f!=null?Jd(s,F,dr(f)):g!=null&&s.removeAttribute("value"),k==null&&A!=null&&(s.defaultChecked=!!A),k!=null&&(s.checked=k&&typeof k!="function"&&typeof k!="symbol"),Y!=null&&typeof Y!="function"&&typeof Y!="symbol"&&typeof Y!="boolean"?s.name=""+dr(Y):s.removeAttribute("name")}function ux(s,o,f,g,k,A,F,Y){if(A!=null&&typeof A!="function"&&typeof A!="symbol"&&typeof A!="boolean"&&(s.type=A),o!=null||f!=null){if(!(A!=="submit"&&A!=="reset"||o!=null)){Xd(s);return}f=f!=null?""+dr(f):"",o=o!=null?""+dr(o):f,Y||o===s.value||(s.value=o),s.defaultValue=o}g=g??k,g=typeof g!="function"&&typeof g!="symbol"&&!!g,s.checked=Y?s.checked:!!g,s.defaultChecked=!!g,F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"&&(s.name=F),Xd(s)}function Jd(s,o,f){o==="number"&&rc(s.ownerDocument)===s||s.defaultValue===""+f||(s.defaultValue=""+f)}function ia(s,o,f,g){if(s=s.options,o){o={};for(var k=0;k<f.length;k++)o["$"+f[k]]=!0;for(f=0;f<s.length;f++)k=o.hasOwnProperty("$"+s[f].value),s[f].selected!==k&&(s[f].selected=k),k&&g&&(s[f].defaultSelected=!0)}else{for(f=""+dr(f),o=null,k=0;k<s.length;k++){if(s[k].value===f){s[k].selected=!0,g&&(s[k].defaultSelected=!0);return}o!==null||s[k].disabled||(o=s[k])}o!==null&&(o.selected=!0)}}function dx(s,o,f){if(o!=null&&(o=""+dr(o),o!==s.value&&(s.value=o),f==null)){s.defaultValue!==o&&(s.defaultValue=o);return}s.defaultValue=f!=null?""+dr(f):""}function hx(s,o,f,g){if(o==null){if(g!=null){if(f!=null)throw Error(r(92));if(V(g)){if(1<g.length)throw Error(r(93));g=g[0]}f=g}f==null&&(f=""),o=f}f=dr(o),s.defaultValue=f,g=s.textContent,g===f&&g!==""&&g!==null&&(s.value=g),Xd(s)}function aa(s,o){if(o){var f=s.firstChild;if(f&&f===s.lastChild&&f.nodeType===3){f.nodeValue=o;return}}s.textContent=o}var j2=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function fx(s,o,f){var g=o.indexOf("--")===0;f==null||typeof f=="boolean"||f===""?g?s.setProperty(o,""):o==="float"?s.cssFloat="":s[o]="":g?s.setProperty(o,f):typeof f!="number"||f===0||j2.has(o)?o==="float"?s.cssFloat=f:s[o]=(""+f).trim():s[o]=f+"px"}function mx(s,o,f){if(o!=null&&typeof o!="object")throw Error(r(62));if(s=s.style,f!=null){for(var g in f)!f.hasOwnProperty(g)||o!=null&&o.hasOwnProperty(g)||(g.indexOf("--")===0?s.setProperty(g,""):g==="float"?s.cssFloat="":s[g]="");for(var k in o)g=o[k],o.hasOwnProperty(k)&&f[k]!==g&&fx(s,k,g)}else for(var A in o)o.hasOwnProperty(A)&&fx(s,A,o[A])}function Zd(s){if(s.indexOf("-")===-1)return!1;switch(s){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 N2=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),T2=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function sc(s){return T2.test(""+s)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":s}function Zr(){}var eh=null;function th(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var oa=null,la=null;function px(s){var o=na(s);if(o&&(s=o.stateNode)){var f=s[Fn]||null;e:switch(s=o.stateNode,o.type){case"input":if(Qd(s,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name),o=f.name,f.type==="radio"&&o!=null){for(f=s;f.parentNode;)f=f.parentNode;for(f=f.querySelectorAll('input[name="'+hr(""+o)+'"][type="radio"]'),o=0;o<f.length;o++){var g=f[o];if(g!==s&&g.form===s.form){var k=g[Fn]||null;if(!k)throw Error(r(90));Qd(g,k.value,k.defaultValue,k.defaultValue,k.checked,k.defaultChecked,k.type,k.name)}}for(o=0;o<f.length;o++)g=f[o],g.form===s.form&&cx(g)}break e;case"textarea":dx(s,f.value,f.defaultValue);break e;case"select":o=f.value,o!=null&&ia(s,!!f.multiple,o,!1)}}}var nh=!1;function gx(s,o,f){if(nh)return s(o,f);nh=!0;try{var g=s(o);return g}finally{if(nh=!1,(oa!==null||la!==null)&&(Gc(),oa&&(o=oa,s=la,la=oa=null,px(o),s)))for(o=0;o<s.length;o++)px(s[o])}}function yo(s,o){var f=s.stateNode;if(f===null)return null;var g=f[Fn]||null;if(g===null)return null;f=g[o];e:switch(o){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(g=!g.disabled)||(s=s.type,g=!(s==="button"||s==="input"||s==="select"||s==="textarea")),s=!g;break e;default:s=!1}if(s)return null;if(f&&typeof f!="function")throw Error(r(231,o,typeof f));return f}var es=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),rh=!1;if(es)try{var bo={};Object.defineProperty(bo,"passive",{get:function(){rh=!0}}),window.addEventListener("test",bo,bo),window.removeEventListener("test",bo,bo)}catch{rh=!1}var Ts=null,sh=null,ic=null;function xx(){if(ic)return ic;var s,o=sh,f=o.length,g,k="value"in Ts?Ts.value:Ts.textContent,A=k.length;for(s=0;s<f&&o[s]===k[s];s++);var F=f-s;for(g=1;g<=F&&o[f-g]===k[A-g];g++);return ic=k.slice(s,1<g?1-g:void 0)}function ac(s){var o=s.keyCode;return"charCode"in s?(s=s.charCode,s===0&&o===13&&(s=13)):s=o,s===10&&(s=13),32<=s||s===13?s:0}function oc(){return!0}function yx(){return!1}function Vn(s){function o(f,g,k,A,F){this._reactName=f,this._targetInst=k,this.type=g,this.nativeEvent=A,this.target=F,this.currentTarget=null;for(var Y in s)s.hasOwnProperty(Y)&&(f=s[Y],this[Y]=f?f(A):A[Y]);return this.isDefaultPrevented=(A.defaultPrevented!=null?A.defaultPrevented:A.returnValue===!1)?oc:yx,this.isPropagationStopped=yx,this}return m(o.prototype,{preventDefault:function(){this.defaultPrevented=!0;var f=this.nativeEvent;f&&(f.preventDefault?f.preventDefault():typeof f.returnValue!="unknown"&&(f.returnValue=!1),this.isDefaultPrevented=oc)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=oc)},persist:function(){},isPersistent:oc}),o}var pi={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(s){return s.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},lc=Vn(pi),vo=m({},pi,{view:0,detail:0}),A2=Vn(vo),ih,ah,_o,cc=m({},vo,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:lh,button:0,buttons:0,relatedTarget:function(s){return s.relatedTarget===void 0?s.fromElement===s.srcElement?s.toElement:s.fromElement:s.relatedTarget},movementX:function(s){return"movementX"in s?s.movementX:(s!==_o&&(_o&&s.type==="mousemove"?(ih=s.screenX-_o.screenX,ah=s.screenY-_o.screenY):ah=ih=0,_o=s),ih)},movementY:function(s){return"movementY"in s?s.movementY:ah}}),bx=Vn(cc),L2=m({},cc,{dataTransfer:0}),D2=Vn(L2),R2=m({},vo,{relatedTarget:0}),oh=Vn(R2),O2=m({},pi,{animationName:0,elapsedTime:0,pseudoElement:0}),I2=Vn(O2),M2=m({},pi,{clipboardData:function(s){return"clipboardData"in s?s.clipboardData:window.clipboardData}}),P2=Vn(M2),B2=m({},pi,{data:0}),vx=Vn(B2),$2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},z2={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},H2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function U2(s){var o=this.nativeEvent;return o.getModifierState?o.getModifierState(s):(s=H2[s])?!!o[s]:!1}function lh(){return U2}var F2=m({},vo,{key:function(s){if(s.key){var o=$2[s.key]||s.key;if(o!=="Unidentified")return o}return s.type==="keypress"?(s=ac(s),s===13?"Enter":String.fromCharCode(s)):s.type==="keydown"||s.type==="keyup"?z2[s.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:lh,charCode:function(s){return s.type==="keypress"?ac(s):0},keyCode:function(s){return s.type==="keydown"||s.type==="keyup"?s.keyCode:0},which:function(s){return s.type==="keypress"?ac(s):s.type==="keydown"||s.type==="keyup"?s.keyCode:0}}),V2=Vn(F2),G2=m({},cc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),_x=Vn(G2),W2=m({},vo,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:lh}),q2=Vn(W2),K2=m({},pi,{propertyName:0,elapsedTime:0,pseudoElement:0}),Y2=Vn(K2),X2=m({},cc,{deltaX:function(s){return"deltaX"in s?s.deltaX:"wheelDeltaX"in s?-s.wheelDeltaX:0},deltaY:function(s){return"deltaY"in s?s.deltaY:"wheelDeltaY"in s?-s.wheelDeltaY:"wheelDelta"in s?-s.wheelDelta:0},deltaZ:0,deltaMode:0}),Q2=Vn(X2),J2=m({},pi,{newState:0,oldState:0}),Z2=Vn(J2),eE=[9,13,27,32],ch=es&&"CompositionEvent"in window,So=null;es&&"documentMode"in document&&(So=document.documentMode);var tE=es&&"TextEvent"in window&&!So,Sx=es&&(!ch||So&&8<So&&11>=So),wx=" ",Cx=!1;function kx(s,o){switch(s){case"keyup":return eE.indexOf(o.keyCode)!==-1;case"keydown":return o.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ex(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var ca=!1;function nE(s,o){switch(s){case"compositionend":return Ex(o);case"keypress":return o.which!==32?null:(Cx=!0,wx);case"textInput":return s=o.data,s===wx&&Cx?null:s;default:return null}}function rE(s,o){if(ca)return s==="compositionend"||!ch&&kx(s,o)?(s=xx(),ic=sh=Ts=null,ca=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(o.ctrlKey||o.altKey||o.metaKey)||o.ctrlKey&&o.altKey){if(o.char&&1<o.char.length)return o.char;if(o.which)return String.fromCharCode(o.which)}return null;case"compositionend":return Sx&&o.locale!=="ko"?null:o.data;default:return null}}var sE={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function jx(s){var o=s&&s.nodeName&&s.nodeName.toLowerCase();return o==="input"?!!sE[s.type]:o==="textarea"}function Nx(s,o,f,g){oa?la?la.push(g):la=[g]:oa=g,o=Jc(o,"onChange"),0<o.length&&(f=new lc("onChange","change",null,f,g),s.push({event:f,listeners:o}))}var wo=null,Co=null;function iE(s){uv(s,0)}function uc(s){var o=xo(s);if(cx(o))return s}function Tx(s,o){if(s==="change")return o}var Ax=!1;if(es){var uh;if(es){var dh="oninput"in document;if(!dh){var Lx=document.createElement("div");Lx.setAttribute("oninput","return;"),dh=typeof Lx.oninput=="function"}uh=dh}else uh=!1;Ax=uh&&(!document.documentMode||9<document.documentMode)}function Dx(){wo&&(wo.detachEvent("onpropertychange",Rx),Co=wo=null)}function Rx(s){if(s.propertyName==="value"&&uc(Co)){var o=[];Nx(o,Co,s,th(s)),gx(iE,o)}}function aE(s,o,f){s==="focusin"?(Dx(),wo=o,Co=f,wo.attachEvent("onpropertychange",Rx)):s==="focusout"&&Dx()}function oE(s){if(s==="selectionchange"||s==="keyup"||s==="keydown")return uc(Co)}function lE(s,o){if(s==="click")return uc(o)}function cE(s,o){if(s==="input"||s==="change")return uc(o)}function uE(s,o){return s===o&&(s!==0||1/s===1/o)||s!==s&&o!==o}var tr=typeof Object.is=="function"?Object.is:uE;function ko(s,o){if(tr(s,o))return!0;if(typeof s!="object"||s===null||typeof o!="object"||o===null)return!1;var f=Object.keys(s),g=Object.keys(o);if(f.length!==g.length)return!1;for(g=0;g<f.length;g++){var k=f[g];if(!Qe.call(o,k)||!tr(s[k],o[k]))return!1}return!0}function Ox(s){for(;s&&s.firstChild;)s=s.firstChild;return s}function Ix(s,o){var f=Ox(s);s=0;for(var g;f;){if(f.nodeType===3){if(g=s+f.textContent.length,s<=o&&g>=o)return{node:f,offset:o-s};s=g}e:{for(;f;){if(f.nextSibling){f=f.nextSibling;break e}f=f.parentNode}f=void 0}f=Ox(f)}}function Mx(s,o){return s&&o?s===o?!0:s&&s.nodeType===3?!1:o&&o.nodeType===3?Mx(s,o.parentNode):"contains"in s?s.contains(o):s.compareDocumentPosition?!!(s.compareDocumentPosition(o)&16):!1:!1}function Px(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var o=rc(s.document);o instanceof s.HTMLIFrameElement;){try{var f=typeof o.contentWindow.location.href=="string"}catch{f=!1}if(f)s=o.contentWindow;else break;o=rc(s.document)}return o}function hh(s){var o=s&&s.nodeName&&s.nodeName.toLowerCase();return o&&(o==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||o==="textarea"||s.contentEditable==="true")}var dE=es&&"documentMode"in document&&11>=document.documentMode,ua=null,fh=null,Eo=null,mh=!1;function Bx(s,o,f){var g=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;mh||ua==null||ua!==rc(g)||(g=ua,"selectionStart"in g&&hh(g)?g={start:g.selectionStart,end:g.selectionEnd}:(g=(g.ownerDocument&&g.ownerDocument.defaultView||window).getSelection(),g={anchorNode:g.anchorNode,anchorOffset:g.anchorOffset,focusNode:g.focusNode,focusOffset:g.focusOffset}),Eo&&ko(Eo,g)||(Eo=g,g=Jc(fh,"onSelect"),0<g.length&&(o=new lc("onSelect","select",null,o,f),s.push({event:o,listeners:g}),o.target=ua)))}function gi(s,o){var f={};return f[s.toLowerCase()]=o.toLowerCase(),f["Webkit"+s]="webkit"+o,f["Moz"+s]="moz"+o,f}var da={animationend:gi("Animation","AnimationEnd"),animationiteration:gi("Animation","AnimationIteration"),animationstart:gi("Animation","AnimationStart"),transitionrun:gi("Transition","TransitionRun"),transitionstart:gi("Transition","TransitionStart"),transitioncancel:gi("Transition","TransitionCancel"),transitionend:gi("Transition","TransitionEnd")},ph={},$x={};es&&($x=document.createElement("div").style,"AnimationEvent"in window||(delete da.animationend.animation,delete da.animationiteration.animation,delete da.animationstart.animation),"TransitionEvent"in window||delete da.transitionend.transition);function xi(s){if(ph[s])return ph[s];if(!da[s])return s;var o=da[s],f;for(f in o)if(o.hasOwnProperty(f)&&f in $x)return ph[s]=o[f];return s}var zx=xi("animationend"),Hx=xi("animationiteration"),Ux=xi("animationstart"),hE=xi("transitionrun"),fE=xi("transitionstart"),mE=xi("transitioncancel"),Fx=xi("transitionend"),Vx=new Map,gh="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");gh.push("scrollEnd");function jr(s,o){Vx.set(s,o),mi(o,[s])}var dc=typeof reportError=="function"?reportError:function(s){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var o=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof s=="object"&&s!==null&&typeof s.message=="string"?String(s.message):String(s),error:s});if(!window.dispatchEvent(o))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",s);return}console.error(s)},fr=[],ha=0,xh=0;function hc(){for(var s=ha,o=xh=ha=0;o<s;){var f=fr[o];fr[o++]=null;var g=fr[o];fr[o++]=null;var k=fr[o];fr[o++]=null;var A=fr[o];if(fr[o++]=null,g!==null&&k!==null){var F=g.pending;F===null?k.next=k:(k.next=F.next,F.next=k),g.pending=k}A!==0&&Gx(f,k,A)}}function fc(s,o,f,g){fr[ha++]=s,fr[ha++]=o,fr[ha++]=f,fr[ha++]=g,xh|=g,s.lanes|=g,s=s.alternate,s!==null&&(s.lanes|=g)}function yh(s,o,f,g){return fc(s,o,f,g),mc(s)}function yi(s,o){return fc(s,null,null,o),mc(s)}function Gx(s,o,f){s.lanes|=f;var g=s.alternate;g!==null&&(g.lanes|=f);for(var k=!1,A=s.return;A!==null;)A.childLanes|=f,g=A.alternate,g!==null&&(g.childLanes|=f),A.tag===22&&(s=A.stateNode,s===null||s._visibility&1||(k=!0)),s=A,A=A.return;return s.tag===3?(A=s.stateNode,k&&o!==null&&(k=31-dt(f),s=A.hiddenUpdates,g=s[k],g===null?s[k]=[o]:g.push(o),o.lane=f|536870912),A):null}function mc(s){if(50<Ko)throw Ko=0,Nf=null,Error(r(185));for(var o=s.return;o!==null;)s=o,o=s.return;return s.tag===3?s.stateNode:null}var fa={};function pE(s,o,f,g){this.tag=s,this.key=f,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=o,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=g,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function nr(s,o,f,g){return new pE(s,o,f,g)}function bh(s){return s=s.prototype,!(!s||!s.isReactComponent)}function ts(s,o){var f=s.alternate;return f===null?(f=nr(s.tag,o,s.key,s.mode),f.elementType=s.elementType,f.type=s.type,f.stateNode=s.stateNode,f.alternate=s,s.alternate=f):(f.pendingProps=o,f.type=s.type,f.flags=0,f.subtreeFlags=0,f.deletions=null),f.flags=s.flags&65011712,f.childLanes=s.childLanes,f.lanes=s.lanes,f.child=s.child,f.memoizedProps=s.memoizedProps,f.memoizedState=s.memoizedState,f.updateQueue=s.updateQueue,o=s.dependencies,f.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext},f.sibling=s.sibling,f.index=s.index,f.ref=s.ref,f.refCleanup=s.refCleanup,f}function Wx(s,o){s.flags&=65011714;var f=s.alternate;return f===null?(s.childLanes=0,s.lanes=o,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=f.childLanes,s.lanes=f.lanes,s.child=f.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=f.memoizedProps,s.memoizedState=f.memoizedState,s.updateQueue=f.updateQueue,s.type=f.type,o=f.dependencies,s.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext}),s}function pc(s,o,f,g,k,A){var F=0;if(g=s,typeof s=="function")bh(s)&&(F=1);else if(typeof s=="string")F=vj(s,f,ee.current)?26:s==="html"||s==="head"||s==="body"?27:5;else e:switch(s){case I:return s=nr(31,f,o,k),s.elementType=I,s.lanes=A,s;case C:return bi(f.children,k,A,o);case _:F=8,k|=24;break;case S:return s=nr(12,f,o,k|2),s.elementType=S,s.lanes=A,s;case j:return s=nr(13,f,o,k),s.elementType=j,s.lanes=A,s;case T:return s=nr(19,f,o,k),s.elementType=T,s.lanes=A,s;default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case b:F=10;break e;case v:F=9;break e;case E:F=11;break e;case D:F=14;break e;case L:F=16,g=null;break e}F=29,f=Error(r(130,s===null?"null":typeof s,"")),g=null}return o=nr(F,f,o,k),o.elementType=s,o.type=g,o.lanes=A,o}function bi(s,o,f,g){return s=nr(7,s,g,o),s.lanes=f,s}function vh(s,o,f){return s=nr(6,s,null,o),s.lanes=f,s}function qx(s){var o=nr(18,null,null,0);return o.stateNode=s,o}function _h(s,o,f){return o=nr(4,s.children!==null?s.children:[],s.key,o),o.lanes=f,o.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},o}var Kx=new WeakMap;function mr(s,o){if(typeof s=="object"&&s!==null){var f=Kx.get(s);return f!==void 0?f:(o={value:s,source:o,stack:rt(o)},Kx.set(s,o),o)}return{value:s,source:o,stack:rt(o)}}var ma=[],pa=0,gc=null,jo=0,pr=[],gr=0,As=null,$r=1,zr="";function ns(s,o){ma[pa++]=jo,ma[pa++]=gc,gc=s,jo=o}function Yx(s,o,f){pr[gr++]=$r,pr[gr++]=zr,pr[gr++]=As,As=s;var g=$r;s=zr;var k=32-dt(g)-1;g&=~(1<<k),f+=1;var A=32-dt(o)+k;if(30<A){var F=k-k%5;A=(g&(1<<F)-1).toString(32),g>>=F,k-=F,$r=1<<32-dt(o)+k|f<<k|g,zr=A+s}else $r=1<<A|f<<k|g,zr=s}function Sh(s){s.return!==null&&(ns(s,1),Yx(s,1,0))}function wh(s){for(;s===gc;)gc=ma[--pa],ma[pa]=null,jo=ma[--pa],ma[pa]=null;for(;s===As;)As=pr[--gr],pr[gr]=null,zr=pr[--gr],pr[gr]=null,$r=pr[--gr],pr[gr]=null}function Xx(s,o){pr[gr++]=$r,pr[gr++]=zr,pr[gr++]=As,$r=o.id,zr=o.overflow,As=s}var En=null,Vt=null,vt=!1,Ls=null,xr=!1,Ch=Error(r(519));function Ds(s){var o=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw No(mr(o,s)),Ch}function Qx(s){var o=s.stateNode,f=s.type,g=s.memoizedProps;switch(o[an]=s,o[Fn]=g,f){case"dialog":ft("cancel",o),ft("close",o);break;case"iframe":case"object":case"embed":ft("load",o);break;case"video":case"audio":for(f=0;f<Xo.length;f++)ft(Xo[f],o);break;case"source":ft("error",o);break;case"img":case"image":case"link":ft("error",o),ft("load",o);break;case"details":ft("toggle",o);break;case"input":ft("invalid",o),ux(o,g.value,g.defaultValue,g.checked,g.defaultChecked,g.type,g.name,!0);break;case"select":ft("invalid",o);break;case"textarea":ft("invalid",o),hx(o,g.value,g.defaultValue,g.children)}f=g.children,typeof f!="string"&&typeof f!="number"&&typeof f!="bigint"||o.textContent===""+f||g.suppressHydrationWarning===!0||mv(o.textContent,f)?(g.popover!=null&&(ft("beforetoggle",o),ft("toggle",o)),g.onScroll!=null&&ft("scroll",o),g.onScrollEnd!=null&&ft("scrollend",o),g.onClick!=null&&(o.onclick=Zr),o=!0):o=!1,o||Ds(s,!0)}function Jx(s){for(En=s.return;En;)switch(En.tag){case 5:case 31:case 13:xr=!1;return;case 27:case 3:xr=!0;return;default:En=En.return}}function ga(s){if(s!==En)return!1;if(!vt)return Jx(s),vt=!0,!1;var o=s.tag,f;if((f=o!==3&&o!==27)&&((f=o===5)&&(f=s.type,f=!(f!=="form"&&f!=="button")||Ff(s.type,s.memoizedProps)),f=!f),f&&Vt&&Ds(s),Jx(s),o===13){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Vt=wv(s)}else if(o===31){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Vt=wv(s)}else o===27?(o=Vt,Ws(s.type)?(s=Kf,Kf=null,Vt=s):Vt=o):Vt=En?br(s.stateNode.nextSibling):null;return!0}function vi(){Vt=En=null,vt=!1}function kh(){var s=Ls;return s!==null&&(Kn===null?Kn=s:Kn.push.apply(Kn,s),Ls=null),s}function No(s){Ls===null?Ls=[s]:Ls.push(s)}var Eh=M(null),_i=null,rs=null;function Rs(s,o,f){z(Eh,o._currentValue),o._currentValue=f}function ss(s){s._currentValue=Eh.current,q(Eh)}function jh(s,o,f){for(;s!==null;){var g=s.alternate;if((s.childLanes&o)!==o?(s.childLanes|=o,g!==null&&(g.childLanes|=o)):g!==null&&(g.childLanes&o)!==o&&(g.childLanes|=o),s===f)break;s=s.return}}function Nh(s,o,f,g){var k=s.child;for(k!==null&&(k.return=s);k!==null;){var A=k.dependencies;if(A!==null){var F=k.child;A=A.firstContext;e:for(;A!==null;){var Y=A;A=k;for(var ie=0;ie<o.length;ie++)if(Y.context===o[ie]){A.lanes|=f,Y=A.alternate,Y!==null&&(Y.lanes|=f),jh(A.return,f,s),g||(F=null);break e}A=Y.next}}else if(k.tag===18){if(F=k.return,F===null)throw Error(r(341));F.lanes|=f,A=F.alternate,A!==null&&(A.lanes|=f),jh(F,f,s),F=null}else F=k.child;if(F!==null)F.return=k;else for(F=k;F!==null;){if(F===s){F=null;break}if(k=F.sibling,k!==null){k.return=F.return,F=k;break}F=F.return}k=F}}function xa(s,o,f,g){s=null;for(var k=o,A=!1;k!==null;){if(!A){if((k.flags&524288)!==0)A=!0;else if((k.flags&262144)!==0)break}if(k.tag===10){var F=k.alternate;if(F===null)throw Error(r(387));if(F=F.memoizedProps,F!==null){var Y=k.type;tr(k.pendingProps.value,F.value)||(s!==null?s.push(Y):s=[Y])}}else if(k===K.current){if(F=k.alternate,F===null)throw Error(r(387));F.memoizedState.memoizedState!==k.memoizedState.memoizedState&&(s!==null?s.push(tl):s=[tl])}k=k.return}s!==null&&Nh(o,s,f,g),o.flags|=262144}function xc(s){for(s=s.firstContext;s!==null;){if(!tr(s.context._currentValue,s.memoizedValue))return!0;s=s.next}return!1}function Si(s){_i=s,rs=null,s=s.dependencies,s!==null&&(s.firstContext=null)}function jn(s){return Zx(_i,s)}function yc(s,o){return _i===null&&Si(s),Zx(s,o)}function Zx(s,o){var f=o._currentValue;if(o={context:o,memoizedValue:f,next:null},rs===null){if(s===null)throw Error(r(308));rs=o,s.dependencies={lanes:0,firstContext:o},s.flags|=524288}else rs=rs.next=o;return f}var gE=typeof AbortController<"u"?AbortController:function(){var s=[],o=this.signal={aborted:!1,addEventListener:function(f,g){s.push(g)}};this.abort=function(){o.aborted=!0,s.forEach(function(f){return f()})}},xE=e.unstable_scheduleCallback,yE=e.unstable_NormalPriority,on={$$typeof:b,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Th(){return{controller:new gE,data:new Map,refCount:0}}function To(s){s.refCount--,s.refCount===0&&xE(yE,function(){s.controller.abort()})}var Ao=null,Ah=0,ya=0,ba=null;function bE(s,o){if(Ao===null){var f=Ao=[];Ah=0,ya=Of(),ba={status:"pending",value:void 0,then:function(g){f.push(g)}}}return Ah++,o.then(ey,ey),o}function ey(){if(--Ah===0&&Ao!==null){ba!==null&&(ba.status="fulfilled");var s=Ao;Ao=null,ya=0,ba=null;for(var o=0;o<s.length;o++)(0,s[o])()}}function vE(s,o){var f=[],g={status:"pending",value:null,reason:null,then:function(k){f.push(k)}};return s.then(function(){g.status="fulfilled",g.value=o;for(var k=0;k<f.length;k++)(0,f[k])(o)},function(k){for(g.status="rejected",g.reason=k,k=0;k<f.length;k++)(0,f[k])(void 0)}),g}var ty=G.S;G.S=function(s,o){Bb=De(),typeof o=="object"&&o!==null&&typeof o.then=="function"&&bE(s,o),ty!==null&&ty(s,o)};var wi=M(null);function Lh(){var s=wi.current;return s!==null?s:Mt.pooledCache}function bc(s,o){o===null?z(wi,wi.current):z(wi,o.pool)}function ny(){var s=Lh();return s===null?null:{parent:on._currentValue,pool:s}}var va=Error(r(460)),Dh=Error(r(474)),vc=Error(r(542)),_c={then:function(){}};function ry(s){return s=s.status,s==="fulfilled"||s==="rejected"}function sy(s,o,f){switch(f=s[f],f===void 0?s.push(o):f!==o&&(o.then(Zr,Zr),o=f),o.status){case"fulfilled":return o.value;case"rejected":throw s=o.reason,ay(s),s;default:if(typeof o.status=="string")o.then(Zr,Zr);else{if(s=Mt,s!==null&&100<s.shellSuspendCounter)throw Error(r(482));s=o,s.status="pending",s.then(function(g){if(o.status==="pending"){var k=o;k.status="fulfilled",k.value=g}},function(g){if(o.status==="pending"){var k=o;k.status="rejected",k.reason=g}})}switch(o.status){case"fulfilled":return o.value;case"rejected":throw s=o.reason,ay(s),s}throw ki=o,va}}function Ci(s){try{var o=s._init;return o(s._payload)}catch(f){throw f!==null&&typeof f=="object"&&typeof f.then=="function"?(ki=f,va):f}}var ki=null;function iy(){if(ki===null)throw Error(r(459));var s=ki;return ki=null,s}function ay(s){if(s===va||s===vc)throw Error(r(483))}var _a=null,Lo=0;function Sc(s){var o=Lo;return Lo+=1,_a===null&&(_a=[]),sy(_a,s,o)}function Do(s,o){o=o.props.ref,s.ref=o!==void 0?o:null}function wc(s,o){throw o.$$typeof===x?Error(r(525)):(s=Object.prototype.toString.call(o),Error(r(31,s==="[object Object]"?"object with keys {"+Object.keys(o).join(", ")+"}":s)))}function oy(s){function o(ue,le){if(s){var pe=ue.deletions;pe===null?(ue.deletions=[le],ue.flags|=16):pe.push(le)}}function f(ue,le){if(!s)return null;for(;le!==null;)o(ue,le),le=le.sibling;return null}function g(ue){for(var le=new Map;ue!==null;)ue.key!==null?le.set(ue.key,ue):le.set(ue.index,ue),ue=ue.sibling;return le}function k(ue,le){return ue=ts(ue,le),ue.index=0,ue.sibling=null,ue}function A(ue,le,pe){return ue.index=pe,s?(pe=ue.alternate,pe!==null?(pe=pe.index,pe<le?(ue.flags|=67108866,le):pe):(ue.flags|=67108866,le)):(ue.flags|=1048576,le)}function F(ue){return s&&ue.alternate===null&&(ue.flags|=67108866),ue}function Y(ue,le,pe,Ee){return le===null||le.tag!==6?(le=vh(pe,ue.mode,Ee),le.return=ue,le):(le=k(le,pe),le.return=ue,le)}function ie(ue,le,pe,Ee){var Xe=pe.type;return Xe===C?ke(ue,le,pe.props.children,Ee,pe.key):le!==null&&(le.elementType===Xe||typeof Xe=="object"&&Xe!==null&&Xe.$$typeof===L&&Ci(Xe)===le.type)?(le=k(le,pe.props),Do(le,pe),le.return=ue,le):(le=pc(pe.type,pe.key,pe.props,null,ue.mode,Ee),Do(le,pe),le.return=ue,le)}function ge(ue,le,pe,Ee){return le===null||le.tag!==4||le.stateNode.containerInfo!==pe.containerInfo||le.stateNode.implementation!==pe.implementation?(le=_h(pe,ue.mode,Ee),le.return=ue,le):(le=k(le,pe.children||[]),le.return=ue,le)}function ke(ue,le,pe,Ee,Xe){return le===null||le.tag!==7?(le=bi(pe,ue.mode,Ee,Xe),le.return=ue,le):(le=k(le,pe),le.return=ue,le)}function Ae(ue,le,pe){if(typeof le=="string"&&le!==""||typeof le=="number"||typeof le=="bigint")return le=vh(""+le,ue.mode,pe),le.return=ue,le;if(typeof le=="object"&&le!==null){switch(le.$$typeof){case y:return pe=pc(le.type,le.key,le.props,null,ue.mode,pe),Do(pe,le),pe.return=ue,pe;case w:return le=_h(le,ue.mode,pe),le.return=ue,le;case L:return le=Ci(le),Ae(ue,le,pe)}if(V(le)||H(le))return le=bi(le,ue.mode,pe,null),le.return=ue,le;if(typeof le.then=="function")return Ae(ue,Sc(le),pe);if(le.$$typeof===b)return Ae(ue,yc(ue,le),pe);wc(ue,le)}return null}function ye(ue,le,pe,Ee){var Xe=le!==null?le.key:null;if(typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint")return Xe!==null?null:Y(ue,le,""+pe,Ee);if(typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case y:return pe.key===Xe?ie(ue,le,pe,Ee):null;case w:return pe.key===Xe?ge(ue,le,pe,Ee):null;case L:return pe=Ci(pe),ye(ue,le,pe,Ee)}if(V(pe)||H(pe))return Xe!==null?null:ke(ue,le,pe,Ee,null);if(typeof pe.then=="function")return ye(ue,le,Sc(pe),Ee);if(pe.$$typeof===b)return ye(ue,le,yc(ue,pe),Ee);wc(ue,pe)}return null}function be(ue,le,pe,Ee,Xe){if(typeof Ee=="string"&&Ee!==""||typeof Ee=="number"||typeof Ee=="bigint")return ue=ue.get(pe)||null,Y(le,ue,""+Ee,Xe);if(typeof Ee=="object"&&Ee!==null){switch(Ee.$$typeof){case y:return ue=ue.get(Ee.key===null?pe:Ee.key)||null,ie(le,ue,Ee,Xe);case w:return ue=ue.get(Ee.key===null?pe:Ee.key)||null,ge(le,ue,Ee,Xe);case L:return Ee=Ci(Ee),be(ue,le,pe,Ee,Xe)}if(V(Ee)||H(Ee))return ue=ue.get(pe)||null,ke(le,ue,Ee,Xe,null);if(typeof Ee.then=="function")return be(ue,le,pe,Sc(Ee),Xe);if(Ee.$$typeof===b)return be(ue,le,pe,yc(le,Ee),Xe);wc(le,Ee)}return null}function Ge(ue,le,pe,Ee){for(var Xe=null,Ct=null,We=le,lt=le=0,bt=null;We!==null&&lt<pe.length;lt++){We.index>lt?(bt=We,We=null):bt=We.sibling;var kt=ye(ue,We,pe[lt],Ee);if(kt===null){We===null&&(We=bt);break}s&&We&&kt.alternate===null&&o(ue,We),le=A(kt,le,lt),Ct===null?Xe=kt:Ct.sibling=kt,Ct=kt,We=bt}if(lt===pe.length)return f(ue,We),vt&&ns(ue,lt),Xe;if(We===null){for(;lt<pe.length;lt++)We=Ae(ue,pe[lt],Ee),We!==null&&(le=A(We,le,lt),Ct===null?Xe=We:Ct.sibling=We,Ct=We);return vt&&ns(ue,lt),Xe}for(We=g(We);lt<pe.length;lt++)bt=be(We,ue,lt,pe[lt],Ee),bt!==null&&(s&&bt.alternate!==null&&We.delete(bt.key===null?lt:bt.key),le=A(bt,le,lt),Ct===null?Xe=bt:Ct.sibling=bt,Ct=bt);return s&&We.forEach(function(Qs){return o(ue,Qs)}),vt&&ns(ue,lt),Xe}function et(ue,le,pe,Ee){if(pe==null)throw Error(r(151));for(var Xe=null,Ct=null,We=le,lt=le=0,bt=null,kt=pe.next();We!==null&&!kt.done;lt++,kt=pe.next()){We.index>lt?(bt=We,We=null):bt=We.sibling;var Qs=ye(ue,We,kt.value,Ee);if(Qs===null){We===null&&(We=bt);break}s&&We&&Qs.alternate===null&&o(ue,We),le=A(Qs,le,lt),Ct===null?Xe=Qs:Ct.sibling=Qs,Ct=Qs,We=bt}if(kt.done)return f(ue,We),vt&&ns(ue,lt),Xe;if(We===null){for(;!kt.done;lt++,kt=pe.next())kt=Ae(ue,kt.value,Ee),kt!==null&&(le=A(kt,le,lt),Ct===null?Xe=kt:Ct.sibling=kt,Ct=kt);return vt&&ns(ue,lt),Xe}for(We=g(We);!kt.done;lt++,kt=pe.next())kt=be(We,ue,lt,kt.value,Ee),kt!==null&&(s&&kt.alternate!==null&&We.delete(kt.key===null?lt:kt.key),le=A(kt,le,lt),Ct===null?Xe=kt:Ct.sibling=kt,Ct=kt);return s&&We.forEach(function(Lj){return o(ue,Lj)}),vt&&ns(ue,lt),Xe}function Dt(ue,le,pe,Ee){if(typeof pe=="object"&&pe!==null&&pe.type===C&&pe.key===null&&(pe=pe.props.children),typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case y:e:{for(var Xe=pe.key;le!==null;){if(le.key===Xe){if(Xe=pe.type,Xe===C){if(le.tag===7){f(ue,le.sibling),Ee=k(le,pe.props.children),Ee.return=ue,ue=Ee;break e}}else if(le.elementType===Xe||typeof Xe=="object"&&Xe!==null&&Xe.$$typeof===L&&Ci(Xe)===le.type){f(ue,le.sibling),Ee=k(le,pe.props),Do(Ee,pe),Ee.return=ue,ue=Ee;break e}f(ue,le);break}else o(ue,le);le=le.sibling}pe.type===C?(Ee=bi(pe.props.children,ue.mode,Ee,pe.key),Ee.return=ue,ue=Ee):(Ee=pc(pe.type,pe.key,pe.props,null,ue.mode,Ee),Do(Ee,pe),Ee.return=ue,ue=Ee)}return F(ue);case w:e:{for(Xe=pe.key;le!==null;){if(le.key===Xe)if(le.tag===4&&le.stateNode.containerInfo===pe.containerInfo&&le.stateNode.implementation===pe.implementation){f(ue,le.sibling),Ee=k(le,pe.children||[]),Ee.return=ue,ue=Ee;break e}else{f(ue,le);break}else o(ue,le);le=le.sibling}Ee=_h(pe,ue.mode,Ee),Ee.return=ue,ue=Ee}return F(ue);case L:return pe=Ci(pe),Dt(ue,le,pe,Ee)}if(V(pe))return Ge(ue,le,pe,Ee);if(H(pe)){if(Xe=H(pe),typeof Xe!="function")throw Error(r(150));return pe=Xe.call(pe),et(ue,le,pe,Ee)}if(typeof pe.then=="function")return Dt(ue,le,Sc(pe),Ee);if(pe.$$typeof===b)return Dt(ue,le,yc(ue,pe),Ee);wc(ue,pe)}return typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint"?(pe=""+pe,le!==null&&le.tag===6?(f(ue,le.sibling),Ee=k(le,pe),Ee.return=ue,ue=Ee):(f(ue,le),Ee=vh(pe,ue.mode,Ee),Ee.return=ue,ue=Ee),F(ue)):f(ue,le)}return function(ue,le,pe,Ee){try{Lo=0;var Xe=Dt(ue,le,pe,Ee);return _a=null,Xe}catch(We){if(We===va||We===vc)throw We;var Ct=nr(29,We,null,ue.mode);return Ct.lanes=Ee,Ct.return=ue,Ct}finally{}}}var Ei=oy(!0),ly=oy(!1),Os=!1;function Rh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Oh(s,o){s=s.updateQueue,o.updateQueue===s&&(o.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function Is(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function Ms(s,o,f){var g=s.updateQueue;if(g===null)return null;if(g=g.shared,(Et&2)!==0){var k=g.pending;return k===null?o.next=o:(o.next=k.next,k.next=o),g.pending=o,o=mc(s),Gx(s,null,f),o}return fc(s,g,o,f),mc(s)}function Ro(s,o,f){if(o=o.updateQueue,o!==null&&(o=o.shared,(f&4194048)!==0)){var g=o.lanes;g&=s.pendingLanes,f|=g,o.lanes=f,Ye(s,f)}}function Ih(s,o){var f=s.updateQueue,g=s.alternate;if(g!==null&&(g=g.updateQueue,f===g)){var k=null,A=null;if(f=f.firstBaseUpdate,f!==null){do{var F={lane:f.lane,tag:f.tag,payload:f.payload,callback:null,next:null};A===null?k=A=F:A=A.next=F,f=f.next}while(f!==null);A===null?k=A=o:A=A.next=o}else k=A=o;f={baseState:g.baseState,firstBaseUpdate:k,lastBaseUpdate:A,shared:g.shared,callbacks:g.callbacks},s.updateQueue=f;return}s=f.lastBaseUpdate,s===null?f.firstBaseUpdate=o:s.next=o,f.lastBaseUpdate=o}var Mh=!1;function Oo(){if(Mh){var s=ba;if(s!==null)throw s}}function Io(s,o,f,g){Mh=!1;var k=s.updateQueue;Os=!1;var A=k.firstBaseUpdate,F=k.lastBaseUpdate,Y=k.shared.pending;if(Y!==null){k.shared.pending=null;var ie=Y,ge=ie.next;ie.next=null,F===null?A=ge:F.next=ge,F=ie;var ke=s.alternate;ke!==null&&(ke=ke.updateQueue,Y=ke.lastBaseUpdate,Y!==F&&(Y===null?ke.firstBaseUpdate=ge:Y.next=ge,ke.lastBaseUpdate=ie))}if(A!==null){var Ae=k.baseState;F=0,ke=ge=ie=null,Y=A;do{var ye=Y.lane&-536870913,be=ye!==Y.lane;if(be?(yt&ye)===ye:(g&ye)===ye){ye!==0&&ye===ya&&(Mh=!0),ke!==null&&(ke=ke.next={lane:0,tag:Y.tag,payload:Y.payload,callback:null,next:null});e:{var Ge=s,et=Y;ye=o;var Dt=f;switch(et.tag){case 1:if(Ge=et.payload,typeof Ge=="function"){Ae=Ge.call(Dt,Ae,ye);break e}Ae=Ge;break e;case 3:Ge.flags=Ge.flags&-65537|128;case 0:if(Ge=et.payload,ye=typeof Ge=="function"?Ge.call(Dt,Ae,ye):Ge,ye==null)break e;Ae=m({},Ae,ye);break e;case 2:Os=!0}}ye=Y.callback,ye!==null&&(s.flags|=64,be&&(s.flags|=8192),be=k.callbacks,be===null?k.callbacks=[ye]:be.push(ye))}else be={lane:ye,tag:Y.tag,payload:Y.payload,callback:Y.callback,next:null},ke===null?(ge=ke=be,ie=Ae):ke=ke.next=be,F|=ye;if(Y=Y.next,Y===null){if(Y=k.shared.pending,Y===null)break;be=Y,Y=be.next,be.next=null,k.lastBaseUpdate=be,k.shared.pending=null}}while(!0);ke===null&&(ie=Ae),k.baseState=ie,k.firstBaseUpdate=ge,k.lastBaseUpdate=ke,A===null&&(k.shared.lanes=0),Hs|=F,s.lanes=F,s.memoizedState=Ae}}function cy(s,o){if(typeof s!="function")throw Error(r(191,s));s.call(o)}function uy(s,o){var f=s.callbacks;if(f!==null)for(s.callbacks=null,s=0;s<f.length;s++)cy(f[s],o)}var Sa=M(null),Cc=M(0);function dy(s,o){s=fs,z(Cc,s),z(Sa,o),fs=s|o.baseLanes}function Ph(){z(Cc,fs),z(Sa,Sa.current)}function Bh(){fs=Cc.current,q(Sa),q(Cc)}var rr=M(null),yr=null;function Ps(s){var o=s.alternate;z(en,en.current&1),z(rr,s),yr===null&&(o===null||Sa.current!==null||o.memoizedState!==null)&&(yr=s)}function $h(s){z(en,en.current),z(rr,s),yr===null&&(yr=s)}function hy(s){s.tag===22?(z(en,en.current),z(rr,s),yr===null&&(yr=s)):Bs()}function Bs(){z(en,en.current),z(rr,rr.current)}function sr(s){q(rr),yr===s&&(yr=null),q(en)}var en=M(0);function kc(s){for(var o=s;o!==null;){if(o.tag===13){var f=o.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||Wf(f)||qf(f)))return o}else if(o.tag===19&&(o.memoizedProps.revealOrder==="forwards"||o.memoizedProps.revealOrder==="backwards"||o.memoizedProps.revealOrder==="unstable_legacy-backwards"||o.memoizedProps.revealOrder==="together")){if((o.flags&128)!==0)return o}else if(o.child!==null){o.child.return=o,o=o.child;continue}if(o===s)break;for(;o.sibling===null;){if(o.return===null||o.return===s)return null;o=o.return}o.sibling.return=o.return,o=o.sibling}return null}var is=0,at=null,At=null,ln=null,Ec=!1,wa=!1,ji=!1,jc=0,Mo=0,Ca=null,_E=0;function Xt(){throw Error(r(321))}function zh(s,o){if(o===null)return!1;for(var f=0;f<o.length&&f<s.length;f++)if(!tr(s[f],o[f]))return!1;return!0}function Hh(s,o,f,g,k,A){return is=A,at=o,o.memoizedState=null,o.updateQueue=null,o.lanes=0,G.H=s===null||s.memoizedState===null?Yy:nf,ji=!1,A=f(g,k),ji=!1,wa&&(A=my(o,f,g,k)),fy(s),A}function fy(s){G.H=$o;var o=At!==null&&At.next!==null;if(is=0,ln=At=at=null,Ec=!1,Mo=0,Ca=null,o)throw Error(r(300));s===null||cn||(s=s.dependencies,s!==null&&xc(s)&&(cn=!0))}function my(s,o,f,g){at=s;var k=0;do{if(wa&&(Ca=null),Mo=0,wa=!1,25<=k)throw Error(r(301));if(k+=1,ln=At=null,s.updateQueue!=null){var A=s.updateQueue;A.lastEffect=null,A.events=null,A.stores=null,A.memoCache!=null&&(A.memoCache.index=0)}G.H=Xy,A=o(f,g)}while(wa);return A}function SE(){var s=G.H,o=s.useState()[0];return o=typeof o.then=="function"?Po(o):o,s=s.useState()[0],(At!==null?At.memoizedState:null)!==s&&(at.flags|=1024),o}function Uh(){var s=jc!==0;return jc=0,s}function Fh(s,o,f){o.updateQueue=s.updateQueue,o.flags&=-2053,s.lanes&=~f}function Vh(s){if(Ec){for(s=s.memoizedState;s!==null;){var o=s.queue;o!==null&&(o.pending=null),s=s.next}Ec=!1}is=0,ln=At=at=null,wa=!1,Mo=jc=0,Ca=null}function Bn(){var s={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ln===null?at.memoizedState=ln=s:ln=ln.next=s,ln}function tn(){if(At===null){var s=at.alternate;s=s!==null?s.memoizedState:null}else s=At.next;var o=ln===null?at.memoizedState:ln.next;if(o!==null)ln=o,At=s;else{if(s===null)throw at.alternate===null?Error(r(467)):Error(r(310));At=s,s={memoizedState:At.memoizedState,baseState:At.baseState,baseQueue:At.baseQueue,queue:At.queue,next:null},ln===null?at.memoizedState=ln=s:ln=ln.next=s}return ln}function Nc(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Po(s){var o=Mo;return Mo+=1,Ca===null&&(Ca=[]),s=sy(Ca,s,o),o=at,(ln===null?o.memoizedState:ln.next)===null&&(o=o.alternate,G.H=o===null||o.memoizedState===null?Yy:nf),s}function Tc(s){if(s!==null&&typeof s=="object"){if(typeof s.then=="function")return Po(s);if(s.$$typeof===b)return jn(s)}throw Error(r(438,String(s)))}function Gh(s){var o=null,f=at.updateQueue;if(f!==null&&(o=f.memoCache),o==null){var g=at.alternate;g!==null&&(g=g.updateQueue,g!==null&&(g=g.memoCache,g!=null&&(o={data:g.data.map(function(k){return k.slice()}),index:0})))}if(o==null&&(o={data:[],index:0}),f===null&&(f=Nc(),at.updateQueue=f),f.memoCache=o,f=o.data[o.index],f===void 0)for(f=o.data[o.index]=Array(s),g=0;g<s;g++)f[g]=P;return o.index++,f}function as(s,o){return typeof o=="function"?o(s):o}function Ac(s){var o=tn();return Wh(o,At,s)}function Wh(s,o,f){var g=s.queue;if(g===null)throw Error(r(311));g.lastRenderedReducer=f;var k=s.baseQueue,A=g.pending;if(A!==null){if(k!==null){var F=k.next;k.next=A.next,A.next=F}o.baseQueue=k=A,g.pending=null}if(A=s.baseState,k===null)s.memoizedState=A;else{o=k.next;var Y=F=null,ie=null,ge=o,ke=!1;do{var Ae=ge.lane&-536870913;if(Ae!==ge.lane?(yt&Ae)===Ae:(is&Ae)===Ae){var ye=ge.revertLane;if(ye===0)ie!==null&&(ie=ie.next={lane:0,revertLane:0,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null}),Ae===ya&&(ke=!0);else if((is&ye)===ye){ge=ge.next,ye===ya&&(ke=!0);continue}else Ae={lane:0,revertLane:ge.revertLane,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},ie===null?(Y=ie=Ae,F=A):ie=ie.next=Ae,at.lanes|=ye,Hs|=ye;Ae=ge.action,ji&&f(A,Ae),A=ge.hasEagerState?ge.eagerState:f(A,Ae)}else ye={lane:Ae,revertLane:ge.revertLane,gesture:ge.gesture,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},ie===null?(Y=ie=ye,F=A):ie=ie.next=ye,at.lanes|=Ae,Hs|=Ae;ge=ge.next}while(ge!==null&&ge!==o);if(ie===null?F=A:ie.next=Y,!tr(A,s.memoizedState)&&(cn=!0,ke&&(f=ba,f!==null)))throw f;s.memoizedState=A,s.baseState=F,s.baseQueue=ie,g.lastRenderedState=A}return k===null&&(g.lanes=0),[s.memoizedState,g.dispatch]}function qh(s){var o=tn(),f=o.queue;if(f===null)throw Error(r(311));f.lastRenderedReducer=s;var g=f.dispatch,k=f.pending,A=o.memoizedState;if(k!==null){f.pending=null;var F=k=k.next;do A=s(A,F.action),F=F.next;while(F!==k);tr(A,o.memoizedState)||(cn=!0),o.memoizedState=A,o.baseQueue===null&&(o.baseState=A),f.lastRenderedState=A}return[A,g]}function py(s,o,f){var g=at,k=tn(),A=vt;if(A){if(f===void 0)throw Error(r(407));f=f()}else f=o();var F=!tr((At||k).memoizedState,f);if(F&&(k.memoizedState=f,cn=!0),k=k.queue,Xh(yy.bind(null,g,k,s),[s]),k.getSnapshot!==o||F||ln!==null&&ln.memoizedState.tag&1){if(g.flags|=2048,ka(9,{destroy:void 0},xy.bind(null,g,k,f,o),null),Mt===null)throw Error(r(349));A||(is&127)!==0||gy(g,o,f)}return f}function gy(s,o,f){s.flags|=16384,s={getSnapshot:o,value:f},o=at.updateQueue,o===null?(o=Nc(),at.updateQueue=o,o.stores=[s]):(f=o.stores,f===null?o.stores=[s]:f.push(s))}function xy(s,o,f,g){o.value=f,o.getSnapshot=g,by(o)&&vy(s)}function yy(s,o,f){return f(function(){by(o)&&vy(s)})}function by(s){var o=s.getSnapshot;s=s.value;try{var f=o();return!tr(s,f)}catch{return!0}}function vy(s){var o=yi(s,2);o!==null&&Yn(o,s,2)}function Kh(s){var o=Bn();if(typeof s=="function"){var f=s;if(s=f(),ji){Yt(!0);try{f()}finally{Yt(!1)}}}return o.memoizedState=o.baseState=s,o.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:s},o}function _y(s,o,f,g){return s.baseState=f,Wh(s,At,typeof g=="function"?g:as)}function wE(s,o,f,g,k){if(Rc(s))throw Error(r(485));if(s=o.action,s!==null){var A={payload:k,action:s,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(F){A.listeners.push(F)}};G.T!==null?f(!0):A.isTransition=!1,g(A),f=o.pending,f===null?(A.next=o.pending=A,Sy(o,A)):(A.next=f.next,o.pending=f.next=A)}}function Sy(s,o){var f=o.action,g=o.payload,k=s.state;if(o.isTransition){var A=G.T,F={};G.T=F;try{var Y=f(k,g),ie=G.S;ie!==null&&ie(F,Y),wy(s,o,Y)}catch(ge){Yh(s,o,ge)}finally{A!==null&&F.types!==null&&(A.types=F.types),G.T=A}}else try{A=f(k,g),wy(s,o,A)}catch(ge){Yh(s,o,ge)}}function wy(s,o,f){f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(function(g){Cy(s,o,g)},function(g){return Yh(s,o,g)}):Cy(s,o,f)}function Cy(s,o,f){o.status="fulfilled",o.value=f,ky(o),s.state=f,o=s.pending,o!==null&&(f=o.next,f===o?s.pending=null:(f=f.next,o.next=f,Sy(s,f)))}function Yh(s,o,f){var g=s.pending;if(s.pending=null,g!==null){g=g.next;do o.status="rejected",o.reason=f,ky(o),o=o.next;while(o!==g)}s.action=null}function ky(s){s=s.listeners;for(var o=0;o<s.length;o++)(0,s[o])()}function Ey(s,o){return o}function jy(s,o){if(vt){var f=Mt.formState;if(f!==null){e:{var g=at;if(vt){if(Vt){t:{for(var k=Vt,A=xr;k.nodeType!==8;){if(!A){k=null;break t}if(k=br(k.nextSibling),k===null){k=null;break t}}A=k.data,k=A==="F!"||A==="F"?k:null}if(k){Vt=br(k.nextSibling),g=k.data==="F!";break e}}Ds(g)}g=!1}g&&(o=f[0])}}return f=Bn(),f.memoizedState=f.baseState=o,g={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ey,lastRenderedState:o},f.queue=g,f=Wy.bind(null,at,g),g.dispatch=f,g=Kh(!1),A=tf.bind(null,at,!1,g.queue),g=Bn(),k={state:o,dispatch:null,action:s,pending:null},g.queue=k,f=wE.bind(null,at,k,A,f),k.dispatch=f,g.memoizedState=s,[o,f,!1]}function Ny(s){var o=tn();return Ty(o,At,s)}function Ty(s,o,f){if(o=Wh(s,o,Ey)[0],s=Ac(as)[0],typeof o=="object"&&o!==null&&typeof o.then=="function")try{var g=Po(o)}catch(F){throw F===va?vc:F}else g=o;o=tn();var k=o.queue,A=k.dispatch;return f!==o.memoizedState&&(at.flags|=2048,ka(9,{destroy:void 0},CE.bind(null,k,f),null)),[g,A,s]}function CE(s,o){s.action=o}function Ay(s){var o=tn(),f=At;if(f!==null)return Ty(o,f,s);tn(),o=o.memoizedState,f=tn();var g=f.queue.dispatch;return f.memoizedState=s,[o,g,!1]}function ka(s,o,f,g){return s={tag:s,create:f,deps:g,inst:o,next:null},o=at.updateQueue,o===null&&(o=Nc(),at.updateQueue=o),f=o.lastEffect,f===null?o.lastEffect=s.next=s:(g=f.next,f.next=s,s.next=g,o.lastEffect=s),s}function Ly(){return tn().memoizedState}function Lc(s,o,f,g){var k=Bn();at.flags|=s,k.memoizedState=ka(1|o,{destroy:void 0},f,g===void 0?null:g)}function Dc(s,o,f,g){var k=tn();g=g===void 0?null:g;var A=k.memoizedState.inst;At!==null&&g!==null&&zh(g,At.memoizedState.deps)?k.memoizedState=ka(o,A,f,g):(at.flags|=s,k.memoizedState=ka(1|o,A,f,g))}function Dy(s,o){Lc(8390656,8,s,o)}function Xh(s,o){Dc(2048,8,s,o)}function kE(s){at.flags|=4;var o=at.updateQueue;if(o===null)o=Nc(),at.updateQueue=o,o.events=[s];else{var f=o.events;f===null?o.events=[s]:f.push(s)}}function Ry(s){var o=tn().memoizedState;return kE({ref:o,nextImpl:s}),function(){if((Et&2)!==0)throw Error(r(440));return o.impl.apply(void 0,arguments)}}function Oy(s,o){return Dc(4,2,s,o)}function Iy(s,o){return Dc(4,4,s,o)}function My(s,o){if(typeof o=="function"){s=s();var f=o(s);return function(){typeof f=="function"?f():o(null)}}if(o!=null)return s=s(),o.current=s,function(){o.current=null}}function Py(s,o,f){f=f!=null?f.concat([s]):null,Dc(4,4,My.bind(null,o,s),f)}function Qh(){}function By(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;return o!==null&&zh(o,g[1])?g[0]:(f.memoizedState=[s,o],s)}function $y(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;if(o!==null&&zh(o,g[1]))return g[0];if(g=s(),ji){Yt(!0);try{s()}finally{Yt(!1)}}return f.memoizedState=[g,o],g}function Jh(s,o,f){return f===void 0||(is&1073741824)!==0&&(yt&261930)===0?s.memoizedState=o:(s.memoizedState=f,s=zb(),at.lanes|=s,Hs|=s,f)}function zy(s,o,f,g){return tr(f,o)?f:Sa.current!==null?(s=Jh(s,f,g),tr(s,o)||(cn=!0),s):(is&42)===0||(is&1073741824)!==0&&(yt&261930)===0?(cn=!0,s.memoizedState=f):(s=zb(),at.lanes|=s,Hs|=s,o)}function Hy(s,o,f,g,k){var A=Z.p;Z.p=A!==0&&8>A?A:8;var F=G.T,Y={};G.T=Y,tf(s,!1,o,f);try{var ie=k(),ge=G.S;if(ge!==null&&ge(Y,ie),ie!==null&&typeof ie=="object"&&typeof ie.then=="function"){var ke=vE(ie,g);Bo(s,o,ke,or(s))}else Bo(s,o,g,or(s))}catch(Ae){Bo(s,o,{then:function(){},status:"rejected",reason:Ae},or())}finally{Z.p=A,F!==null&&Y.types!==null&&(F.types=Y.types),G.T=F}}function EE(){}function Zh(s,o,f,g){if(s.tag!==5)throw Error(r(476));var k=Uy(s).queue;Hy(s,k,o,X,f===null?EE:function(){return Fy(s),f(g)})}function Uy(s){var o=s.memoizedState;if(o!==null)return o;o={memoizedState:X,baseState:X,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:X},next:null};var f={};return o.next={memoizedState:f,baseState:f,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:f},next:null},s.memoizedState=o,s=s.alternate,s!==null&&(s.memoizedState=o),o}function Fy(s){var o=Uy(s);o.next===null&&(o=s.alternate.memoizedState),Bo(s,o.next.queue,{},or())}function ef(){return jn(tl)}function Vy(){return tn().memoizedState}function Gy(){return tn().memoizedState}function jE(s){for(var o=s.return;o!==null;){switch(o.tag){case 24:case 3:var f=or();s=Is(f);var g=Ms(o,s,f);g!==null&&(Yn(g,o,f),Ro(g,o,f)),o={cache:Th()},s.payload=o;return}o=o.return}}function NE(s,o,f){var g=or();f={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null},Rc(s)?qy(o,f):(f=yh(s,o,f,g),f!==null&&(Yn(f,s,g),Ky(f,o,g)))}function Wy(s,o,f){var g=or();Bo(s,o,f,g)}function Bo(s,o,f,g){var k={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null};if(Rc(s))qy(o,k);else{var A=s.alternate;if(s.lanes===0&&(A===null||A.lanes===0)&&(A=o.lastRenderedReducer,A!==null))try{var F=o.lastRenderedState,Y=A(F,f);if(k.hasEagerState=!0,k.eagerState=Y,tr(Y,F))return fc(s,o,k,0),Mt===null&&hc(),!1}catch{}finally{}if(f=yh(s,o,k,g),f!==null)return Yn(f,s,g),Ky(f,o,g),!0}return!1}function tf(s,o,f,g){if(g={lane:2,revertLane:Of(),gesture:null,action:g,hasEagerState:!1,eagerState:null,next:null},Rc(s)){if(o)throw Error(r(479))}else o=yh(s,f,g,2),o!==null&&Yn(o,s,2)}function Rc(s){var o=s.alternate;return s===at||o!==null&&o===at}function qy(s,o){wa=Ec=!0;var f=s.pending;f===null?o.next=o:(o.next=f.next,f.next=o),s.pending=o}function Ky(s,o,f){if((f&4194048)!==0){var g=o.lanes;g&=s.pendingLanes,f|=g,o.lanes=f,Ye(s,f)}}var $o={readContext:jn,use:Tc,useCallback:Xt,useContext:Xt,useEffect:Xt,useImperativeHandle:Xt,useLayoutEffect:Xt,useInsertionEffect:Xt,useMemo:Xt,useReducer:Xt,useRef:Xt,useState:Xt,useDebugValue:Xt,useDeferredValue:Xt,useTransition:Xt,useSyncExternalStore:Xt,useId:Xt,useHostTransitionStatus:Xt,useFormState:Xt,useActionState:Xt,useOptimistic:Xt,useMemoCache:Xt,useCacheRefresh:Xt};$o.useEffectEvent=Xt;var Yy={readContext:jn,use:Tc,useCallback:function(s,o){return Bn().memoizedState=[s,o===void 0?null:o],s},useContext:jn,useEffect:Dy,useImperativeHandle:function(s,o,f){f=f!=null?f.concat([s]):null,Lc(4194308,4,My.bind(null,o,s),f)},useLayoutEffect:function(s,o){return Lc(4194308,4,s,o)},useInsertionEffect:function(s,o){Lc(4,2,s,o)},useMemo:function(s,o){var f=Bn();o=o===void 0?null:o;var g=s();if(ji){Yt(!0);try{s()}finally{Yt(!1)}}return f.memoizedState=[g,o],g},useReducer:function(s,o,f){var g=Bn();if(f!==void 0){var k=f(o);if(ji){Yt(!0);try{f(o)}finally{Yt(!1)}}}else k=o;return g.memoizedState=g.baseState=k,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:k},g.queue=s,s=s.dispatch=NE.bind(null,at,s),[g.memoizedState,s]},useRef:function(s){var o=Bn();return s={current:s},o.memoizedState=s},useState:function(s){s=Kh(s);var o=s.queue,f=Wy.bind(null,at,o);return o.dispatch=f,[s.memoizedState,f]},useDebugValue:Qh,useDeferredValue:function(s,o){var f=Bn();return Jh(f,s,o)},useTransition:function(){var s=Kh(!1);return s=Hy.bind(null,at,s.queue,!0,!1),Bn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,o,f){var g=at,k=Bn();if(vt){if(f===void 0)throw Error(r(407));f=f()}else{if(f=o(),Mt===null)throw Error(r(349));(yt&127)!==0||gy(g,o,f)}k.memoizedState=f;var A={value:f,getSnapshot:o};return k.queue=A,Dy(yy.bind(null,g,A,s),[s]),g.flags|=2048,ka(9,{destroy:void 0},xy.bind(null,g,A,f,o),null),f},useId:function(){var s=Bn(),o=Mt.identifierPrefix;if(vt){var f=zr,g=$r;f=(g&~(1<<32-dt(g)-1)).toString(32)+f,o="_"+o+"R_"+f,f=jc++,0<f&&(o+="H"+f.toString(32)),o+="_"}else f=_E++,o="_"+o+"r_"+f.toString(32)+"_";return s.memoizedState=o},useHostTransitionStatus:ef,useFormState:jy,useActionState:jy,useOptimistic:function(s){var o=Bn();o.memoizedState=o.baseState=s;var f={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return o.queue=f,o=tf.bind(null,at,!0,f),f.dispatch=o,[s,o]},useMemoCache:Gh,useCacheRefresh:function(){return Bn().memoizedState=jE.bind(null,at)},useEffectEvent:function(s){var o=Bn(),f={impl:s};return o.memoizedState=f,function(){if((Et&2)!==0)throw Error(r(440));return f.impl.apply(void 0,arguments)}}},nf={readContext:jn,use:Tc,useCallback:By,useContext:jn,useEffect:Xh,useImperativeHandle:Py,useInsertionEffect:Oy,useLayoutEffect:Iy,useMemo:$y,useReducer:Ac,useRef:Ly,useState:function(){return Ac(as)},useDebugValue:Qh,useDeferredValue:function(s,o){var f=tn();return zy(f,At.memoizedState,s,o)},useTransition:function(){var s=Ac(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:Po(s),o]},useSyncExternalStore:py,useId:Vy,useHostTransitionStatus:ef,useFormState:Ny,useActionState:Ny,useOptimistic:function(s,o){var f=tn();return _y(f,At,s,o)},useMemoCache:Gh,useCacheRefresh:Gy};nf.useEffectEvent=Ry;var Xy={readContext:jn,use:Tc,useCallback:By,useContext:jn,useEffect:Xh,useImperativeHandle:Py,useInsertionEffect:Oy,useLayoutEffect:Iy,useMemo:$y,useReducer:qh,useRef:Ly,useState:function(){return qh(as)},useDebugValue:Qh,useDeferredValue:function(s,o){var f=tn();return At===null?Jh(f,s,o):zy(f,At.memoizedState,s,o)},useTransition:function(){var s=qh(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:Po(s),o]},useSyncExternalStore:py,useId:Vy,useHostTransitionStatus:ef,useFormState:Ay,useActionState:Ay,useOptimistic:function(s,o){var f=tn();return At!==null?_y(f,At,s,o):(f.baseState=s,[s,f.queue.dispatch])},useMemoCache:Gh,useCacheRefresh:Gy};Xy.useEffectEvent=Ry;function rf(s,o,f,g){o=s.memoizedState,f=f(g,o),f=f==null?o:m({},o,f),s.memoizedState=f,s.lanes===0&&(s.updateQueue.baseState=f)}var sf={enqueueSetState:function(s,o,f){s=s._reactInternals;var g=or(),k=Is(g);k.payload=o,f!=null&&(k.callback=f),o=Ms(s,k,g),o!==null&&(Yn(o,s,g),Ro(o,s,g))},enqueueReplaceState:function(s,o,f){s=s._reactInternals;var g=or(),k=Is(g);k.tag=1,k.payload=o,f!=null&&(k.callback=f),o=Ms(s,k,g),o!==null&&(Yn(o,s,g),Ro(o,s,g))},enqueueForceUpdate:function(s,o){s=s._reactInternals;var f=or(),g=Is(f);g.tag=2,o!=null&&(g.callback=o),o=Ms(s,g,f),o!==null&&(Yn(o,s,f),Ro(o,s,f))}};function Qy(s,o,f,g,k,A,F){return s=s.stateNode,typeof s.shouldComponentUpdate=="function"?s.shouldComponentUpdate(g,A,F):o.prototype&&o.prototype.isPureReactComponent?!ko(f,g)||!ko(k,A):!0}function Jy(s,o,f,g){s=o.state,typeof o.componentWillReceiveProps=="function"&&o.componentWillReceiveProps(f,g),typeof o.UNSAFE_componentWillReceiveProps=="function"&&o.UNSAFE_componentWillReceiveProps(f,g),o.state!==s&&sf.enqueueReplaceState(o,o.state,null)}function Ni(s,o){var f=o;if("ref"in o){f={};for(var g in o)g!=="ref"&&(f[g]=o[g])}if(s=s.defaultProps){f===o&&(f=m({},f));for(var k in s)f[k]===void 0&&(f[k]=s[k])}return f}function Zy(s){dc(s)}function eb(s){console.error(s)}function tb(s){dc(s)}function Oc(s,o){try{var f=s.onUncaughtError;f(o.value,{componentStack:o.stack})}catch(g){setTimeout(function(){throw g})}}function nb(s,o,f){try{var g=s.onCaughtError;g(f.value,{componentStack:f.stack,errorBoundary:o.tag===1?o.stateNode:null})}catch(k){setTimeout(function(){throw k})}}function af(s,o,f){return f=Is(f),f.tag=3,f.payload={element:null},f.callback=function(){Oc(s,o)},f}function rb(s){return s=Is(s),s.tag=3,s}function sb(s,o,f,g){var k=f.type.getDerivedStateFromError;if(typeof k=="function"){var A=g.value;s.payload=function(){return k(A)},s.callback=function(){nb(o,f,g)}}var F=f.stateNode;F!==null&&typeof F.componentDidCatch=="function"&&(s.callback=function(){nb(o,f,g),typeof k!="function"&&(Us===null?Us=new Set([this]):Us.add(this));var Y=g.stack;this.componentDidCatch(g.value,{componentStack:Y!==null?Y:""})})}function TE(s,o,f,g,k){if(f.flags|=32768,g!==null&&typeof g=="object"&&typeof g.then=="function"){if(o=f.alternate,o!==null&&xa(o,f,k,!0),f=rr.current,f!==null){switch(f.tag){case 31:case 13:return yr===null?Wc():f.alternate===null&&Qt===0&&(Qt=3),f.flags&=-257,f.flags|=65536,f.lanes=k,g===_c?f.flags|=16384:(o=f.updateQueue,o===null?f.updateQueue=new Set([g]):o.add(g),Lf(s,g,k)),!1;case 22:return f.flags|=65536,g===_c?f.flags|=16384:(o=f.updateQueue,o===null?(o={transitions:null,markerInstances:null,retryQueue:new Set([g])},f.updateQueue=o):(f=o.retryQueue,f===null?o.retryQueue=new Set([g]):f.add(g)),Lf(s,g,k)),!1}throw Error(r(435,f.tag))}return Lf(s,g,k),Wc(),!1}if(vt)return o=rr.current,o!==null?((o.flags&65536)===0&&(o.flags|=256),o.flags|=65536,o.lanes=k,g!==Ch&&(s=Error(r(422),{cause:g}),No(mr(s,f)))):(g!==Ch&&(o=Error(r(423),{cause:g}),No(mr(o,f))),s=s.current.alternate,s.flags|=65536,k&=-k,s.lanes|=k,g=mr(g,f),k=af(s.stateNode,g,k),Ih(s,k),Qt!==4&&(Qt=2)),!1;var A=Error(r(520),{cause:g});if(A=mr(A,f),qo===null?qo=[A]:qo.push(A),Qt!==4&&(Qt=2),o===null)return!0;g=mr(g,f),f=o;do{switch(f.tag){case 3:return f.flags|=65536,s=k&-k,f.lanes|=s,s=af(f.stateNode,g,s),Ih(f,s),!1;case 1:if(o=f.type,A=f.stateNode,(f.flags&128)===0&&(typeof o.getDerivedStateFromError=="function"||A!==null&&typeof A.componentDidCatch=="function"&&(Us===null||!Us.has(A))))return f.flags|=65536,k&=-k,f.lanes|=k,k=rb(k),sb(k,s,f,g),Ih(f,k),!1}f=f.return}while(f!==null);return!1}var of=Error(r(461)),cn=!1;function Nn(s,o,f,g){o.child=s===null?ly(o,null,f,g):Ei(o,s.child,f,g)}function ib(s,o,f,g,k){f=f.render;var A=o.ref;if("ref"in g){var F={};for(var Y in g)Y!=="ref"&&(F[Y]=g[Y])}else F=g;return Si(o),g=Hh(s,o,f,F,A,k),Y=Uh(),s!==null&&!cn?(Fh(s,o,k),os(s,o,k)):(vt&&Y&&Sh(o),o.flags|=1,Nn(s,o,g,k),o.child)}function ab(s,o,f,g,k){if(s===null){var A=f.type;return typeof A=="function"&&!bh(A)&&A.defaultProps===void 0&&f.compare===null?(o.tag=15,o.type=A,ob(s,o,A,g,k)):(s=pc(f.type,null,g,o,o.mode,k),s.ref=o.ref,s.return=o,o.child=s)}if(A=s.child,!pf(s,k)){var F=A.memoizedProps;if(f=f.compare,f=f!==null?f:ko,f(F,g)&&s.ref===o.ref)return os(s,o,k)}return o.flags|=1,s=ts(A,g),s.ref=o.ref,s.return=o,o.child=s}function ob(s,o,f,g,k){if(s!==null){var A=s.memoizedProps;if(ko(A,g)&&s.ref===o.ref)if(cn=!1,o.pendingProps=g=A,pf(s,k))(s.flags&131072)!==0&&(cn=!0);else return o.lanes=s.lanes,os(s,o,k)}return lf(s,o,f,g,k)}function lb(s,o,f,g){var k=g.children,A=s!==null?s.memoizedState:null;if(s===null&&o.stateNode===null&&(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),g.mode==="hidden"){if((o.flags&128)!==0){if(A=A!==null?A.baseLanes|f:f,s!==null){for(g=o.child=s.child,k=0;g!==null;)k=k|g.lanes|g.childLanes,g=g.sibling;g=k&~A}else g=0,o.child=null;return cb(s,o,A,f,g)}if((f&536870912)!==0)o.memoizedState={baseLanes:0,cachePool:null},s!==null&&bc(o,A!==null?A.cachePool:null),A!==null?dy(o,A):Ph(),hy(o);else return g=o.lanes=536870912,cb(s,o,A!==null?A.baseLanes|f:f,f,g)}else A!==null?(bc(o,A.cachePool),dy(o,A),Bs(),o.memoizedState=null):(s!==null&&bc(o,null),Ph(),Bs());return Nn(s,o,k,f),o.child}function zo(s,o){return s!==null&&s.tag===22||o.stateNode!==null||(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.sibling}function cb(s,o,f,g,k){var A=Lh();return A=A===null?null:{parent:on._currentValue,pool:A},o.memoizedState={baseLanes:f,cachePool:A},s!==null&&bc(o,null),Ph(),hy(o),s!==null&&xa(s,o,g,!0),o.childLanes=k,null}function Ic(s,o){return o=Pc({mode:o.mode,children:o.children},s.mode),o.ref=s.ref,s.child=o,o.return=s,o}function ub(s,o,f){return Ei(o,s.child,null,f),s=Ic(o,o.pendingProps),s.flags|=2,sr(o),o.memoizedState=null,s}function AE(s,o,f){var g=o.pendingProps,k=(o.flags&128)!==0;if(o.flags&=-129,s===null){if(vt){if(g.mode==="hidden")return s=Ic(o,g),o.lanes=536870912,zo(null,s);if($h(o),(s=Vt)?(s=Sv(s,xr),s=s!==null&&s.data==="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:As!==null?{id:$r,overflow:zr}:null,retryLane:536870912,hydrationErrors:null},f=qx(s),f.return=o,o.child=f,En=o,Vt=null)):s=null,s===null)throw Ds(o);return o.lanes=536870912,null}return Ic(o,g)}var A=s.memoizedState;if(A!==null){var F=A.dehydrated;if($h(o),k)if(o.flags&256)o.flags&=-257,o=ub(s,o,f);else if(o.memoizedState!==null)o.child=s.child,o.flags|=128,o=null;else throw Error(r(558));else if(cn||xa(s,o,f,!1),k=(f&s.childLanes)!==0,cn||k){if(g=Mt,g!==null&&(F=ot(g,f),F!==0&&F!==A.retryLane))throw A.retryLane=F,yi(s,F),Yn(g,s,F),of;Wc(),o=ub(s,o,f)}else s=A.treeContext,Vt=br(F.nextSibling),En=o,vt=!0,Ls=null,xr=!1,s!==null&&Xx(o,s),o=Ic(o,g),o.flags|=4096;return o}return s=ts(s.child,{mode:g.mode,children:g.children}),s.ref=o.ref,o.child=s,s.return=o,s}function Mc(s,o){var f=o.ref;if(f===null)s!==null&&s.ref!==null&&(o.flags|=4194816);else{if(typeof f!="function"&&typeof f!="object")throw Error(r(284));(s===null||s.ref!==f)&&(o.flags|=4194816)}}function lf(s,o,f,g,k){return Si(o),f=Hh(s,o,f,g,void 0,k),g=Uh(),s!==null&&!cn?(Fh(s,o,k),os(s,o,k)):(vt&&g&&Sh(o),o.flags|=1,Nn(s,o,f,k),o.child)}function db(s,o,f,g,k,A){return Si(o),o.updateQueue=null,f=my(o,g,f,k),fy(s),g=Uh(),s!==null&&!cn?(Fh(s,o,A),os(s,o,A)):(vt&&g&&Sh(o),o.flags|=1,Nn(s,o,f,A),o.child)}function hb(s,o,f,g,k){if(Si(o),o.stateNode===null){var A=fa,F=f.contextType;typeof F=="object"&&F!==null&&(A=jn(F)),A=new f(g,A),o.memoizedState=A.state!==null&&A.state!==void 0?A.state:null,A.updater=sf,o.stateNode=A,A._reactInternals=o,A=o.stateNode,A.props=g,A.state=o.memoizedState,A.refs={},Rh(o),F=f.contextType,A.context=typeof F=="object"&&F!==null?jn(F):fa,A.state=o.memoizedState,F=f.getDerivedStateFromProps,typeof F=="function"&&(rf(o,f,F,g),A.state=o.memoizedState),typeof f.getDerivedStateFromProps=="function"||typeof A.getSnapshotBeforeUpdate=="function"||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(F=A.state,typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount(),F!==A.state&&sf.enqueueReplaceState(A,A.state,null),Io(o,g,A,k),Oo(),A.state=o.memoizedState),typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!0}else if(s===null){A=o.stateNode;var Y=o.memoizedProps,ie=Ni(f,Y);A.props=ie;var ge=A.context,ke=f.contextType;F=fa,typeof ke=="object"&&ke!==null&&(F=jn(ke));var Ae=f.getDerivedStateFromProps;ke=typeof Ae=="function"||typeof A.getSnapshotBeforeUpdate=="function",Y=o.pendingProps!==Y,ke||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(Y||ge!==F)&&Jy(o,A,g,F),Os=!1;var ye=o.memoizedState;A.state=ye,Io(o,g,A,k),Oo(),ge=o.memoizedState,Y||ye!==ge||Os?(typeof Ae=="function"&&(rf(o,f,Ae,g),ge=o.memoizedState),(ie=Os||Qy(o,f,ie,g,ye,ge,F))?(ke||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount()),typeof A.componentDidMount=="function"&&(o.flags|=4194308)):(typeof A.componentDidMount=="function"&&(o.flags|=4194308),o.memoizedProps=g,o.memoizedState=ge),A.props=g,A.state=ge,A.context=F,g=ie):(typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!1)}else{A=o.stateNode,Oh(s,o),F=o.memoizedProps,ke=Ni(f,F),A.props=ke,Ae=o.pendingProps,ye=A.context,ge=f.contextType,ie=fa,typeof ge=="object"&&ge!==null&&(ie=jn(ge)),Y=f.getDerivedStateFromProps,(ge=typeof Y=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(F!==Ae||ye!==ie)&&Jy(o,A,g,ie),Os=!1,ye=o.memoizedState,A.state=ye,Io(o,g,A,k),Oo();var be=o.memoizedState;F!==Ae||ye!==be||Os||s!==null&&s.dependencies!==null&&xc(s.dependencies)?(typeof Y=="function"&&(rf(o,f,Y,g),be=o.memoizedState),(ke=Os||Qy(o,f,ke,g,ye,be,ie)||s!==null&&s.dependencies!==null&&xc(s.dependencies))?(ge||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(g,be,ie),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(g,be,ie)),typeof A.componentDidUpdate=="function"&&(o.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(o.flags|=1024)):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=1024),o.memoizedProps=g,o.memoizedState=be),A.props=g,A.state=be,A.context=ie,g=ke):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&ye===s.memoizedState||(o.flags|=1024),g=!1)}return A=g,Mc(s,o),g=(o.flags&128)!==0,A||g?(A=o.stateNode,f=g&&typeof f.getDerivedStateFromError!="function"?null:A.render(),o.flags|=1,s!==null&&g?(o.child=Ei(o,s.child,null,k),o.child=Ei(o,null,f,k)):Nn(s,o,f,k),o.memoizedState=A.state,s=o.child):s=os(s,o,k),s}function fb(s,o,f,g){return vi(),o.flags|=256,Nn(s,o,f,g),o.child}var cf={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function uf(s){return{baseLanes:s,cachePool:ny()}}function df(s,o,f){return s=s!==null?s.childLanes&~f:0,o&&(s|=ar),s}function mb(s,o,f){var g=o.pendingProps,k=!1,A=(o.flags&128)!==0,F;if((F=A)||(F=s!==null&&s.memoizedState===null?!1:(en.current&2)!==0),F&&(k=!0,o.flags&=-129),F=(o.flags&32)!==0,o.flags&=-33,s===null){if(vt){if(k?Ps(o):Bs(),(s=Vt)?(s=Sv(s,xr),s=s!==null&&s.data!=="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:As!==null?{id:$r,overflow:zr}:null,retryLane:536870912,hydrationErrors:null},f=qx(s),f.return=o,o.child=f,En=o,Vt=null)):s=null,s===null)throw Ds(o);return qf(s)?o.lanes=32:o.lanes=536870912,null}var Y=g.children;return g=g.fallback,k?(Bs(),k=o.mode,Y=Pc({mode:"hidden",children:Y},k),g=bi(g,k,f,null),Y.return=o,g.return=o,Y.sibling=g,o.child=Y,g=o.child,g.memoizedState=uf(f),g.childLanes=df(s,F,f),o.memoizedState=cf,zo(null,g)):(Ps(o),hf(o,Y))}var ie=s.memoizedState;if(ie!==null&&(Y=ie.dehydrated,Y!==null)){if(A)o.flags&256?(Ps(o),o.flags&=-257,o=ff(s,o,f)):o.memoizedState!==null?(Bs(),o.child=s.child,o.flags|=128,o=null):(Bs(),Y=g.fallback,k=o.mode,g=Pc({mode:"visible",children:g.children},k),Y=bi(Y,k,f,null),Y.flags|=2,g.return=o,Y.return=o,g.sibling=Y,o.child=g,Ei(o,s.child,null,f),g=o.child,g.memoizedState=uf(f),g.childLanes=df(s,F,f),o.memoizedState=cf,o=zo(null,g));else if(Ps(o),qf(Y)){if(F=Y.nextSibling&&Y.nextSibling.dataset,F)var ge=F.dgst;F=ge,g=Error(r(419)),g.stack="",g.digest=F,No({value:g,source:null,stack:null}),o=ff(s,o,f)}else if(cn||xa(s,o,f,!1),F=(f&s.childLanes)!==0,cn||F){if(F=Mt,F!==null&&(g=ot(F,f),g!==0&&g!==ie.retryLane))throw ie.retryLane=g,yi(s,g),Yn(F,s,g),of;Wf(Y)||Wc(),o=ff(s,o,f)}else Wf(Y)?(o.flags|=192,o.child=s.child,o=null):(s=ie.treeContext,Vt=br(Y.nextSibling),En=o,vt=!0,Ls=null,xr=!1,s!==null&&Xx(o,s),o=hf(o,g.children),o.flags|=4096);return o}return k?(Bs(),Y=g.fallback,k=o.mode,ie=s.child,ge=ie.sibling,g=ts(ie,{mode:"hidden",children:g.children}),g.subtreeFlags=ie.subtreeFlags&65011712,ge!==null?Y=ts(ge,Y):(Y=bi(Y,k,f,null),Y.flags|=2),Y.return=o,g.return=o,g.sibling=Y,o.child=g,zo(null,g),g=o.child,Y=s.child.memoizedState,Y===null?Y=uf(f):(k=Y.cachePool,k!==null?(ie=on._currentValue,k=k.parent!==ie?{parent:ie,pool:ie}:k):k=ny(),Y={baseLanes:Y.baseLanes|f,cachePool:k}),g.memoizedState=Y,g.childLanes=df(s,F,f),o.memoizedState=cf,zo(s.child,g)):(Ps(o),f=s.child,s=f.sibling,f=ts(f,{mode:"visible",children:g.children}),f.return=o,f.sibling=null,s!==null&&(F=o.deletions,F===null?(o.deletions=[s],o.flags|=16):F.push(s)),o.child=f,o.memoizedState=null,f)}function hf(s,o){return o=Pc({mode:"visible",children:o},s.mode),o.return=s,s.child=o}function Pc(s,o){return s=nr(22,s,null,o),s.lanes=0,s}function ff(s,o,f){return Ei(o,s.child,null,f),s=hf(o,o.pendingProps.children),s.flags|=2,o.memoizedState=null,s}function pb(s,o,f){s.lanes|=o;var g=s.alternate;g!==null&&(g.lanes|=o),jh(s.return,o,f)}function mf(s,o,f,g,k,A){var F=s.memoizedState;F===null?s.memoizedState={isBackwards:o,rendering:null,renderingStartTime:0,last:g,tail:f,tailMode:k,treeForkCount:A}:(F.isBackwards=o,F.rendering=null,F.renderingStartTime=0,F.last=g,F.tail=f,F.tailMode=k,F.treeForkCount=A)}function gb(s,o,f){var g=o.pendingProps,k=g.revealOrder,A=g.tail;g=g.children;var F=en.current,Y=(F&2)!==0;if(Y?(F=F&1|2,o.flags|=128):F&=1,z(en,F),Nn(s,o,g,f),g=vt?jo:0,!Y&&s!==null&&(s.flags&128)!==0)e:for(s=o.child;s!==null;){if(s.tag===13)s.memoizedState!==null&&pb(s,f,o);else if(s.tag===19)pb(s,f,o);else if(s.child!==null){s.child.return=s,s=s.child;continue}if(s===o)break e;for(;s.sibling===null;){if(s.return===null||s.return===o)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}switch(k){case"forwards":for(f=o.child,k=null;f!==null;)s=f.alternate,s!==null&&kc(s)===null&&(k=f),f=f.sibling;f=k,f===null?(k=o.child,o.child=null):(k=f.sibling,f.sibling=null),mf(o,!1,k,f,A,g);break;case"backwards":case"unstable_legacy-backwards":for(f=null,k=o.child,o.child=null;k!==null;){if(s=k.alternate,s!==null&&kc(s)===null){o.child=k;break}s=k.sibling,k.sibling=f,f=k,k=s}mf(o,!0,f,null,A,g);break;case"together":mf(o,!1,null,null,void 0,g);break;default:o.memoizedState=null}return o.child}function os(s,o,f){if(s!==null&&(o.dependencies=s.dependencies),Hs|=o.lanes,(f&o.childLanes)===0)if(s!==null){if(xa(s,o,f,!1),(f&o.childLanes)===0)return null}else return null;if(s!==null&&o.child!==s.child)throw Error(r(153));if(o.child!==null){for(s=o.child,f=ts(s,s.pendingProps),o.child=f,f.return=o;s.sibling!==null;)s=s.sibling,f=f.sibling=ts(s,s.pendingProps),f.return=o;f.sibling=null}return o.child}function pf(s,o){return(s.lanes&o)!==0?!0:(s=s.dependencies,!!(s!==null&&xc(s)))}function LE(s,o,f){switch(o.tag){case 3:B(o,o.stateNode.containerInfo),Rs(o,on,s.memoizedState.cache),vi();break;case 27:case 5:se(o);break;case 4:B(o,o.stateNode.containerInfo);break;case 10:Rs(o,o.type,o.memoizedProps.value);break;case 31:if(o.memoizedState!==null)return o.flags|=128,$h(o),null;break;case 13:var g=o.memoizedState;if(g!==null)return g.dehydrated!==null?(Ps(o),o.flags|=128,null):(f&o.child.childLanes)!==0?mb(s,o,f):(Ps(o),s=os(s,o,f),s!==null?s.sibling:null);Ps(o);break;case 19:var k=(s.flags&128)!==0;if(g=(f&o.childLanes)!==0,g||(xa(s,o,f,!1),g=(f&o.childLanes)!==0),k){if(g)return gb(s,o,f);o.flags|=128}if(k=o.memoizedState,k!==null&&(k.rendering=null,k.tail=null,k.lastEffect=null),z(en,en.current),g)break;return null;case 22:return o.lanes=0,lb(s,o,f,o.pendingProps);case 24:Rs(o,on,s.memoizedState.cache)}return os(s,o,f)}function xb(s,o,f){if(s!==null)if(s.memoizedProps!==o.pendingProps)cn=!0;else{if(!pf(s,f)&&(o.flags&128)===0)return cn=!1,LE(s,o,f);cn=(s.flags&131072)!==0}else cn=!1,vt&&(o.flags&1048576)!==0&&Yx(o,jo,o.index);switch(o.lanes=0,o.tag){case 16:e:{var g=o.pendingProps;if(s=Ci(o.elementType),o.type=s,typeof s=="function")bh(s)?(g=Ni(s,g),o.tag=1,o=hb(null,o,s,g,f)):(o.tag=0,o=lf(null,o,s,g,f));else{if(s!=null){var k=s.$$typeof;if(k===E){o.tag=11,o=ib(null,o,s,g,f);break e}else if(k===D){o.tag=14,o=ab(null,o,s,g,f);break e}}throw o=U(s)||s,Error(r(306,o,""))}}return o;case 0:return lf(s,o,o.type,o.pendingProps,f);case 1:return g=o.type,k=Ni(g,o.pendingProps),hb(s,o,g,k,f);case 3:e:{if(B(o,o.stateNode.containerInfo),s===null)throw Error(r(387));g=o.pendingProps;var A=o.memoizedState;k=A.element,Oh(s,o),Io(o,g,null,f);var F=o.memoizedState;if(g=F.cache,Rs(o,on,g),g!==A.cache&&Nh(o,[on],f,!0),Oo(),g=F.element,A.isDehydrated)if(A={element:g,isDehydrated:!1,cache:F.cache},o.updateQueue.baseState=A,o.memoizedState=A,o.flags&256){o=fb(s,o,g,f);break e}else if(g!==k){k=mr(Error(r(424)),o),No(k),o=fb(s,o,g,f);break e}else{switch(s=o.stateNode.containerInfo,s.nodeType){case 9:s=s.body;break;default:s=s.nodeName==="HTML"?s.ownerDocument.body:s}for(Vt=br(s.firstChild),En=o,vt=!0,Ls=null,xr=!0,f=ly(o,null,g,f),o.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling}else{if(vi(),g===k){o=os(s,o,f);break e}Nn(s,o,g,f)}o=o.child}return o;case 26:return Mc(s,o),s===null?(f=Nv(o.type,null,o.pendingProps,null))?o.memoizedState=f:vt||(f=o.type,s=o.pendingProps,g=Zc(ne.current).createElement(f),g[an]=o,g[Fn]=s,Tn(g,f,s),_n(g),o.stateNode=g):o.memoizedState=Nv(o.type,s.memoizedProps,o.pendingProps,s.memoizedState),null;case 27:return se(o),s===null&&vt&&(g=o.stateNode=kv(o.type,o.pendingProps,ne.current),En=o,xr=!0,k=Vt,Ws(o.type)?(Kf=k,Vt=br(g.firstChild)):Vt=k),Nn(s,o,o.pendingProps.children,f),Mc(s,o),s===null&&(o.flags|=4194304),o.child;case 5:return s===null&&vt&&((k=g=Vt)&&(g=oj(g,o.type,o.pendingProps,xr),g!==null?(o.stateNode=g,En=o,Vt=br(g.firstChild),xr=!1,k=!0):k=!1),k||Ds(o)),se(o),k=o.type,A=o.pendingProps,F=s!==null?s.memoizedProps:null,g=A.children,Ff(k,A)?g=null:F!==null&&Ff(k,F)&&(o.flags|=32),o.memoizedState!==null&&(k=Hh(s,o,SE,null,null,f),tl._currentValue=k),Mc(s,o),Nn(s,o,g,f),o.child;case 6:return s===null&&vt&&((s=f=Vt)&&(f=lj(f,o.pendingProps,xr),f!==null?(o.stateNode=f,En=o,Vt=null,s=!0):s=!1),s||Ds(o)),null;case 13:return mb(s,o,f);case 4:return B(o,o.stateNode.containerInfo),g=o.pendingProps,s===null?o.child=Ei(o,null,g,f):Nn(s,o,g,f),o.child;case 11:return ib(s,o,o.type,o.pendingProps,f);case 7:return Nn(s,o,o.pendingProps,f),o.child;case 8:return Nn(s,o,o.pendingProps.children,f),o.child;case 12:return Nn(s,o,o.pendingProps.children,f),o.child;case 10:return g=o.pendingProps,Rs(o,o.type,g.value),Nn(s,o,g.children,f),o.child;case 9:return k=o.type._context,g=o.pendingProps.children,Si(o),k=jn(k),g=g(k),o.flags|=1,Nn(s,o,g,f),o.child;case 14:return ab(s,o,o.type,o.pendingProps,f);case 15:return ob(s,o,o.type,o.pendingProps,f);case 19:return gb(s,o,f);case 31:return AE(s,o,f);case 22:return lb(s,o,f,o.pendingProps);case 24:return Si(o),g=jn(on),s===null?(k=Lh(),k===null&&(k=Mt,A=Th(),k.pooledCache=A,A.refCount++,A!==null&&(k.pooledCacheLanes|=f),k=A),o.memoizedState={parent:g,cache:k},Rh(o),Rs(o,on,k)):((s.lanes&f)!==0&&(Oh(s,o),Io(o,null,null,f),Oo()),k=s.memoizedState,A=o.memoizedState,k.parent!==g?(k={parent:g,cache:g},o.memoizedState=k,o.lanes===0&&(o.memoizedState=o.updateQueue.baseState=k),Rs(o,on,g)):(g=A.cache,Rs(o,on,g),g!==k.cache&&Nh(o,[on],f,!0))),Nn(s,o,o.pendingProps.children,f),o.child;case 29:throw o.pendingProps}throw Error(r(156,o.tag))}function ls(s){s.flags|=4}function gf(s,o,f,g,k){if((o=(s.mode&32)!==0)&&(o=!1),o){if(s.flags|=16777216,(k&335544128)===k)if(s.stateNode.complete)s.flags|=8192;else if(Vb())s.flags|=8192;else throw ki=_c,Dh}else s.flags&=-16777217}function yb(s,o){if(o.type!=="stylesheet"||(o.state.loading&4)!==0)s.flags&=-16777217;else if(s.flags|=16777216,!Rv(o))if(Vb())s.flags|=8192;else throw ki=_c,Dh}function Bc(s,o){o!==null&&(s.flags|=4),s.flags&16384&&(o=s.tag!==22?vn():536870912,s.lanes|=o,Ta|=o)}function Ho(s,o){if(!vt)switch(s.tailMode){case"hidden":o=s.tail;for(var f=null;o!==null;)o.alternate!==null&&(f=o),o=o.sibling;f===null?s.tail=null:f.sibling=null;break;case"collapsed":f=s.tail;for(var g=null;f!==null;)f.alternate!==null&&(g=f),f=f.sibling;g===null?o||s.tail===null?s.tail=null:s.tail.sibling=null:g.sibling=null}}function Gt(s){var o=s.alternate!==null&&s.alternate.child===s.child,f=0,g=0;if(o)for(var k=s.child;k!==null;)f|=k.lanes|k.childLanes,g|=k.subtreeFlags&65011712,g|=k.flags&65011712,k.return=s,k=k.sibling;else for(k=s.child;k!==null;)f|=k.lanes|k.childLanes,g|=k.subtreeFlags,g|=k.flags,k.return=s,k=k.sibling;return s.subtreeFlags|=g,s.childLanes=f,o}function DE(s,o,f){var g=o.pendingProps;switch(wh(o),o.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Gt(o),null;case 1:return Gt(o),null;case 3:return f=o.stateNode,g=null,s!==null&&(g=s.memoizedState.cache),o.memoizedState.cache!==g&&(o.flags|=2048),ss(on),te(),f.pendingContext&&(f.context=f.pendingContext,f.pendingContext=null),(s===null||s.child===null)&&(ga(o)?ls(o):s===null||s.memoizedState.isDehydrated&&(o.flags&256)===0||(o.flags|=1024,kh())),Gt(o),null;case 26:var k=o.type,A=o.memoizedState;return s===null?(ls(o),A!==null?(Gt(o),yb(o,A)):(Gt(o),gf(o,k,null,g,f))):A?A!==s.memoizedState?(ls(o),Gt(o),yb(o,A)):(Gt(o),o.flags&=-16777217):(s=s.memoizedProps,s!==g&&ls(o),Gt(o),gf(o,k,s,g,f)),null;case 27:if(xe(o),f=ne.current,k=o.type,s!==null&&o.stateNode!=null)s.memoizedProps!==g&&ls(o);else{if(!g){if(o.stateNode===null)throw Error(r(166));return Gt(o),null}s=ee.current,ga(o)?Qx(o):(s=kv(k,g,f),o.stateNode=s,ls(o))}return Gt(o),null;case 5:if(xe(o),k=o.type,s!==null&&o.stateNode!=null)s.memoizedProps!==g&&ls(o);else{if(!g){if(o.stateNode===null)throw Error(r(166));return Gt(o),null}if(A=ee.current,ga(o))Qx(o);else{var F=Zc(ne.current);switch(A){case 1:A=F.createElementNS("http://www.w3.org/2000/svg",k);break;case 2:A=F.createElementNS("http://www.w3.org/1998/Math/MathML",k);break;default:switch(k){case"svg":A=F.createElementNS("http://www.w3.org/2000/svg",k);break;case"math":A=F.createElementNS("http://www.w3.org/1998/Math/MathML",k);break;case"script":A=F.createElement("div"),A.innerHTML="<script><\/script>",A=A.removeChild(A.firstChild);break;case"select":A=typeof g.is=="string"?F.createElement("select",{is:g.is}):F.createElement("select"),g.multiple?A.multiple=!0:g.size&&(A.size=g.size);break;default:A=typeof g.is=="string"?F.createElement(k,{is:g.is}):F.createElement(k)}}A[an]=o,A[Fn]=g;e:for(F=o.child;F!==null;){if(F.tag===5||F.tag===6)A.appendChild(F.stateNode);else if(F.tag!==4&&F.tag!==27&&F.child!==null){F.child.return=F,F=F.child;continue}if(F===o)break e;for(;F.sibling===null;){if(F.return===null||F.return===o)break e;F=F.return}F.sibling.return=F.return,F=F.sibling}o.stateNode=A;e:switch(Tn(A,k,g),k){case"button":case"input":case"select":case"textarea":g=!!g.autoFocus;break e;case"img":g=!0;break e;default:g=!1}g&&ls(o)}}return Gt(o),gf(o,o.type,s===null?null:s.memoizedProps,o.pendingProps,f),null;case 6:if(s&&o.stateNode!=null)s.memoizedProps!==g&&ls(o);else{if(typeof g!="string"&&o.stateNode===null)throw Error(r(166));if(s=ne.current,ga(o)){if(s=o.stateNode,f=o.memoizedProps,g=null,k=En,k!==null)switch(k.tag){case 27:case 5:g=k.memoizedProps}s[an]=o,s=!!(s.nodeValue===f||g!==null&&g.suppressHydrationWarning===!0||mv(s.nodeValue,f)),s||Ds(o,!0)}else s=Zc(s).createTextNode(g),s[an]=o,o.stateNode=s}return Gt(o),null;case 31:if(f=o.memoizedState,s===null||s.memoizedState!==null){if(g=ga(o),f!==null){if(s===null){if(!g)throw Error(r(318));if(s=o.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[an]=o}else vi(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;Gt(o),s=!1}else f=kh(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=f),s=!0;if(!s)return o.flags&256?(sr(o),o):(sr(o),null);if((o.flags&128)!==0)throw Error(r(558))}return Gt(o),null;case 13:if(g=o.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(k=ga(o),g!==null&&g.dehydrated!==null){if(s===null){if(!k)throw Error(r(318));if(k=o.memoizedState,k=k!==null?k.dehydrated:null,!k)throw Error(r(317));k[an]=o}else vi(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;Gt(o),k=!1}else k=kh(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=k),k=!0;if(!k)return o.flags&256?(sr(o),o):(sr(o),null)}return sr(o),(o.flags&128)!==0?(o.lanes=f,o):(f=g!==null,s=s!==null&&s.memoizedState!==null,f&&(g=o.child,k=null,g.alternate!==null&&g.alternate.memoizedState!==null&&g.alternate.memoizedState.cachePool!==null&&(k=g.alternate.memoizedState.cachePool.pool),A=null,g.memoizedState!==null&&g.memoizedState.cachePool!==null&&(A=g.memoizedState.cachePool.pool),A!==k&&(g.flags|=2048)),f!==s&&f&&(o.child.flags|=8192),Bc(o,o.updateQueue),Gt(o),null);case 4:return te(),s===null&&Bf(o.stateNode.containerInfo),Gt(o),null;case 10:return ss(o.type),Gt(o),null;case 19:if(q(en),g=o.memoizedState,g===null)return Gt(o),null;if(k=(o.flags&128)!==0,A=g.rendering,A===null)if(k)Ho(g,!1);else{if(Qt!==0||s!==null&&(s.flags&128)!==0)for(s=o.child;s!==null;){if(A=kc(s),A!==null){for(o.flags|=128,Ho(g,!1),s=A.updateQueue,o.updateQueue=s,Bc(o,s),o.subtreeFlags=0,s=f,f=o.child;f!==null;)Wx(f,s),f=f.sibling;return z(en,en.current&1|2),vt&&ns(o,g.treeForkCount),o.child}s=s.sibling}g.tail!==null&&De()>Fc&&(o.flags|=128,k=!0,Ho(g,!1),o.lanes=4194304)}else{if(!k)if(s=kc(A),s!==null){if(o.flags|=128,k=!0,s=s.updateQueue,o.updateQueue=s,Bc(o,s),Ho(g,!0),g.tail===null&&g.tailMode==="hidden"&&!A.alternate&&!vt)return Gt(o),null}else 2*De()-g.renderingStartTime>Fc&&f!==536870912&&(o.flags|=128,k=!0,Ho(g,!1),o.lanes=4194304);g.isBackwards?(A.sibling=o.child,o.child=A):(s=g.last,s!==null?s.sibling=A:o.child=A,g.last=A)}return g.tail!==null?(s=g.tail,g.rendering=s,g.tail=s.sibling,g.renderingStartTime=De(),s.sibling=null,f=en.current,z(en,k?f&1|2:f&1),vt&&ns(o,g.treeForkCount),s):(Gt(o),null);case 22:case 23:return sr(o),Bh(),g=o.memoizedState!==null,s!==null?s.memoizedState!==null!==g&&(o.flags|=8192):g&&(o.flags|=8192),g?(f&536870912)!==0&&(o.flags&128)===0&&(Gt(o),o.subtreeFlags&6&&(o.flags|=8192)):Gt(o),f=o.updateQueue,f!==null&&Bc(o,f.retryQueue),f=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(f=s.memoizedState.cachePool.pool),g=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(g=o.memoizedState.cachePool.pool),g!==f&&(o.flags|=2048),s!==null&&q(wi),null;case 24:return f=null,s!==null&&(f=s.memoizedState.cache),o.memoizedState.cache!==f&&(o.flags|=2048),ss(on),Gt(o),null;case 25:return null;case 30:return null}throw Error(r(156,o.tag))}function RE(s,o){switch(wh(o),o.tag){case 1:return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 3:return ss(on),te(),s=o.flags,(s&65536)!==0&&(s&128)===0?(o.flags=s&-65537|128,o):null;case 26:case 27:case 5:return xe(o),null;case 31:if(o.memoizedState!==null){if(sr(o),o.alternate===null)throw Error(r(340));vi()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 13:if(sr(o),s=o.memoizedState,s!==null&&s.dehydrated!==null){if(o.alternate===null)throw Error(r(340));vi()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 19:return q(en),null;case 4:return te(),null;case 10:return ss(o.type),null;case 22:case 23:return sr(o),Bh(),s!==null&&q(wi),s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 24:return ss(on),null;case 25:return null;default:return null}}function bb(s,o){switch(wh(o),o.tag){case 3:ss(on),te();break;case 26:case 27:case 5:xe(o);break;case 4:te();break;case 31:o.memoizedState!==null&&sr(o);break;case 13:sr(o);break;case 19:q(en);break;case 10:ss(o.type);break;case 22:case 23:sr(o),Bh(),s!==null&&q(wi);break;case 24:ss(on)}}function Uo(s,o){try{var f=o.updateQueue,g=f!==null?f.lastEffect:null;if(g!==null){var k=g.next;f=k;do{if((f.tag&s)===s){g=void 0;var A=f.create,F=f.inst;g=A(),F.destroy=g}f=f.next}while(f!==k)}}catch(Y){Tt(o,o.return,Y)}}function $s(s,o,f){try{var g=o.updateQueue,k=g!==null?g.lastEffect:null;if(k!==null){var A=k.next;g=A;do{if((g.tag&s)===s){var F=g.inst,Y=F.destroy;if(Y!==void 0){F.destroy=void 0,k=o;var ie=f,ge=Y;try{ge()}catch(ke){Tt(k,ie,ke)}}}g=g.next}while(g!==A)}}catch(ke){Tt(o,o.return,ke)}}function vb(s){var o=s.updateQueue;if(o!==null){var f=s.stateNode;try{uy(o,f)}catch(g){Tt(s,s.return,g)}}}function _b(s,o,f){f.props=Ni(s.type,s.memoizedProps),f.state=s.memoizedState;try{f.componentWillUnmount()}catch(g){Tt(s,o,g)}}function Fo(s,o){try{var f=s.ref;if(f!==null){switch(s.tag){case 26:case 27:case 5:var g=s.stateNode;break;case 30:g=s.stateNode;break;default:g=s.stateNode}typeof f=="function"?s.refCleanup=f(g):f.current=g}}catch(k){Tt(s,o,k)}}function Hr(s,o){var f=s.ref,g=s.refCleanup;if(f!==null)if(typeof g=="function")try{g()}catch(k){Tt(s,o,k)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof f=="function")try{f(null)}catch(k){Tt(s,o,k)}else f.current=null}function Sb(s){var o=s.type,f=s.memoizedProps,g=s.stateNode;try{e:switch(o){case"button":case"input":case"select":case"textarea":f.autoFocus&&g.focus();break e;case"img":f.src?g.src=f.src:f.srcSet&&(g.srcset=f.srcSet)}}catch(k){Tt(s,s.return,k)}}function xf(s,o,f){try{var g=s.stateNode;tj(g,s.type,f,o),g[Fn]=o}catch(k){Tt(s,s.return,k)}}function wb(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&Ws(s.type)||s.tag===4}function yf(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||wb(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&Ws(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function bf(s,o,f){var g=s.tag;if(g===5||g===6)s=s.stateNode,o?(f.nodeType===9?f.body:f.nodeName==="HTML"?f.ownerDocument.body:f).insertBefore(s,o):(o=f.nodeType===9?f.body:f.nodeName==="HTML"?f.ownerDocument.body:f,o.appendChild(s),f=f._reactRootContainer,f!=null||o.onclick!==null||(o.onclick=Zr));else if(g!==4&&(g===27&&Ws(s.type)&&(f=s.stateNode,o=null),s=s.child,s!==null))for(bf(s,o,f),s=s.sibling;s!==null;)bf(s,o,f),s=s.sibling}function $c(s,o,f){var g=s.tag;if(g===5||g===6)s=s.stateNode,o?f.insertBefore(s,o):f.appendChild(s);else if(g!==4&&(g===27&&Ws(s.type)&&(f=s.stateNode),s=s.child,s!==null))for($c(s,o,f),s=s.sibling;s!==null;)$c(s,o,f),s=s.sibling}function Cb(s){var o=s.stateNode,f=s.memoizedProps;try{for(var g=s.type,k=o.attributes;k.length;)o.removeAttributeNode(k[0]);Tn(o,g,f),o[an]=s,o[Fn]=f}catch(A){Tt(s,s.return,A)}}var cs=!1,un=!1,vf=!1,kb=typeof WeakSet=="function"?WeakSet:Set,Sn=null;function OE(s,o){if(s=s.containerInfo,Hf=au,s=Px(s),hh(s)){if("selectionStart"in s)var f={start:s.selectionStart,end:s.selectionEnd};else e:{f=(f=s.ownerDocument)&&f.defaultView||window;var g=f.getSelection&&f.getSelection();if(g&&g.rangeCount!==0){f=g.anchorNode;var k=g.anchorOffset,A=g.focusNode;g=g.focusOffset;try{f.nodeType,A.nodeType}catch{f=null;break e}var F=0,Y=-1,ie=-1,ge=0,ke=0,Ae=s,ye=null;t:for(;;){for(var be;Ae!==f||k!==0&&Ae.nodeType!==3||(Y=F+k),Ae!==A||g!==0&&Ae.nodeType!==3||(ie=F+g),Ae.nodeType===3&&(F+=Ae.nodeValue.length),(be=Ae.firstChild)!==null;)ye=Ae,Ae=be;for(;;){if(Ae===s)break t;if(ye===f&&++ge===k&&(Y=F),ye===A&&++ke===g&&(ie=F),(be=Ae.nextSibling)!==null)break;Ae=ye,ye=Ae.parentNode}Ae=be}f=Y===-1||ie===-1?null:{start:Y,end:ie}}else f=null}f=f||{start:0,end:0}}else f=null;for(Uf={focusedElem:s,selectionRange:f},au=!1,Sn=o;Sn!==null;)if(o=Sn,s=o.child,(o.subtreeFlags&1028)!==0&&s!==null)s.return=o,Sn=s;else for(;Sn!==null;){switch(o=Sn,A=o.alternate,s=o.flags,o.tag){case 0:if((s&4)!==0&&(s=o.updateQueue,s=s!==null?s.events:null,s!==null))for(f=0;f<s.length;f++)k=s[f],k.ref.impl=k.nextImpl;break;case 11:case 15:break;case 1:if((s&1024)!==0&&A!==null){s=void 0,f=o,k=A.memoizedProps,A=A.memoizedState,g=f.stateNode;try{var Ge=Ni(f.type,k);s=g.getSnapshotBeforeUpdate(Ge,A),g.__reactInternalSnapshotBeforeUpdate=s}catch(et){Tt(f,f.return,et)}}break;case 3:if((s&1024)!==0){if(s=o.stateNode.containerInfo,f=s.nodeType,f===9)Gf(s);else if(f===1)switch(s.nodeName){case"HEAD":case"HTML":case"BODY":Gf(s);break;default:s.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((s&1024)!==0)throw Error(r(163))}if(s=o.sibling,s!==null){s.return=o.return,Sn=s;break}Sn=o.return}}function Eb(s,o,f){var g=f.flags;switch(f.tag){case 0:case 11:case 15:ds(s,f),g&4&&Uo(5,f);break;case 1:if(ds(s,f),g&4)if(s=f.stateNode,o===null)try{s.componentDidMount()}catch(F){Tt(f,f.return,F)}else{var k=Ni(f.type,o.memoizedProps);o=o.memoizedState;try{s.componentDidUpdate(k,o,s.__reactInternalSnapshotBeforeUpdate)}catch(F){Tt(f,f.return,F)}}g&64&&vb(f),g&512&&Fo(f,f.return);break;case 3:if(ds(s,f),g&64&&(s=f.updateQueue,s!==null)){if(o=null,f.child!==null)switch(f.child.tag){case 27:case 5:o=f.child.stateNode;break;case 1:o=f.child.stateNode}try{uy(s,o)}catch(F){Tt(f,f.return,F)}}break;case 27:o===null&&g&4&&Cb(f);case 26:case 5:ds(s,f),o===null&&g&4&&Sb(f),g&512&&Fo(f,f.return);break;case 12:ds(s,f);break;case 31:ds(s,f),g&4&&Tb(s,f);break;case 13:ds(s,f),g&4&&Ab(s,f),g&64&&(s=f.memoizedState,s!==null&&(s=s.dehydrated,s!==null&&(f=FE.bind(null,f),cj(s,f))));break;case 22:if(g=f.memoizedState!==null||cs,!g){o=o!==null&&o.memoizedState!==null||un,k=cs;var A=un;cs=g,(un=o)&&!A?hs(s,f,(f.subtreeFlags&8772)!==0):ds(s,f),cs=k,un=A}break;case 30:break;default:ds(s,f)}}function jb(s){var o=s.alternate;o!==null&&(s.alternate=null,jb(o)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(o=s.stateNode,o!==null&&Yd(o)),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}var Wt=null,Gn=!1;function us(s,o,f){for(f=f.child;f!==null;)Nb(s,o,f),f=f.sibling}function Nb(s,o,f){if(It&&typeof It.onCommitFiberUnmount=="function")try{It.onCommitFiberUnmount(_t,f)}catch{}switch(f.tag){case 26:un||Hr(f,o),us(s,o,f),f.memoizedState?f.memoizedState.count--:f.stateNode&&(f=f.stateNode,f.parentNode.removeChild(f));break;case 27:un||Hr(f,o);var g=Wt,k=Gn;Ws(f.type)&&(Wt=f.stateNode,Gn=!1),us(s,o,f),Jo(f.stateNode),Wt=g,Gn=k;break;case 5:un||Hr(f,o);case 6:if(g=Wt,k=Gn,Wt=null,us(s,o,f),Wt=g,Gn=k,Wt!==null)if(Gn)try{(Wt.nodeType===9?Wt.body:Wt.nodeName==="HTML"?Wt.ownerDocument.body:Wt).removeChild(f.stateNode)}catch(A){Tt(f,o,A)}else try{Wt.removeChild(f.stateNode)}catch(A){Tt(f,o,A)}break;case 18:Wt!==null&&(Gn?(s=Wt,vv(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,f.stateNode),Pa(s)):vv(Wt,f.stateNode));break;case 4:g=Wt,k=Gn,Wt=f.stateNode.containerInfo,Gn=!0,us(s,o,f),Wt=g,Gn=k;break;case 0:case 11:case 14:case 15:$s(2,f,o),un||$s(4,f,o),us(s,o,f);break;case 1:un||(Hr(f,o),g=f.stateNode,typeof g.componentWillUnmount=="function"&&_b(f,o,g)),us(s,o,f);break;case 21:us(s,o,f);break;case 22:un=(g=un)||f.memoizedState!==null,us(s,o,f),un=g;break;default:us(s,o,f)}}function Tb(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null))){s=s.dehydrated;try{Pa(s)}catch(f){Tt(o,o.return,f)}}}function Ab(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null&&(s=s.dehydrated,s!==null))))try{Pa(s)}catch(f){Tt(o,o.return,f)}}function IE(s){switch(s.tag){case 31:case 13:case 19:var o=s.stateNode;return o===null&&(o=s.stateNode=new kb),o;case 22:return s=s.stateNode,o=s._retryCache,o===null&&(o=s._retryCache=new kb),o;default:throw Error(r(435,s.tag))}}function zc(s,o){var f=IE(s);o.forEach(function(g){if(!f.has(g)){f.add(g);var k=VE.bind(null,s,g);g.then(k,k)}})}function Wn(s,o){var f=o.deletions;if(f!==null)for(var g=0;g<f.length;g++){var k=f[g],A=s,F=o,Y=F;e:for(;Y!==null;){switch(Y.tag){case 27:if(Ws(Y.type)){Wt=Y.stateNode,Gn=!1;break e}break;case 5:Wt=Y.stateNode,Gn=!1;break e;case 3:case 4:Wt=Y.stateNode.containerInfo,Gn=!0;break e}Y=Y.return}if(Wt===null)throw Error(r(160));Nb(A,F,k),Wt=null,Gn=!1,A=k.alternate,A!==null&&(A.return=null),k.return=null}if(o.subtreeFlags&13886)for(o=o.child;o!==null;)Lb(o,s),o=o.sibling}var Nr=null;function Lb(s,o){var f=s.alternate,g=s.flags;switch(s.tag){case 0:case 11:case 14:case 15:Wn(o,s),qn(s),g&4&&($s(3,s,s.return),Uo(3,s),$s(5,s,s.return));break;case 1:Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),g&64&&cs&&(s=s.updateQueue,s!==null&&(g=s.callbacks,g!==null&&(f=s.shared.hiddenCallbacks,s.shared.hiddenCallbacks=f===null?g:f.concat(g))));break;case 26:var k=Nr;if(Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),g&4){var A=f!==null?f.memoizedState:null;if(g=s.memoizedState,f===null)if(g===null)if(s.stateNode===null){e:{g=s.type,f=s.memoizedProps,k=k.ownerDocument||k;t:switch(g){case"title":A=k.getElementsByTagName("title")[0],(!A||A[go]||A[an]||A.namespaceURI==="http://www.w3.org/2000/svg"||A.hasAttribute("itemprop"))&&(A=k.createElement(g),k.head.insertBefore(A,k.querySelector("head > title"))),Tn(A,g,f),A[an]=s,_n(A),g=A;break e;case"link":var F=Lv("link","href",k).get(g+(f.href||""));if(F){for(var Y=0;Y<F.length;Y++)if(A=F[Y],A.getAttribute("href")===(f.href==null||f.href===""?null:f.href)&&A.getAttribute("rel")===(f.rel==null?null:f.rel)&&A.getAttribute("title")===(f.title==null?null:f.title)&&A.getAttribute("crossorigin")===(f.crossOrigin==null?null:f.crossOrigin)){F.splice(Y,1);break t}}A=k.createElement(g),Tn(A,g,f),k.head.appendChild(A);break;case"meta":if(F=Lv("meta","content",k).get(g+(f.content||""))){for(Y=0;Y<F.length;Y++)if(A=F[Y],A.getAttribute("content")===(f.content==null?null:""+f.content)&&A.getAttribute("name")===(f.name==null?null:f.name)&&A.getAttribute("property")===(f.property==null?null:f.property)&&A.getAttribute("http-equiv")===(f.httpEquiv==null?null:f.httpEquiv)&&A.getAttribute("charset")===(f.charSet==null?null:f.charSet)){F.splice(Y,1);break t}}A=k.createElement(g),Tn(A,g,f),k.head.appendChild(A);break;default:throw Error(r(468,g))}A[an]=s,_n(A),g=A}s.stateNode=g}else Dv(k,s.type,s.stateNode);else s.stateNode=Av(k,g,s.memoizedProps);else A!==g?(A===null?f.stateNode!==null&&(f=f.stateNode,f.parentNode.removeChild(f)):A.count--,g===null?Dv(k,s.type,s.stateNode):Av(k,g,s.memoizedProps)):g===null&&s.stateNode!==null&&xf(s,s.memoizedProps,f.memoizedProps)}break;case 27:Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),f!==null&&g&4&&xf(s,s.memoizedProps,f.memoizedProps);break;case 5:if(Wn(o,s),qn(s),g&512&&(un||f===null||Hr(f,f.return)),s.flags&32){k=s.stateNode;try{aa(k,"")}catch(Ge){Tt(s,s.return,Ge)}}g&4&&s.stateNode!=null&&(k=s.memoizedProps,xf(s,k,f!==null?f.memoizedProps:k)),g&1024&&(vf=!0);break;case 6:if(Wn(o,s),qn(s),g&4){if(s.stateNode===null)throw Error(r(162));g=s.memoizedProps,f=s.stateNode;try{f.nodeValue=g}catch(Ge){Tt(s,s.return,Ge)}}break;case 3:if(nu=null,k=Nr,Nr=eu(o.containerInfo),Wn(o,s),Nr=k,qn(s),g&4&&f!==null&&f.memoizedState.isDehydrated)try{Pa(o.containerInfo)}catch(Ge){Tt(s,s.return,Ge)}vf&&(vf=!1,Db(s));break;case 4:g=Nr,Nr=eu(s.stateNode.containerInfo),Wn(o,s),qn(s),Nr=g;break;case 12:Wn(o,s),qn(s);break;case 31:Wn(o,s),qn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,zc(s,g)));break;case 13:Wn(o,s),qn(s),s.child.flags&8192&&s.memoizedState!==null!=(f!==null&&f.memoizedState!==null)&&(Uc=De()),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,zc(s,g)));break;case 22:k=s.memoizedState!==null;var ie=f!==null&&f.memoizedState!==null,ge=cs,ke=un;if(cs=ge||k,un=ke||ie,Wn(o,s),un=ke,cs=ge,qn(s),g&8192)e:for(o=s.stateNode,o._visibility=k?o._visibility&-2:o._visibility|1,k&&(f===null||ie||cs||un||Ti(s)),f=null,o=s;;){if(o.tag===5||o.tag===26){if(f===null){ie=f=o;try{if(A=ie.stateNode,k)F=A.style,typeof F.setProperty=="function"?F.setProperty("display","none","important"):F.display="none";else{Y=ie.stateNode;var Ae=ie.memoizedProps.style,ye=Ae!=null&&Ae.hasOwnProperty("display")?Ae.display:null;Y.style.display=ye==null||typeof ye=="boolean"?"":(""+ye).trim()}}catch(Ge){Tt(ie,ie.return,Ge)}}}else if(o.tag===6){if(f===null){ie=o;try{ie.stateNode.nodeValue=k?"":ie.memoizedProps}catch(Ge){Tt(ie,ie.return,Ge)}}}else if(o.tag===18){if(f===null){ie=o;try{var be=ie.stateNode;k?_v(be,!0):_v(ie.stateNode,!1)}catch(Ge){Tt(ie,ie.return,Ge)}}}else if((o.tag!==22&&o.tag!==23||o.memoizedState===null||o===s)&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===s)break e;for(;o.sibling===null;){if(o.return===null||o.return===s)break e;f===o&&(f=null),o=o.return}f===o&&(f=null),o.sibling.return=o.return,o=o.sibling}g&4&&(g=s.updateQueue,g!==null&&(f=g.retryQueue,f!==null&&(g.retryQueue=null,zc(s,f))));break;case 19:Wn(o,s),qn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,zc(s,g)));break;case 30:break;case 21:break;default:Wn(o,s),qn(s)}}function qn(s){var o=s.flags;if(o&2){try{for(var f,g=s.return;g!==null;){if(wb(g)){f=g;break}g=g.return}if(f==null)throw Error(r(160));switch(f.tag){case 27:var k=f.stateNode,A=yf(s);$c(s,A,k);break;case 5:var F=f.stateNode;f.flags&32&&(aa(F,""),f.flags&=-33);var Y=yf(s);$c(s,Y,F);break;case 3:case 4:var ie=f.stateNode.containerInfo,ge=yf(s);bf(s,ge,ie);break;default:throw Error(r(161))}}catch(ke){Tt(s,s.return,ke)}s.flags&=-3}o&4096&&(s.flags&=-4097)}function Db(s){if(s.subtreeFlags&1024)for(s=s.child;s!==null;){var o=s;Db(o),o.tag===5&&o.flags&1024&&o.stateNode.reset(),s=s.sibling}}function ds(s,o){if(o.subtreeFlags&8772)for(o=o.child;o!==null;)Eb(s,o.alternate,o),o=o.sibling}function Ti(s){for(s=s.child;s!==null;){var o=s;switch(o.tag){case 0:case 11:case 14:case 15:$s(4,o,o.return),Ti(o);break;case 1:Hr(o,o.return);var f=o.stateNode;typeof f.componentWillUnmount=="function"&&_b(o,o.return,f),Ti(o);break;case 27:Jo(o.stateNode);case 26:case 5:Hr(o,o.return),Ti(o);break;case 22:o.memoizedState===null&&Ti(o);break;case 30:Ti(o);break;default:Ti(o)}s=s.sibling}}function hs(s,o,f){for(f=f&&(o.subtreeFlags&8772)!==0,o=o.child;o!==null;){var g=o.alternate,k=s,A=o,F=A.flags;switch(A.tag){case 0:case 11:case 15:hs(k,A,f),Uo(4,A);break;case 1:if(hs(k,A,f),g=A,k=g.stateNode,typeof k.componentDidMount=="function")try{k.componentDidMount()}catch(ge){Tt(g,g.return,ge)}if(g=A,k=g.updateQueue,k!==null){var Y=g.stateNode;try{var ie=k.shared.hiddenCallbacks;if(ie!==null)for(k.shared.hiddenCallbacks=null,k=0;k<ie.length;k++)cy(ie[k],Y)}catch(ge){Tt(g,g.return,ge)}}f&&F&64&&vb(A),Fo(A,A.return);break;case 27:Cb(A);case 26:case 5:hs(k,A,f),f&&g===null&&F&4&&Sb(A),Fo(A,A.return);break;case 12:hs(k,A,f);break;case 31:hs(k,A,f),f&&F&4&&Tb(k,A);break;case 13:hs(k,A,f),f&&F&4&&Ab(k,A);break;case 22:A.memoizedState===null&&hs(k,A,f),Fo(A,A.return);break;case 30:break;default:hs(k,A,f)}o=o.sibling}}function _f(s,o){var f=null;s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(f=s.memoizedState.cachePool.pool),s=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(s=o.memoizedState.cachePool.pool),s!==f&&(s!=null&&s.refCount++,f!=null&&To(f))}function Sf(s,o){s=null,o.alternate!==null&&(s=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==s&&(o.refCount++,s!=null&&To(s))}function Tr(s,o,f,g){if(o.subtreeFlags&10256)for(o=o.child;o!==null;)Rb(s,o,f,g),o=o.sibling}function Rb(s,o,f,g){var k=o.flags;switch(o.tag){case 0:case 11:case 15:Tr(s,o,f,g),k&2048&&Uo(9,o);break;case 1:Tr(s,o,f,g);break;case 3:Tr(s,o,f,g),k&2048&&(s=null,o.alternate!==null&&(s=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==s&&(o.refCount++,s!=null&&To(s)));break;case 12:if(k&2048){Tr(s,o,f,g),s=o.stateNode;try{var A=o.memoizedProps,F=A.id,Y=A.onPostCommit;typeof Y=="function"&&Y(F,o.alternate===null?"mount":"update",s.passiveEffectDuration,-0)}catch(ie){Tt(o,o.return,ie)}}else Tr(s,o,f,g);break;case 31:Tr(s,o,f,g);break;case 13:Tr(s,o,f,g);break;case 23:break;case 22:A=o.stateNode,F=o.alternate,o.memoizedState!==null?A._visibility&2?Tr(s,o,f,g):Vo(s,o):A._visibility&2?Tr(s,o,f,g):(A._visibility|=2,Ea(s,o,f,g,(o.subtreeFlags&10256)!==0||!1)),k&2048&&_f(F,o);break;case 24:Tr(s,o,f,g),k&2048&&Sf(o.alternate,o);break;default:Tr(s,o,f,g)}}function Ea(s,o,f,g,k){for(k=k&&((o.subtreeFlags&10256)!==0||!1),o=o.child;o!==null;){var A=s,F=o,Y=f,ie=g,ge=F.flags;switch(F.tag){case 0:case 11:case 15:Ea(A,F,Y,ie,k),Uo(8,F);break;case 23:break;case 22:var ke=F.stateNode;F.memoizedState!==null?ke._visibility&2?Ea(A,F,Y,ie,k):Vo(A,F):(ke._visibility|=2,Ea(A,F,Y,ie,k)),k&&ge&2048&&_f(F.alternate,F);break;case 24:Ea(A,F,Y,ie,k),k&&ge&2048&&Sf(F.alternate,F);break;default:Ea(A,F,Y,ie,k)}o=o.sibling}}function Vo(s,o){if(o.subtreeFlags&10256)for(o=o.child;o!==null;){var f=s,g=o,k=g.flags;switch(g.tag){case 22:Vo(f,g),k&2048&&_f(g.alternate,g);break;case 24:Vo(f,g),k&2048&&Sf(g.alternate,g);break;default:Vo(f,g)}o=o.sibling}}var Go=8192;function ja(s,o,f){if(s.subtreeFlags&Go)for(s=s.child;s!==null;)Ob(s,o,f),s=s.sibling}function Ob(s,o,f){switch(s.tag){case 26:ja(s,o,f),s.flags&Go&&s.memoizedState!==null&&_j(f,Nr,s.memoizedState,s.memoizedProps);break;case 5:ja(s,o,f);break;case 3:case 4:var g=Nr;Nr=eu(s.stateNode.containerInfo),ja(s,o,f),Nr=g;break;case 22:s.memoizedState===null&&(g=s.alternate,g!==null&&g.memoizedState!==null?(g=Go,Go=16777216,ja(s,o,f),Go=g):ja(s,o,f));break;default:ja(s,o,f)}}function Ib(s){var o=s.alternate;if(o!==null&&(s=o.child,s!==null)){o.child=null;do o=s.sibling,s.sibling=null,s=o;while(s!==null)}}function Wo(s){var o=s.deletions;if((s.flags&16)!==0){if(o!==null)for(var f=0;f<o.length;f++){var g=o[f];Sn=g,Pb(g,s)}Ib(s)}if(s.subtreeFlags&10256)for(s=s.child;s!==null;)Mb(s),s=s.sibling}function Mb(s){switch(s.tag){case 0:case 11:case 15:Wo(s),s.flags&2048&&$s(9,s,s.return);break;case 3:Wo(s);break;case 12:Wo(s);break;case 22:var o=s.stateNode;s.memoizedState!==null&&o._visibility&2&&(s.return===null||s.return.tag!==13)?(o._visibility&=-3,Hc(s)):Wo(s);break;default:Wo(s)}}function Hc(s){var o=s.deletions;if((s.flags&16)!==0){if(o!==null)for(var f=0;f<o.length;f++){var g=o[f];Sn=g,Pb(g,s)}Ib(s)}for(s=s.child;s!==null;){switch(o=s,o.tag){case 0:case 11:case 15:$s(8,o,o.return),Hc(o);break;case 22:f=o.stateNode,f._visibility&2&&(f._visibility&=-3,Hc(o));break;default:Hc(o)}s=s.sibling}}function Pb(s,o){for(;Sn!==null;){var f=Sn;switch(f.tag){case 0:case 11:case 15:$s(8,f,o);break;case 23:case 22:if(f.memoizedState!==null&&f.memoizedState.cachePool!==null){var g=f.memoizedState.cachePool.pool;g!=null&&g.refCount++}break;case 24:To(f.memoizedState.cache)}if(g=f.child,g!==null)g.return=f,Sn=g;else e:for(f=s;Sn!==null;){g=Sn;var k=g.sibling,A=g.return;if(jb(g),g===f){Sn=null;break e}if(k!==null){k.return=A,Sn=k;break e}Sn=A}}}var ME={getCacheForType:function(s){var o=jn(on),f=o.data.get(s);return f===void 0&&(f=s(),o.data.set(s,f)),f},cacheSignal:function(){return jn(on).controller.signal}},PE=typeof WeakMap=="function"?WeakMap:Map,Et=0,Mt=null,ht=null,yt=0,Nt=0,ir=null,zs=!1,Na=!1,wf=!1,fs=0,Qt=0,Hs=0,Ai=0,Cf=0,ar=0,Ta=0,qo=null,Kn=null,kf=!1,Uc=0,Bb=0,Fc=1/0,Vc=null,Us=null,pn=0,Fs=null,Aa=null,ms=0,Ef=0,jf=null,$b=null,Ko=0,Nf=null;function or(){return(Et&2)!==0&&yt!==0?yt&-yt:G.T!==null?Of():sn()}function zb(){if(ar===0)if((yt&536870912)===0||vt){var s=ve;ve<<=1,(ve&3932160)===0&&(ve=262144),ar=s}else ar=536870912;return s=rr.current,s!==null&&(s.flags|=32),ar}function Yn(s,o,f){(s===Mt&&(Nt===2||Nt===9)||s.cancelPendingCommit!==null)&&(La(s,0),Vs(s,yt,ar,!1)),Ce(s,f),((Et&2)===0||s!==Mt)&&(s===Mt&&((Et&2)===0&&(Ai|=f),Qt===4&&Vs(s,yt,ar,!1)),Ur(s))}function Hb(s,o,f){if((Et&6)!==0)throw Error(r(327));var g=!f&&(o&127)===0&&(o&s.expiredLanes)===0||Ie(s,o),k=g?zE(s,o):Af(s,o,!0),A=g;do{if(k===0){Na&&!g&&Vs(s,o,0,!1);break}else{if(f=s.current.alternate,A&&!BE(f)){k=Af(s,o,!1),A=!1;continue}if(k===2){if(A=o,s.errorRecoveryDisabledLanes&A)var F=0;else F=s.pendingLanes&-536870913,F=F!==0?F:F&536870912?536870912:0;if(F!==0){o=F;e:{var Y=s;k=qo;var ie=Y.current.memoizedState.isDehydrated;if(ie&&(La(Y,F).flags|=256),F=Af(Y,F,!1),F!==2){if(wf&&!ie){Y.errorRecoveryDisabledLanes|=A,Ai|=A,k=4;break e}A=Kn,Kn=k,A!==null&&(Kn===null?Kn=A:Kn.push.apply(Kn,A))}k=F}if(A=!1,k!==2)continue}}if(k===1){La(s,0),Vs(s,o,0,!0);break}e:{switch(g=s,A=k,A){case 0:case 1:throw Error(r(345));case 4:if((o&4194048)!==o)break;case 6:Vs(g,o,ar,!zs);break e;case 2:Kn=null;break;case 3:case 5:break;default:throw Error(r(329))}if((o&62914560)===o&&(k=Uc+300-De(),10<k)){if(Vs(g,o,ar,!zs),me(g,0,!0)!==0)break e;ms=o,g.timeoutHandle=yv(Ub.bind(null,g,f,Kn,Vc,kf,o,ar,Ai,Ta,zs,A,"Throttled",-0,0),k);break e}Ub(g,f,Kn,Vc,kf,o,ar,Ai,Ta,zs,A,null,-0,0)}}break}while(!0);Ur(s)}function Ub(s,o,f,g,k,A,F,Y,ie,ge,ke,Ae,ye,be){if(s.timeoutHandle=-1,Ae=o.subtreeFlags,Ae&8192||(Ae&16785408)===16785408){Ae={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Zr},Ob(o,A,Ae);var Ge=(A&62914560)===A?Uc-De():(A&4194048)===A?Bb-De():0;if(Ge=Sj(Ae,Ge),Ge!==null){ms=A,s.cancelPendingCommit=Ge(Xb.bind(null,s,o,A,f,g,k,F,Y,ie,ke,Ae,null,ye,be)),Vs(s,A,F,!ge);return}}Xb(s,o,A,f,g,k,F,Y,ie)}function BE(s){for(var o=s;;){var f=o.tag;if((f===0||f===11||f===15)&&o.flags&16384&&(f=o.updateQueue,f!==null&&(f=f.stores,f!==null)))for(var g=0;g<f.length;g++){var k=f[g],A=k.getSnapshot;k=k.value;try{if(!tr(A(),k))return!1}catch{return!1}}if(f=o.child,o.subtreeFlags&16384&&f!==null)f.return=o,o=f;else{if(o===s)break;for(;o.sibling===null;){if(o.return===null||o.return===s)return!0;o=o.return}o.sibling.return=o.return,o=o.sibling}}return!0}function Vs(s,o,f,g){o&=~Cf,o&=~Ai,s.suspendedLanes|=o,s.pingedLanes&=~o,g&&(s.warmLanes|=o),g=s.expirationTimes;for(var k=o;0<k;){var A=31-dt(k),F=1<<A;g[A]=-1,k&=~F}f!==0&&Fe(s,f,o)}function Gc(){return(Et&6)===0?(Yo(0),!1):!0}function Tf(){if(ht!==null){if(Nt===0)var s=ht.return;else s=ht,rs=_i=null,Vh(s),_a=null,Lo=0,s=ht;for(;s!==null;)bb(s.alternate,s),s=s.return;ht=null}}function La(s,o){var f=s.timeoutHandle;f!==-1&&(s.timeoutHandle=-1,sj(f)),f=s.cancelPendingCommit,f!==null&&(s.cancelPendingCommit=null,f()),ms=0,Tf(),Mt=s,ht=f=ts(s.current,null),yt=o,Nt=0,ir=null,zs=!1,Na=Ie(s,o),wf=!1,Ta=ar=Cf=Ai=Hs=Qt=0,Kn=qo=null,kf=!1,(o&8)!==0&&(o|=o&32);var g=s.entangledLanes;if(g!==0)for(s=s.entanglements,g&=o;0<g;){var k=31-dt(g),A=1<<k;o|=s[k],g&=~A}return fs=o,hc(),f}function Fb(s,o){at=null,G.H=$o,o===va||o===vc?(o=iy(),Nt=3):o===Dh?(o=iy(),Nt=4):Nt=o===of?8:o!==null&&typeof o=="object"&&typeof o.then=="function"?6:1,ir=o,ht===null&&(Qt=1,Oc(s,mr(o,s.current)))}function Vb(){var s=rr.current;return s===null?!0:(yt&4194048)===yt?yr===null:(yt&62914560)===yt||(yt&536870912)!==0?s===yr:!1}function Gb(){var s=G.H;return G.H=$o,s===null?$o:s}function Wb(){var s=G.A;return G.A=ME,s}function Wc(){Qt=4,zs||(yt&4194048)!==yt&&rr.current!==null||(Na=!0),(Hs&134217727)===0&&(Ai&134217727)===0||Mt===null||Vs(Mt,yt,ar,!1)}function Af(s,o,f){var g=Et;Et|=2;var k=Gb(),A=Wb();(Mt!==s||yt!==o)&&(Vc=null,La(s,o)),o=!1;var F=Qt;e:do try{if(Nt!==0&&ht!==null){var Y=ht,ie=ir;switch(Nt){case 8:Tf(),F=6;break e;case 3:case 2:case 9:case 6:rr.current===null&&(o=!0);var ge=Nt;if(Nt=0,ir=null,Da(s,Y,ie,ge),f&&Na){F=0;break e}break;default:ge=Nt,Nt=0,ir=null,Da(s,Y,ie,ge)}}$E(),F=Qt;break}catch(ke){Fb(s,ke)}while(!0);return o&&s.shellSuspendCounter++,rs=_i=null,Et=g,G.H=k,G.A=A,ht===null&&(Mt=null,yt=0,hc()),F}function $E(){for(;ht!==null;)qb(ht)}function zE(s,o){var f=Et;Et|=2;var g=Gb(),k=Wb();Mt!==s||yt!==o?(Vc=null,Fc=De()+500,La(s,o)):Na=Ie(s,o);e:do try{if(Nt!==0&&ht!==null){o=ht;var A=ir;t:switch(Nt){case 1:Nt=0,ir=null,Da(s,o,A,1);break;case 2:case 9:if(ry(A)){Nt=0,ir=null,Kb(o);break}o=function(){Nt!==2&&Nt!==9||Mt!==s||(Nt=7),Ur(s)},A.then(o,o);break e;case 3:Nt=7;break e;case 4:Nt=5;break e;case 7:ry(A)?(Nt=0,ir=null,Kb(o)):(Nt=0,ir=null,Da(s,o,A,7));break;case 5:var F=null;switch(ht.tag){case 26:F=ht.memoizedState;case 5:case 27:var Y=ht;if(F?Rv(F):Y.stateNode.complete){Nt=0,ir=null;var ie=Y.sibling;if(ie!==null)ht=ie;else{var ge=Y.return;ge!==null?(ht=ge,qc(ge)):ht=null}break t}}Nt=0,ir=null,Da(s,o,A,5);break;case 6:Nt=0,ir=null,Da(s,o,A,6);break;case 8:Tf(),Qt=6;break e;default:throw Error(r(462))}}HE();break}catch(ke){Fb(s,ke)}while(!0);return rs=_i=null,G.H=g,G.A=k,Et=f,ht!==null?0:(Mt=null,yt=0,hc(),Qt)}function HE(){for(;ht!==null&&!de();)qb(ht)}function qb(s){var o=xb(s.alternate,s,fs);s.memoizedProps=s.pendingProps,o===null?qc(s):ht=o}function Kb(s){var o=s,f=o.alternate;switch(o.tag){case 15:case 0:o=db(f,o,o.pendingProps,o.type,void 0,yt);break;case 11:o=db(f,o,o.pendingProps,o.type.render,o.ref,yt);break;case 5:Vh(o);default:bb(f,o),o=ht=Wx(o,fs),o=xb(f,o,fs)}s.memoizedProps=s.pendingProps,o===null?qc(s):ht=o}function Da(s,o,f,g){rs=_i=null,Vh(o),_a=null,Lo=0;var k=o.return;try{if(TE(s,k,o,f,yt)){Qt=1,Oc(s,mr(f,s.current)),ht=null;return}}catch(A){if(k!==null)throw ht=k,A;Qt=1,Oc(s,mr(f,s.current)),ht=null;return}o.flags&32768?(vt||g===1?s=!0:Na||(yt&536870912)!==0?s=!1:(zs=s=!0,(g===2||g===9||g===3||g===6)&&(g=rr.current,g!==null&&g.tag===13&&(g.flags|=16384))),Yb(o,s)):qc(o)}function qc(s){var o=s;do{if((o.flags&32768)!==0){Yb(o,zs);return}s=o.return;var f=DE(o.alternate,o,fs);if(f!==null){ht=f;return}if(o=o.sibling,o!==null){ht=o;return}ht=o=s}while(o!==null);Qt===0&&(Qt=5)}function Yb(s,o){do{var f=RE(s.alternate,s);if(f!==null){f.flags&=32767,ht=f;return}if(f=s.return,f!==null&&(f.flags|=32768,f.subtreeFlags=0,f.deletions=null),!o&&(s=s.sibling,s!==null)){ht=s;return}ht=s=f}while(s!==null);Qt=6,ht=null}function Xb(s,o,f,g,k,A,F,Y,ie){s.cancelPendingCommit=null;do Kc();while(pn!==0);if((Et&6)!==0)throw Error(r(327));if(o!==null){if(o===s.current)throw Error(r(177));if(A=o.lanes|o.childLanes,A|=xh,Ne(s,f,A,F,Y,ie),s===Mt&&(ht=Mt=null,yt=0),Aa=o,Fs=s,ms=f,Ef=A,jf=k,$b=g,(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?(s.callbackNode=null,s.callbackPriority=0,GE(Le,function(){return tv(),null})):(s.callbackNode=null,s.callbackPriority=0),g=(o.flags&13878)!==0,(o.subtreeFlags&13878)!==0||g){g=G.T,G.T=null,k=Z.p,Z.p=2,F=Et,Et|=4;try{OE(s,o,f)}finally{Et=F,Z.p=k,G.T=g}}pn=1,Qb(),Jb(),Zb()}}function Qb(){if(pn===1){pn=0;var s=Fs,o=Aa,f=(o.flags&13878)!==0;if((o.subtreeFlags&13878)!==0||f){f=G.T,G.T=null;var g=Z.p;Z.p=2;var k=Et;Et|=4;try{Lb(o,s);var A=Uf,F=Px(s.containerInfo),Y=A.focusedElem,ie=A.selectionRange;if(F!==Y&&Y&&Y.ownerDocument&&Mx(Y.ownerDocument.documentElement,Y)){if(ie!==null&&hh(Y)){var ge=ie.start,ke=ie.end;if(ke===void 0&&(ke=ge),"selectionStart"in Y)Y.selectionStart=ge,Y.selectionEnd=Math.min(ke,Y.value.length);else{var Ae=Y.ownerDocument||document,ye=Ae&&Ae.defaultView||window;if(ye.getSelection){var be=ye.getSelection(),Ge=Y.textContent.length,et=Math.min(ie.start,Ge),Dt=ie.end===void 0?et:Math.min(ie.end,Ge);!be.extend&&et>Dt&&(F=Dt,Dt=et,et=F);var ue=Ix(Y,et),le=Ix(Y,Dt);if(ue&&le&&(be.rangeCount!==1||be.anchorNode!==ue.node||be.anchorOffset!==ue.offset||be.focusNode!==le.node||be.focusOffset!==le.offset)){var pe=Ae.createRange();pe.setStart(ue.node,ue.offset),be.removeAllRanges(),et>Dt?(be.addRange(pe),be.extend(le.node,le.offset)):(pe.setEnd(le.node,le.offset),be.addRange(pe))}}}}for(Ae=[],be=Y;be=be.parentNode;)be.nodeType===1&&Ae.push({element:be,left:be.scrollLeft,top:be.scrollTop});for(typeof Y.focus=="function"&&Y.focus(),Y=0;Y<Ae.length;Y++){var Ee=Ae[Y];Ee.element.scrollLeft=Ee.left,Ee.element.scrollTop=Ee.top}}au=!!Hf,Uf=Hf=null}finally{Et=k,Z.p=g,G.T=f}}s.current=o,pn=2}}function Jb(){if(pn===2){pn=0;var s=Fs,o=Aa,f=(o.flags&8772)!==0;if((o.subtreeFlags&8772)!==0||f){f=G.T,G.T=null;var g=Z.p;Z.p=2;var k=Et;Et|=4;try{Eb(s,o.alternate,o)}finally{Et=k,Z.p=g,G.T=f}}pn=3}}function Zb(){if(pn===4||pn===3){pn=0,he();var s=Fs,o=Aa,f=ms,g=$b;(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?pn=5:(pn=0,Aa=Fs=null,ev(s,s.pendingLanes));var k=s.pendingLanes;if(k===0&&(Us=null),xt(f),o=o.stateNode,It&&typeof It.onCommitFiberRoot=="function")try{It.onCommitFiberRoot(_t,o,void 0,(o.current.flags&128)===128)}catch{}if(g!==null){o=G.T,k=Z.p,Z.p=2,G.T=null;try{for(var A=s.onRecoverableError,F=0;F<g.length;F++){var Y=g[F];A(Y.value,{componentStack:Y.stack})}}finally{G.T=o,Z.p=k}}(ms&3)!==0&&Kc(),Ur(s),k=s.pendingLanes,(f&261930)!==0&&(k&42)!==0?s===Nf?Ko++:(Ko=0,Nf=s):Ko=0,Yo(0)}}function ev(s,o){(s.pooledCacheLanes&=o)===0&&(o=s.pooledCache,o!=null&&(s.pooledCache=null,To(o)))}function Kc(){return Qb(),Jb(),Zb(),tv()}function tv(){if(pn!==5)return!1;var s=Fs,o=Ef;Ef=0;var f=xt(ms),g=G.T,k=Z.p;try{Z.p=32>f?32:f,G.T=null,f=jf,jf=null;var A=Fs,F=ms;if(pn=0,Aa=Fs=null,ms=0,(Et&6)!==0)throw Error(r(331));var Y=Et;if(Et|=4,Mb(A.current),Rb(A,A.current,F,f),Et=Y,Yo(0,!1),It&&typeof It.onPostCommitFiberRoot=="function")try{It.onPostCommitFiberRoot(_t,A)}catch{}return!0}finally{Z.p=k,G.T=g,ev(s,o)}}function nv(s,o,f){o=mr(f,o),o=af(s.stateNode,o,2),s=Ms(s,o,2),s!==null&&(Ce(s,2),Ur(s))}function Tt(s,o,f){if(s.tag===3)nv(s,s,f);else for(;o!==null;){if(o.tag===3){nv(o,s,f);break}else if(o.tag===1){var g=o.stateNode;if(typeof o.type.getDerivedStateFromError=="function"||typeof g.componentDidCatch=="function"&&(Us===null||!Us.has(g))){s=mr(f,s),f=rb(2),g=Ms(o,f,2),g!==null&&(sb(f,g,o,s),Ce(g,2),Ur(g));break}}o=o.return}}function Lf(s,o,f){var g=s.pingCache;if(g===null){g=s.pingCache=new PE;var k=new Set;g.set(o,k)}else k=g.get(o),k===void 0&&(k=new Set,g.set(o,k));k.has(f)||(wf=!0,k.add(f),s=UE.bind(null,s,o,f),o.then(s,s))}function UE(s,o,f){var g=s.pingCache;g!==null&&g.delete(o),s.pingedLanes|=s.suspendedLanes&f,s.warmLanes&=~f,Mt===s&&(yt&f)===f&&(Qt===4||Qt===3&&(yt&62914560)===yt&&300>De()-Uc?(Et&2)===0&&La(s,0):Cf|=f,Ta===yt&&(Ta=0)),Ur(s)}function rv(s,o){o===0&&(o=vn()),s=yi(s,o),s!==null&&(Ce(s,o),Ur(s))}function FE(s){var o=s.memoizedState,f=0;o!==null&&(f=o.retryLane),rv(s,f)}function VE(s,o){var f=0;switch(s.tag){case 31:case 13:var g=s.stateNode,k=s.memoizedState;k!==null&&(f=k.retryLane);break;case 19:g=s.stateNode;break;case 22:g=s.stateNode._retryCache;break;default:throw Error(r(314))}g!==null&&g.delete(o),rv(s,f)}function GE(s,o){return fe(s,o)}var Yc=null,Ra=null,Df=!1,Xc=!1,Rf=!1,Gs=0;function Ur(s){s!==Ra&&s.next===null&&(Ra===null?Yc=Ra=s:Ra=Ra.next=s),Xc=!0,Df||(Df=!0,qE())}function Yo(s,o){if(!Rf&&Xc){Rf=!0;do for(var f=!1,g=Yc;g!==null;){if(s!==0){var k=g.pendingLanes;if(k===0)var A=0;else{var F=g.suspendedLanes,Y=g.pingedLanes;A=(1<<31-dt(42|s)+1)-1,A&=k&~(F&~Y),A=A&201326741?A&201326741|1:A?A|2:0}A!==0&&(f=!0,ov(g,A))}else A=yt,A=me(g,g===Mt?A:0,g.cancelPendingCommit!==null||g.timeoutHandle!==-1),(A&3)===0||Ie(g,A)||(f=!0,ov(g,A));g=g.next}while(f);Rf=!1}}function WE(){sv()}function sv(){Xc=Df=!1;var s=0;Gs!==0&&rj()&&(s=Gs);for(var o=De(),f=null,g=Yc;g!==null;){var k=g.next,A=iv(g,o);A===0?(g.next=null,f===null?Yc=k:f.next=k,k===null&&(Ra=f)):(f=g,(s!==0||(A&3)!==0)&&(Xc=!0)),g=k}pn!==0&&pn!==5||Yo(s),Gs!==0&&(Gs=0)}function iv(s,o){for(var f=s.suspendedLanes,g=s.pingedLanes,k=s.expirationTimes,A=s.pendingLanes&-62914561;0<A;){var F=31-dt(A),Y=1<<F,ie=k[F];ie===-1?((Y&f)===0||(Y&g)!==0)&&(k[F]=gt(Y,o)):ie<=o&&(s.expiredLanes|=Y),A&=~Y}if(o=Mt,f=yt,f=me(s,s===o?f:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g=s.callbackNode,f===0||s===o&&(Nt===2||Nt===9)||s.cancelPendingCommit!==null)return g!==null&&g!==null&&ce(g),s.callbackNode=null,s.callbackPriority=0;if((f&3)===0||Ie(s,f)){if(o=f&-f,o===s.callbackPriority)return o;switch(g!==null&&ce(g),xt(f)){case 2:case 8:f=_e;break;case 32:f=Le;break;case 268435456:f=qe;break;default:f=Le}return g=av.bind(null,s),f=fe(f,g),s.callbackPriority=o,s.callbackNode=f,o}return g!==null&&g!==null&&ce(g),s.callbackPriority=2,s.callbackNode=null,2}function av(s,o){if(pn!==0&&pn!==5)return s.callbackNode=null,s.callbackPriority=0,null;var f=s.callbackNode;if(Kc()&&s.callbackNode!==f)return null;var g=yt;return g=me(s,s===Mt?g:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g===0?null:(Hb(s,g,o),iv(s,De()),s.callbackNode!=null&&s.callbackNode===f?av.bind(null,s):null)}function ov(s,o){if(Kc())return null;Hb(s,o,!0)}function qE(){ij(function(){(Et&6)!==0?fe(re,WE):sv()})}function Of(){if(Gs===0){var s=ya;s===0&&(s=Br,Br<<=1,(Br&261888)===0&&(Br=256)),Gs=s}return Gs}function lv(s){return s==null||typeof s=="symbol"||typeof s=="boolean"?null:typeof s=="function"?s:sc(""+s)}function cv(s,o){var f=o.ownerDocument.createElement("input");return f.name=o.name,f.value=o.value,s.id&&f.setAttribute("form",s.id),o.parentNode.insertBefore(f,o),s=new FormData(s),f.parentNode.removeChild(f),s}function KE(s,o,f,g,k){if(o==="submit"&&f&&f.stateNode===k){var A=lv((k[Fn]||null).action),F=g.submitter;F&&(o=(o=F[Fn]||null)?lv(o.formAction):F.getAttribute("formAction"),o!==null&&(A=o,F=null));var Y=new lc("action","action",null,g,k);s.push({event:Y,listeners:[{instance:null,listener:function(){if(g.defaultPrevented){if(Gs!==0){var ie=F?cv(k,F):new FormData(k);Zh(f,{pending:!0,data:ie,method:k.method,action:A},null,ie)}}else typeof A=="function"&&(Y.preventDefault(),ie=F?cv(k,F):new FormData(k),Zh(f,{pending:!0,data:ie,method:k.method,action:A},A,ie))},currentTarget:k}]})}}for(var If=0;If<gh.length;If++){var Mf=gh[If],YE=Mf.toLowerCase(),XE=Mf[0].toUpperCase()+Mf.slice(1);jr(YE,"on"+XE)}jr(zx,"onAnimationEnd"),jr(Hx,"onAnimationIteration"),jr(Ux,"onAnimationStart"),jr("dblclick","onDoubleClick"),jr("focusin","onFocus"),jr("focusout","onBlur"),jr(hE,"onTransitionRun"),jr(fE,"onTransitionStart"),jr(mE,"onTransitionCancel"),jr(Fx,"onTransitionEnd"),sa("onMouseEnter",["mouseout","mouseover"]),sa("onMouseLeave",["mouseout","mouseover"]),sa("onPointerEnter",["pointerout","pointerover"]),sa("onPointerLeave",["pointerout","pointerover"]),mi("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),mi("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),mi("onBeforeInput",["compositionend","keypress","textInput","paste"]),mi("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),mi("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),mi("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Xo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),QE=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Xo));function uv(s,o){o=(o&4)!==0;for(var f=0;f<s.length;f++){var g=s[f],k=g.event;g=g.listeners;e:{var A=void 0;if(o)for(var F=g.length-1;0<=F;F--){var Y=g[F],ie=Y.instance,ge=Y.currentTarget;if(Y=Y.listener,ie!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){dc(ke)}k.currentTarget=null,A=ie}else for(F=0;F<g.length;F++){if(Y=g[F],ie=Y.instance,ge=Y.currentTarget,Y=Y.listener,ie!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){dc(ke)}k.currentTarget=null,A=ie}}}}function ft(s,o){var f=o[Kd];f===void 0&&(f=o[Kd]=new Set);var g=s+"__bubble";f.has(g)||(dv(o,s,2,!1),f.add(g))}function Pf(s,o,f){var g=0;o&&(g|=4),dv(f,s,g,o)}var Qc="_reactListening"+Math.random().toString(36).slice(2);function Bf(s){if(!s[Qc]){s[Qc]=!0,sx.forEach(function(f){f!=="selectionchange"&&(QE.has(f)||Pf(f,!1,s),Pf(f,!0,s))});var o=s.nodeType===9?s:s.ownerDocument;o===null||o[Qc]||(o[Qc]=!0,Pf("selectionchange",!1,o))}}function dv(s,o,f,g){switch(zv(o)){case 2:var k=kj;break;case 8:k=Ej;break;default:k=Zf}f=k.bind(null,o,f,s),k=void 0,!rh||o!=="touchstart"&&o!=="touchmove"&&o!=="wheel"||(k=!0),g?k!==void 0?s.addEventListener(o,f,{capture:!0,passive:k}):s.addEventListener(o,f,!0):k!==void 0?s.addEventListener(o,f,{passive:k}):s.addEventListener(o,f,!1)}function $f(s,o,f,g,k){var A=g;if((o&1)===0&&(o&2)===0&&g!==null)e:for(;;){if(g===null)return;var F=g.tag;if(F===3||F===4){var Y=g.stateNode.containerInfo;if(Y===k)break;if(F===4)for(F=g.return;F!==null;){var ie=F.tag;if((ie===3||ie===4)&&F.stateNode.containerInfo===k)return;F=F.return}for(;Y!==null;){if(F=ta(Y),F===null)return;if(ie=F.tag,ie===5||ie===6||ie===26||ie===27){g=A=F;continue e}Y=Y.parentNode}}g=g.return}gx(function(){var ge=A,ke=th(f),Ae=[];e:{var ye=Vx.get(s);if(ye!==void 0){var be=lc,Ge=s;switch(s){case"keypress":if(ac(f)===0)break e;case"keydown":case"keyup":be=V2;break;case"focusin":Ge="focus",be=oh;break;case"focusout":Ge="blur",be=oh;break;case"beforeblur":case"afterblur":be=oh;break;case"click":if(f.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":be=bx;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":be=D2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":be=q2;break;case zx:case Hx:case Ux:be=I2;break;case Fx:be=Y2;break;case"scroll":case"scrollend":be=A2;break;case"wheel":be=Q2;break;case"copy":case"cut":case"paste":be=P2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":be=_x;break;case"toggle":case"beforetoggle":be=Z2}var et=(o&4)!==0,Dt=!et&&(s==="scroll"||s==="scrollend"),ue=et?ye!==null?ye+"Capture":null:ye;et=[];for(var le=ge,pe;le!==null;){var Ee=le;if(pe=Ee.stateNode,Ee=Ee.tag,Ee!==5&&Ee!==26&&Ee!==27||pe===null||ue===null||(Ee=yo(le,ue),Ee!=null&&et.push(Qo(le,Ee,pe))),Dt)break;le=le.return}0<et.length&&(ye=new be(ye,Ge,null,f,ke),Ae.push({event:ye,listeners:et}))}}if((o&7)===0){e:{if(ye=s==="mouseover"||s==="pointerover",be=s==="mouseout"||s==="pointerout",ye&&f!==eh&&(Ge=f.relatedTarget||f.fromElement)&&(ta(Ge)||Ge[ea]))break e;if((be||ye)&&(ye=ke.window===ke?ke:(ye=ke.ownerDocument)?ye.defaultView||ye.parentWindow:window,be?(Ge=f.relatedTarget||f.toElement,be=ge,Ge=Ge?ta(Ge):null,Ge!==null&&(Dt=l(Ge),et=Ge.tag,Ge!==Dt||et!==5&&et!==27&&et!==6)&&(Ge=null)):(be=null,Ge=ge),be!==Ge)){if(et=bx,Ee="onMouseLeave",ue="onMouseEnter",le="mouse",(s==="pointerout"||s==="pointerover")&&(et=_x,Ee="onPointerLeave",ue="onPointerEnter",le="pointer"),Dt=be==null?ye:xo(be),pe=Ge==null?ye:xo(Ge),ye=new et(Ee,le+"leave",be,f,ke),ye.target=Dt,ye.relatedTarget=pe,Ee=null,ta(ke)===ge&&(et=new et(ue,le+"enter",Ge,f,ke),et.target=pe,et.relatedTarget=Dt,Ee=et),Dt=Ee,be&&Ge)t:{for(et=JE,ue=be,le=Ge,pe=0,Ee=ue;Ee;Ee=et(Ee))pe++;Ee=0;for(var Xe=le;Xe;Xe=et(Xe))Ee++;for(;0<pe-Ee;)ue=et(ue),pe--;for(;0<Ee-pe;)le=et(le),Ee--;for(;pe--;){if(ue===le||le!==null&&ue===le.alternate){et=ue;break t}ue=et(ue),le=et(le)}et=null}else et=null;be!==null&&hv(Ae,ye,be,et,!1),Ge!==null&&Dt!==null&&hv(Ae,Dt,Ge,et,!0)}}e:{if(ye=ge?xo(ge):window,be=ye.nodeName&&ye.nodeName.toLowerCase(),be==="select"||be==="input"&&ye.type==="file")var Ct=Tx;else if(jx(ye))if(Ax)Ct=cE;else{Ct=oE;var We=aE}else be=ye.nodeName,!be||be.toLowerCase()!=="input"||ye.type!=="checkbox"&&ye.type!=="radio"?ge&&Zd(ge.elementType)&&(Ct=Tx):Ct=lE;if(Ct&&(Ct=Ct(s,ge))){Nx(Ae,Ct,f,ke);break e}We&&We(s,ye,ge),s==="focusout"&&ge&&ye.type==="number"&&ge.memoizedProps.value!=null&&Jd(ye,"number",ye.value)}switch(We=ge?xo(ge):window,s){case"focusin":(jx(We)||We.contentEditable==="true")&&(ua=We,fh=ge,Eo=null);break;case"focusout":Eo=fh=ua=null;break;case"mousedown":mh=!0;break;case"contextmenu":case"mouseup":case"dragend":mh=!1,Bx(Ae,f,ke);break;case"selectionchange":if(dE)break;case"keydown":case"keyup":Bx(Ae,f,ke)}var lt;if(ch)e:{switch(s){case"compositionstart":var bt="onCompositionStart";break e;case"compositionend":bt="onCompositionEnd";break e;case"compositionupdate":bt="onCompositionUpdate";break e}bt=void 0}else ca?kx(s,f)&&(bt="onCompositionEnd"):s==="keydown"&&f.keyCode===229&&(bt="onCompositionStart");bt&&(Sx&&f.locale!=="ko"&&(ca||bt!=="onCompositionStart"?bt==="onCompositionEnd"&&ca&&(lt=xx()):(Ts=ke,sh="value"in Ts?Ts.value:Ts.textContent,ca=!0)),We=Jc(ge,bt),0<We.length&&(bt=new vx(bt,s,null,f,ke),Ae.push({event:bt,listeners:We}),lt?bt.data=lt:(lt=Ex(f),lt!==null&&(bt.data=lt)))),(lt=tE?nE(s,f):rE(s,f))&&(bt=Jc(ge,"onBeforeInput"),0<bt.length&&(We=new vx("onBeforeInput","beforeinput",null,f,ke),Ae.push({event:We,listeners:bt}),We.data=lt)),KE(Ae,s,ge,f,ke)}uv(Ae,o)})}function Qo(s,o,f){return{instance:s,listener:o,currentTarget:f}}function Jc(s,o){for(var f=o+"Capture",g=[];s!==null;){var k=s,A=k.stateNode;if(k=k.tag,k!==5&&k!==26&&k!==27||A===null||(k=yo(s,f),k!=null&&g.unshift(Qo(s,k,A)),k=yo(s,o),k!=null&&g.push(Qo(s,k,A))),s.tag===3)return g;s=s.return}return[]}function JE(s){if(s===null)return null;do s=s.return;while(s&&s.tag!==5&&s.tag!==27);return s||null}function hv(s,o,f,g,k){for(var A=o._reactName,F=[];f!==null&&f!==g;){var Y=f,ie=Y.alternate,ge=Y.stateNode;if(Y=Y.tag,ie!==null&&ie===g)break;Y!==5&&Y!==26&&Y!==27||ge===null||(ie=ge,k?(ge=yo(f,A),ge!=null&&F.unshift(Qo(f,ge,ie))):k||(ge=yo(f,A),ge!=null&&F.push(Qo(f,ge,ie)))),f=f.return}F.length!==0&&s.push({event:o,listeners:F})}var ZE=/\r\n?/g,ej=/\u0000|\uFFFD/g;function fv(s){return(typeof s=="string"?s:""+s).replace(ZE,`
50
50
  `).replace(ej,"")}function mv(s,o){return o=fv(o),fv(s)===o}function Lt(s,o,f,g,k,A){switch(f){case"children":typeof g=="string"?o==="body"||o==="textarea"&&g===""||aa(s,g):(typeof g=="number"||typeof g=="bigint")&&o!=="body"&&aa(s,""+g);break;case"className":nc(s,"class",g);break;case"tabIndex":nc(s,"tabindex",g);break;case"dir":case"role":case"viewBox":case"width":case"height":nc(s,f,g);break;case"style":mx(s,g,A);break;case"data":if(o!=="object"){nc(s,"data",g);break}case"src":case"href":if(g===""&&(o!=="a"||f!=="href")){s.removeAttribute(f);break}if(g==null||typeof g=="function"||typeof g=="symbol"||typeof g=="boolean"){s.removeAttribute(f);break}g=sc(""+g),s.setAttribute(f,g);break;case"action":case"formAction":if(typeof g=="function"){s.setAttribute(f,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof A=="function"&&(f==="formAction"?(o!=="input"&&Lt(s,o,"name",k.name,k,null),Lt(s,o,"formEncType",k.formEncType,k,null),Lt(s,o,"formMethod",k.formMethod,k,null),Lt(s,o,"formTarget",k.formTarget,k,null)):(Lt(s,o,"encType",k.encType,k,null),Lt(s,o,"method",k.method,k,null),Lt(s,o,"target",k.target,k,null)));if(g==null||typeof g=="symbol"||typeof g=="boolean"){s.removeAttribute(f);break}g=sc(""+g),s.setAttribute(f,g);break;case"onClick":g!=null&&(s.onclick=Zr);break;case"onScroll":g!=null&&ft("scroll",s);break;case"onScrollEnd":g!=null&&ft("scrollend",s);break;case"dangerouslySetInnerHTML":if(g!=null){if(typeof g!="object"||!("__html"in g))throw Error(r(61));if(f=g.__html,f!=null){if(k.children!=null)throw Error(r(60));s.innerHTML=f}}break;case"multiple":s.multiple=g&&typeof g!="function"&&typeof g!="symbol";break;case"muted":s.muted=g&&typeof g!="function"&&typeof g!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(g==null||typeof g=="function"||typeof g=="boolean"||typeof g=="symbol"){s.removeAttribute("xlink:href");break}f=sc(""+g),s.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",f);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":g!=null&&typeof g!="function"&&typeof g!="symbol"?s.setAttribute(f,""+g):s.removeAttribute(f);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":g&&typeof g!="function"&&typeof g!="symbol"?s.setAttribute(f,""):s.removeAttribute(f);break;case"capture":case"download":g===!0?s.setAttribute(f,""):g!==!1&&g!=null&&typeof g!="function"&&typeof g!="symbol"?s.setAttribute(f,g):s.removeAttribute(f);break;case"cols":case"rows":case"size":case"span":g!=null&&typeof g!="function"&&typeof g!="symbol"&&!isNaN(g)&&1<=g?s.setAttribute(f,g):s.removeAttribute(f);break;case"rowSpan":case"start":g==null||typeof g=="function"||typeof g=="symbol"||isNaN(g)?s.removeAttribute(f):s.setAttribute(f,g);break;case"popover":ft("beforetoggle",s),ft("toggle",s),tc(s,"popover",g);break;case"xlinkActuate":Jr(s,"http://www.w3.org/1999/xlink","xlink:actuate",g);break;case"xlinkArcrole":Jr(s,"http://www.w3.org/1999/xlink","xlink:arcrole",g);break;case"xlinkRole":Jr(s,"http://www.w3.org/1999/xlink","xlink:role",g);break;case"xlinkShow":Jr(s,"http://www.w3.org/1999/xlink","xlink:show",g);break;case"xlinkTitle":Jr(s,"http://www.w3.org/1999/xlink","xlink:title",g);break;case"xlinkType":Jr(s,"http://www.w3.org/1999/xlink","xlink:type",g);break;case"xmlBase":Jr(s,"http://www.w3.org/XML/1998/namespace","xml:base",g);break;case"xmlLang":Jr(s,"http://www.w3.org/XML/1998/namespace","xml:lang",g);break;case"xmlSpace":Jr(s,"http://www.w3.org/XML/1998/namespace","xml:space",g);break;case"is":tc(s,"is",g);break;case"innerText":case"textContent":break;default:(!(2<f.length)||f[0]!=="o"&&f[0]!=="O"||f[1]!=="n"&&f[1]!=="N")&&(f=N2.get(f)||f,tc(s,f,g))}}function zf(s,o,f,g,k,A){switch(f){case"style":mx(s,g,A);break;case"dangerouslySetInnerHTML":if(g!=null){if(typeof g!="object"||!("__html"in g))throw Error(r(61));if(f=g.__html,f!=null){if(k.children!=null)throw Error(r(60));s.innerHTML=f}}break;case"children":typeof g=="string"?aa(s,g):(typeof g=="number"||typeof g=="bigint")&&aa(s,""+g);break;case"onScroll":g!=null&&ft("scroll",s);break;case"onScrollEnd":g!=null&&ft("scrollend",s);break;case"onClick":g!=null&&(s.onclick=Zr);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!ix.hasOwnProperty(f))e:{if(f[0]==="o"&&f[1]==="n"&&(k=f.endsWith("Capture"),o=f.slice(2,k?f.length-7:void 0),A=s[Fn]||null,A=A!=null?A[f]:null,typeof A=="function"&&s.removeEventListener(o,A,k),typeof g=="function")){typeof A!="function"&&A!==null&&(f in s?s[f]=null:s.hasAttribute(f)&&s.removeAttribute(f)),s.addEventListener(o,g,k);break e}f in s?s[f]=g:g===!0?s.setAttribute(f,""):tc(s,f,g)}}}function Tn(s,o,f){switch(o){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":ft("error",s),ft("load",s);var g=!1,k=!1,A;for(A in f)if(f.hasOwnProperty(A)){var F=f[A];if(F!=null)switch(A){case"src":g=!0;break;case"srcSet":k=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,o));default:Lt(s,o,A,F,f,null)}}k&&Lt(s,o,"srcSet",f.srcSet,f,null),g&&Lt(s,o,"src",f.src,f,null);return;case"input":ft("invalid",s);var Y=A=F=k=null,ie=null,ge=null;for(g in f)if(f.hasOwnProperty(g)){var ke=f[g];if(ke!=null)switch(g){case"name":k=ke;break;case"type":F=ke;break;case"checked":ie=ke;break;case"defaultChecked":ge=ke;break;case"value":A=ke;break;case"defaultValue":Y=ke;break;case"children":case"dangerouslySetInnerHTML":if(ke!=null)throw Error(r(137,o));break;default:Lt(s,o,g,ke,f,null)}}ux(s,A,Y,ie,ge,F,k,!1);return;case"select":ft("invalid",s),g=F=A=null;for(k in f)if(f.hasOwnProperty(k)&&(Y=f[k],Y!=null))switch(k){case"value":A=Y;break;case"defaultValue":F=Y;break;case"multiple":g=Y;default:Lt(s,o,k,Y,f,null)}o=A,f=F,s.multiple=!!g,o!=null?ia(s,!!g,o,!1):f!=null&&ia(s,!!g,f,!0);return;case"textarea":ft("invalid",s),A=k=g=null;for(F in f)if(f.hasOwnProperty(F)&&(Y=f[F],Y!=null))switch(F){case"value":g=Y;break;case"defaultValue":k=Y;break;case"children":A=Y;break;case"dangerouslySetInnerHTML":if(Y!=null)throw Error(r(91));break;default:Lt(s,o,F,Y,f,null)}hx(s,g,k,A);return;case"option":for(ie in f)if(f.hasOwnProperty(ie)&&(g=f[ie],g!=null))switch(ie){case"selected":s.selected=g&&typeof g!="function"&&typeof g!="symbol";break;default:Lt(s,o,ie,g,f,null)}return;case"dialog":ft("beforetoggle",s),ft("toggle",s),ft("cancel",s),ft("close",s);break;case"iframe":case"object":ft("load",s);break;case"video":case"audio":for(g=0;g<Xo.length;g++)ft(Xo[g],s);break;case"image":ft("error",s),ft("load",s);break;case"details":ft("toggle",s);break;case"embed":case"source":case"link":ft("error",s),ft("load",s);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(ge in f)if(f.hasOwnProperty(ge)&&(g=f[ge],g!=null))switch(ge){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,o));default:Lt(s,o,ge,g,f,null)}return;default:if(Zd(o)){for(ke in f)f.hasOwnProperty(ke)&&(g=f[ke],g!==void 0&&zf(s,o,ke,g,f,void 0));return}}for(Y in f)f.hasOwnProperty(Y)&&(g=f[Y],g!=null&&Lt(s,o,Y,g,f,null))}function tj(s,o,f,g){switch(o){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var k=null,A=null,F=null,Y=null,ie=null,ge=null,ke=null;for(be in f){var Ae=f[be];if(f.hasOwnProperty(be)&&Ae!=null)switch(be){case"checked":break;case"value":break;case"defaultValue":ie=Ae;default:g.hasOwnProperty(be)||Lt(s,o,be,null,g,Ae)}}for(var ye in g){var be=g[ye];if(Ae=f[ye],g.hasOwnProperty(ye)&&(be!=null||Ae!=null))switch(ye){case"type":A=be;break;case"name":k=be;break;case"checked":ge=be;break;case"defaultChecked":ke=be;break;case"value":F=be;break;case"defaultValue":Y=be;break;case"children":case"dangerouslySetInnerHTML":if(be!=null)throw Error(r(137,o));break;default:be!==Ae&&Lt(s,o,ye,be,g,Ae)}}Qd(s,F,Y,ie,ge,ke,A,k);return;case"select":be=F=Y=ye=null;for(A in f)if(ie=f[A],f.hasOwnProperty(A)&&ie!=null)switch(A){case"value":break;case"multiple":be=ie;default:g.hasOwnProperty(A)||Lt(s,o,A,null,g,ie)}for(k in g)if(A=g[k],ie=f[k],g.hasOwnProperty(k)&&(A!=null||ie!=null))switch(k){case"value":ye=A;break;case"defaultValue":Y=A;break;case"multiple":F=A;default:A!==ie&&Lt(s,o,k,A,g,ie)}o=Y,f=F,g=be,ye!=null?ia(s,!!f,ye,!1):!!g!=!!f&&(o!=null?ia(s,!!f,o,!0):ia(s,!!f,f?[]:"",!1));return;case"textarea":be=ye=null;for(Y in f)if(k=f[Y],f.hasOwnProperty(Y)&&k!=null&&!g.hasOwnProperty(Y))switch(Y){case"value":break;case"children":break;default:Lt(s,o,Y,null,g,k)}for(F in g)if(k=g[F],A=f[F],g.hasOwnProperty(F)&&(k!=null||A!=null))switch(F){case"value":ye=k;break;case"defaultValue":be=k;break;case"children":break;case"dangerouslySetInnerHTML":if(k!=null)throw Error(r(91));break;default:k!==A&&Lt(s,o,F,k,g,A)}dx(s,ye,be);return;case"option":for(var Ge in f)if(ye=f[Ge],f.hasOwnProperty(Ge)&&ye!=null&&!g.hasOwnProperty(Ge))switch(Ge){case"selected":s.selected=!1;break;default:Lt(s,o,Ge,null,g,ye)}for(ie in g)if(ye=g[ie],be=f[ie],g.hasOwnProperty(ie)&&ye!==be&&(ye!=null||be!=null))switch(ie){case"selected":s.selected=ye&&typeof ye!="function"&&typeof ye!="symbol";break;default:Lt(s,o,ie,ye,g,be)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var et in f)ye=f[et],f.hasOwnProperty(et)&&ye!=null&&!g.hasOwnProperty(et)&&Lt(s,o,et,null,g,ye);for(ge in g)if(ye=g[ge],be=f[ge],g.hasOwnProperty(ge)&&ye!==be&&(ye!=null||be!=null))switch(ge){case"children":case"dangerouslySetInnerHTML":if(ye!=null)throw Error(r(137,o));break;default:Lt(s,o,ge,ye,g,be)}return;default:if(Zd(o)){for(var Dt in f)ye=f[Dt],f.hasOwnProperty(Dt)&&ye!==void 0&&!g.hasOwnProperty(Dt)&&zf(s,o,Dt,void 0,g,ye);for(ke in g)ye=g[ke],be=f[ke],!g.hasOwnProperty(ke)||ye===be||ye===void 0&&be===void 0||zf(s,o,ke,ye,g,be);return}}for(var ue in f)ye=f[ue],f.hasOwnProperty(ue)&&ye!=null&&!g.hasOwnProperty(ue)&&Lt(s,o,ue,null,g,ye);for(Ae in g)ye=g[Ae],be=f[Ae],!g.hasOwnProperty(Ae)||ye===be||ye==null&&be==null||Lt(s,o,Ae,ye,g,be)}function pv(s){switch(s){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function nj(){if(typeof performance.getEntriesByType=="function"){for(var s=0,o=0,f=performance.getEntriesByType("resource"),g=0;g<f.length;g++){var k=f[g],A=k.transferSize,F=k.initiatorType,Y=k.duration;if(A&&Y&&pv(F)){for(F=0,Y=k.responseEnd,g+=1;g<f.length;g++){var ie=f[g],ge=ie.startTime;if(ge>Y)break;var ke=ie.transferSize,Ae=ie.initiatorType;ke&&pv(Ae)&&(ie=ie.responseEnd,F+=ke*(ie<Y?1:(Y-ge)/(ie-ge)))}if(--g,o+=8*(A+F)/(k.duration/1e3),s++,10<s)break}}if(0<s)return o/s/1e6}return navigator.connection&&(s=navigator.connection.downlink,typeof s=="number")?s:5}var Hf=null,Uf=null;function Zc(s){return s.nodeType===9?s:s.ownerDocument}function gv(s){switch(s){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function xv(s,o){if(s===0)switch(o){case"svg":return 1;case"math":return 2;default:return 0}return s===1&&o==="foreignObject"?0:s}function Ff(s,o){return s==="textarea"||s==="noscript"||typeof o.children=="string"||typeof o.children=="number"||typeof o.children=="bigint"||typeof o.dangerouslySetInnerHTML=="object"&&o.dangerouslySetInnerHTML!==null&&o.dangerouslySetInnerHTML.__html!=null}var Vf=null;function rj(){var s=window.event;return s&&s.type==="popstate"?s===Vf?!1:(Vf=s,!0):(Vf=null,!1)}var yv=typeof setTimeout=="function"?setTimeout:void 0,sj=typeof clearTimeout=="function"?clearTimeout:void 0,bv=typeof Promise=="function"?Promise:void 0,ij=typeof queueMicrotask=="function"?queueMicrotask:typeof bv<"u"?function(s){return bv.resolve(null).then(s).catch(aj)}:yv;function aj(s){setTimeout(function(){throw s})}function Ws(s){return s==="head"}function vv(s,o){var f=o,g=0;do{var k=f.nextSibling;if(s.removeChild(f),k&&k.nodeType===8)if(f=k.data,f==="/$"||f==="/&"){if(g===0){s.removeChild(k),Pa(o);return}g--}else if(f==="$"||f==="$?"||f==="$~"||f==="$!"||f==="&")g++;else if(f==="html")Jo(s.ownerDocument.documentElement);else if(f==="head"){f=s.ownerDocument.head,Jo(f);for(var A=f.firstChild;A;){var F=A.nextSibling,Y=A.nodeName;A[go]||Y==="SCRIPT"||Y==="STYLE"||Y==="LINK"&&A.rel.toLowerCase()==="stylesheet"||f.removeChild(A),A=F}}else f==="body"&&Jo(s.ownerDocument.body);f=k}while(f);Pa(o)}function _v(s,o){var f=s;s=0;do{var g=f.nextSibling;if(f.nodeType===1?o?(f._stashedDisplay=f.style.display,f.style.display="none"):(f.style.display=f._stashedDisplay||"",f.getAttribute("style")===""&&f.removeAttribute("style")):f.nodeType===3&&(o?(f._stashedText=f.nodeValue,f.nodeValue=""):f.nodeValue=f._stashedText||""),g&&g.nodeType===8)if(f=g.data,f==="/$"){if(s===0)break;s--}else f!=="$"&&f!=="$?"&&f!=="$~"&&f!=="$!"||s++;f=g}while(f)}function Gf(s){var o=s.firstChild;for(o&&o.nodeType===10&&(o=o.nextSibling);o;){var f=o;switch(o=o.nextSibling,f.nodeName){case"HTML":case"HEAD":case"BODY":Gf(f),Yd(f);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(f.rel.toLowerCase()==="stylesheet")continue}s.removeChild(f)}}function oj(s,o,f,g){for(;s.nodeType===1;){var k=f;if(s.nodeName.toLowerCase()!==o.toLowerCase()){if(!g&&(s.nodeName!=="INPUT"||s.type!=="hidden"))break}else if(g){if(!s[go])switch(o){case"meta":if(!s.hasAttribute("itemprop"))break;return s;case"link":if(A=s.getAttribute("rel"),A==="stylesheet"&&s.hasAttribute("data-precedence"))break;if(A!==k.rel||s.getAttribute("href")!==(k.href==null||k.href===""?null:k.href)||s.getAttribute("crossorigin")!==(k.crossOrigin==null?null:k.crossOrigin)||s.getAttribute("title")!==(k.title==null?null:k.title))break;return s;case"style":if(s.hasAttribute("data-precedence"))break;return s;case"script":if(A=s.getAttribute("src"),(A!==(k.src==null?null:k.src)||s.getAttribute("type")!==(k.type==null?null:k.type)||s.getAttribute("crossorigin")!==(k.crossOrigin==null?null:k.crossOrigin))&&A&&s.hasAttribute("async")&&!s.hasAttribute("itemprop"))break;return s;default:return s}}else if(o==="input"&&s.type==="hidden"){var A=k.name==null?null:""+k.name;if(k.type==="hidden"&&s.getAttribute("name")===A)return s}else return s;if(s=br(s.nextSibling),s===null)break}return null}function lj(s,o,f){if(o==="")return null;for(;s.nodeType!==3;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!f||(s=br(s.nextSibling),s===null))return null;return s}function Sv(s,o){for(;s.nodeType!==8;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!o||(s=br(s.nextSibling),s===null))return null;return s}function Wf(s){return s.data==="$?"||s.data==="$~"}function qf(s){return s.data==="$!"||s.data==="$?"&&s.ownerDocument.readyState!=="loading"}function cj(s,o){var f=s.ownerDocument;if(s.data==="$~")s._reactRetry=o;else if(s.data!=="$?"||f.readyState!=="loading")o();else{var g=function(){o(),f.removeEventListener("DOMContentLoaded",g)};f.addEventListener("DOMContentLoaded",g),s._reactRetry=g}}function br(s){for(;s!=null;s=s.nextSibling){var o=s.nodeType;if(o===1||o===3)break;if(o===8){if(o=s.data,o==="$"||o==="$!"||o==="$?"||o==="$~"||o==="&"||o==="F!"||o==="F")break;if(o==="/$"||o==="/&")return null}}return s}var Kf=null;function wv(s){s=s.nextSibling;for(var o=0;s;){if(s.nodeType===8){var f=s.data;if(f==="/$"||f==="/&"){if(o===0)return br(s.nextSibling);o--}else f!=="$"&&f!=="$!"&&f!=="$?"&&f!=="$~"&&f!=="&"||o++}s=s.nextSibling}return null}function Cv(s){s=s.previousSibling;for(var o=0;s;){if(s.nodeType===8){var f=s.data;if(f==="$"||f==="$!"||f==="$?"||f==="$~"||f==="&"){if(o===0)return s;o--}else f!=="/$"&&f!=="/&"||o++}s=s.previousSibling}return null}function kv(s,o,f){switch(o=Zc(f),s){case"html":if(s=o.documentElement,!s)throw Error(r(452));return s;case"head":if(s=o.head,!s)throw Error(r(453));return s;case"body":if(s=o.body,!s)throw Error(r(454));return s;default:throw Error(r(451))}}function Jo(s){for(var o=s.attributes;o.length;)s.removeAttributeNode(o[0]);Yd(s)}var vr=new Map,Ev=new Set;function eu(s){return typeof s.getRootNode=="function"?s.getRootNode():s.nodeType===9?s:s.ownerDocument}var ps=Z.d;Z.d={f:uj,r:dj,D:hj,C:fj,L:mj,m:pj,X:xj,S:gj,M:yj};function uj(){var s=ps.f(),o=Gc();return s||o}function dj(s){var o=na(s);o!==null&&o.tag===5&&o.type==="form"?Fy(o):ps.r(s)}var Oa=typeof document>"u"?null:document;function jv(s,o,f){var g=Oa;if(g&&typeof o=="string"&&o){var k=hr(o);k='link[rel="'+s+'"][href="'+k+'"]',typeof f=="string"&&(k+='[crossorigin="'+f+'"]'),Ev.has(k)||(Ev.add(k),s={rel:s,crossOrigin:f,href:o},g.querySelector(k)===null&&(o=g.createElement("link"),Tn(o,"link",s),_n(o),g.head.appendChild(o)))}}function hj(s){ps.D(s),jv("dns-prefetch",s,null)}function fj(s,o){ps.C(s,o),jv("preconnect",s,o)}function mj(s,o,f){ps.L(s,o,f);var g=Oa;if(g&&s&&o){var k='link[rel="preload"][as="'+hr(o)+'"]';o==="image"&&f&&f.imageSrcSet?(k+='[imagesrcset="'+hr(f.imageSrcSet)+'"]',typeof f.imageSizes=="string"&&(k+='[imagesizes="'+hr(f.imageSizes)+'"]')):k+='[href="'+hr(s)+'"]';var A=k;switch(o){case"style":A=Ia(s);break;case"script":A=Ma(s)}vr.has(A)||(s=m({rel:"preload",href:o==="image"&&f&&f.imageSrcSet?void 0:s,as:o},f),vr.set(A,s),g.querySelector(k)!==null||o==="style"&&g.querySelector(Zo(A))||o==="script"&&g.querySelector(el(A))||(o=g.createElement("link"),Tn(o,"link",s),_n(o),g.head.appendChild(o)))}}function pj(s,o){ps.m(s,o);var f=Oa;if(f&&s){var g=o&&typeof o.as=="string"?o.as:"script",k='link[rel="modulepreload"][as="'+hr(g)+'"][href="'+hr(s)+'"]',A=k;switch(g){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":A=Ma(s)}if(!vr.has(A)&&(s=m({rel:"modulepreload",href:s},o),vr.set(A,s),f.querySelector(k)===null)){switch(g){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(f.querySelector(el(A)))return}g=f.createElement("link"),Tn(g,"link",s),_n(g),f.head.appendChild(g)}}}function gj(s,o,f){ps.S(s,o,f);var g=Oa;if(g&&s){var k=ra(g).hoistableStyles,A=Ia(s);o=o||"default";var F=k.get(A);if(!F){var Y={loading:0,preload:null};if(F=g.querySelector(Zo(A)))Y.loading=5;else{s=m({rel:"stylesheet",href:s,"data-precedence":o},f),(f=vr.get(A))&&Yf(s,f);var ie=F=g.createElement("link");_n(ie),Tn(ie,"link",s),ie._p=new Promise(function(ge,ke){ie.onload=ge,ie.onerror=ke}),ie.addEventListener("load",function(){Y.loading|=1}),ie.addEventListener("error",function(){Y.loading|=2}),Y.loading|=4,tu(F,o,g)}F={type:"stylesheet",instance:F,count:1,state:Y},k.set(A,F)}}}function xj(s,o){ps.X(s,o);var f=Oa;if(f&&s){var g=ra(f).hoistableScripts,k=Ma(s),A=g.get(k);A||(A=f.querySelector(el(k)),A||(s=m({src:s,async:!0},o),(o=vr.get(k))&&Xf(s,o),A=f.createElement("script"),_n(A),Tn(A,"link",s),f.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},g.set(k,A))}}function yj(s,o){ps.M(s,o);var f=Oa;if(f&&s){var g=ra(f).hoistableScripts,k=Ma(s),A=g.get(k);A||(A=f.querySelector(el(k)),A||(s=m({src:s,async:!0,type:"module"},o),(o=vr.get(k))&&Xf(s,o),A=f.createElement("script"),_n(A),Tn(A,"link",s),f.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},g.set(k,A))}}function Nv(s,o,f,g){var k=(k=ne.current)?eu(k):null;if(!k)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof f.precedence=="string"&&typeof f.href=="string"?(o=Ia(f.href),f=ra(k).hoistableStyles,g=f.get(o),g||(g={type:"style",instance:null,count:0,state:null},f.set(o,g)),g):{type:"void",instance:null,count:0,state:null};case"link":if(f.rel==="stylesheet"&&typeof f.href=="string"&&typeof f.precedence=="string"){s=Ia(f.href);var A=ra(k).hoistableStyles,F=A.get(s);if(F||(k=k.ownerDocument||k,F={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},A.set(s,F),(A=k.querySelector(Zo(s)))&&!A._p&&(F.instance=A,F.state.loading=5),vr.has(s)||(f={rel:"preload",as:"style",href:f.href,crossOrigin:f.crossOrigin,integrity:f.integrity,media:f.media,hrefLang:f.hrefLang,referrerPolicy:f.referrerPolicy},vr.set(s,f),A||bj(k,s,f,F.state))),o&&g===null)throw Error(r(528,""));return F}if(o&&g!==null)throw Error(r(529,""));return null;case"script":return o=f.async,f=f.src,typeof f=="string"&&o&&typeof o!="function"&&typeof o!="symbol"?(o=Ma(f),f=ra(k).hoistableScripts,g=f.get(o),g||(g={type:"script",instance:null,count:0,state:null},f.set(o,g)),g):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function Ia(s){return'href="'+hr(s)+'"'}function Zo(s){return'link[rel="stylesheet"]['+s+"]"}function Tv(s){return m({},s,{"data-precedence":s.precedence,precedence:null})}function bj(s,o,f,g){s.querySelector('link[rel="preload"][as="style"]['+o+"]")?g.loading=1:(o=s.createElement("link"),g.preload=o,o.addEventListener("load",function(){return g.loading|=1}),o.addEventListener("error",function(){return g.loading|=2}),Tn(o,"link",f),_n(o),s.head.appendChild(o))}function Ma(s){return'[src="'+hr(s)+'"]'}function el(s){return"script[async]"+s}function Av(s,o,f){if(o.count++,o.instance===null)switch(o.type){case"style":var g=s.querySelector('style[data-href~="'+hr(f.href)+'"]');if(g)return o.instance=g,_n(g),g;var k=m({},f,{"data-href":f.href,"data-precedence":f.precedence,href:null,precedence:null});return g=(s.ownerDocument||s).createElement("style"),_n(g),Tn(g,"style",k),tu(g,f.precedence,s),o.instance=g;case"stylesheet":k=Ia(f.href);var A=s.querySelector(Zo(k));if(A)return o.state.loading|=4,o.instance=A,_n(A),A;g=Tv(f),(k=vr.get(k))&&Yf(g,k),A=(s.ownerDocument||s).createElement("link"),_n(A);var F=A;return F._p=new Promise(function(Y,ie){F.onload=Y,F.onerror=ie}),Tn(A,"link",g),o.state.loading|=4,tu(A,f.precedence,s),o.instance=A;case"script":return A=Ma(f.src),(k=s.querySelector(el(A)))?(o.instance=k,_n(k),k):(g=f,(k=vr.get(A))&&(g=m({},f),Xf(g,k)),s=s.ownerDocument||s,k=s.createElement("script"),_n(k),Tn(k,"link",g),s.head.appendChild(k),o.instance=k);case"void":return null;default:throw Error(r(443,o.type))}else o.type==="stylesheet"&&(o.state.loading&4)===0&&(g=o.instance,o.state.loading|=4,tu(g,f.precedence,s));return o.instance}function tu(s,o,f){for(var g=f.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),k=g.length?g[g.length-1]:null,A=k,F=0;F<g.length;F++){var Y=g[F];if(Y.dataset.precedence===o)A=Y;else if(A!==k)break}A?A.parentNode.insertBefore(s,A.nextSibling):(o=f.nodeType===9?f.head:f,o.insertBefore(s,o.firstChild))}function Yf(s,o){s.crossOrigin==null&&(s.crossOrigin=o.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=o.referrerPolicy),s.title==null&&(s.title=o.title)}function Xf(s,o){s.crossOrigin==null&&(s.crossOrigin=o.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=o.referrerPolicy),s.integrity==null&&(s.integrity=o.integrity)}var nu=null;function Lv(s,o,f){if(nu===null){var g=new Map,k=nu=new Map;k.set(f,g)}else k=nu,g=k.get(f),g||(g=new Map,k.set(f,g));if(g.has(s))return g;for(g.set(s,null),f=f.getElementsByTagName(s),k=0;k<f.length;k++){var A=f[k];if(!(A[go]||A[an]||s==="link"&&A.getAttribute("rel")==="stylesheet")&&A.namespaceURI!=="http://www.w3.org/2000/svg"){var F=A.getAttribute(o)||"";F=s+F;var Y=g.get(F);Y?Y.push(A):g.set(F,[A])}}return g}function Dv(s,o,f){s=s.ownerDocument||s,s.head.insertBefore(f,o==="title"?s.querySelector("head > title"):null)}function vj(s,o,f){if(f===1||o.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof o.precedence!="string"||typeof o.href!="string"||o.href==="")break;return!0;case"link":if(typeof o.rel!="string"||typeof o.href!="string"||o.href===""||o.onLoad||o.onError)break;switch(o.rel){case"stylesheet":return s=o.disabled,typeof o.precedence=="string"&&s==null;default:return!0}case"script":if(o.async&&typeof o.async!="function"&&typeof o.async!="symbol"&&!o.onLoad&&!o.onError&&o.src&&typeof o.src=="string")return!0}return!1}function Rv(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function _j(s,o,f,g){if(f.type==="stylesheet"&&(typeof g.media!="string"||matchMedia(g.media).matches!==!1)&&(f.state.loading&4)===0){if(f.instance===null){var k=Ia(g.href),A=o.querySelector(Zo(k));if(A){o=A._p,o!==null&&typeof o=="object"&&typeof o.then=="function"&&(s.count++,s=ru.bind(s),o.then(s,s)),f.state.loading|=4,f.instance=A,_n(A);return}A=o.ownerDocument||o,g=Tv(g),(k=vr.get(k))&&Yf(g,k),A=A.createElement("link"),_n(A);var F=A;F._p=new Promise(function(Y,ie){F.onload=Y,F.onerror=ie}),Tn(A,"link",g),f.instance=A}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(f,o),(o=f.state.preload)&&(f.state.loading&3)===0&&(s.count++,f=ru.bind(s),o.addEventListener("load",f),o.addEventListener("error",f))}}var Qf=0;function Sj(s,o){return s.stylesheets&&s.count===0&&iu(s,s.stylesheets),0<s.count||0<s.imgCount?function(f){var g=setTimeout(function(){if(s.stylesheets&&iu(s,s.stylesheets),s.unsuspend){var A=s.unsuspend;s.unsuspend=null,A()}},6e4+o);0<s.imgBytes&&Qf===0&&(Qf=62500*nj());var k=setTimeout(function(){if(s.waitingForImages=!1,s.count===0&&(s.stylesheets&&iu(s,s.stylesheets),s.unsuspend)){var A=s.unsuspend;s.unsuspend=null,A()}},(s.imgBytes>Qf?50:800)+o);return s.unsuspend=f,function(){s.unsuspend=null,clearTimeout(g),clearTimeout(k)}}:null}function ru(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)iu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var su=null;function iu(s,o){s.stylesheets=null,s.unsuspend!==null&&(s.count++,su=new Map,o.forEach(wj,s),su=null,ru.call(s))}function wj(s,o){if(!(o.state.loading&4)){var f=su.get(s);if(f)var g=f.get(null);else{f=new Map,su.set(s,f);for(var k=s.querySelectorAll("link[data-precedence],style[data-precedence]"),A=0;A<k.length;A++){var F=k[A];(F.nodeName==="LINK"||F.getAttribute("media")!=="not all")&&(f.set(F.dataset.precedence,F),g=F)}g&&f.set(null,g)}k=o.instance,F=k.getAttribute("data-precedence"),A=f.get(F)||g,A===g&&f.set(null,k),f.set(F,k),this.count++,g=ru.bind(this),k.addEventListener("load",g),k.addEventListener("error",g),A?A.parentNode.insertBefore(k,A.nextSibling):(s=s.nodeType===9?s.head:s,s.insertBefore(k,s.firstChild)),o.state.loading|=4}}var tl={$$typeof:b,Provider:null,Consumer:null,_currentValue:X,_currentValue2:X,_threadCount:0};function Cj(s,o,f,g,k,A,F,Y,ie){this.tag=1,this.containerInfo=s,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=rn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=rn(0),this.hiddenUpdates=rn(null),this.identifierPrefix=g,this.onUncaughtError=k,this.onCaughtError=A,this.onRecoverableError=F,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ie,this.incompleteTransitions=new Map}function Ov(s,o,f,g,k,A,F,Y,ie,ge,ke,Ae){return s=new Cj(s,o,f,F,ie,ge,ke,Ae,Y),o=1,A===!0&&(o|=24),A=nr(3,null,null,o),s.current=A,A.stateNode=s,o=Th(),o.refCount++,s.pooledCache=o,o.refCount++,A.memoizedState={element:g,isDehydrated:f,cache:o},Rh(A),s}function Iv(s){return s?(s=fa,s):fa}function Mv(s,o,f,g,k,A){k=Iv(k),g.context===null?g.context=k:g.pendingContext=k,g=Is(o),g.payload={element:f},A=A===void 0?null:A,A!==null&&(g.callback=A),f=Ms(s,g,o),f!==null&&(Yn(f,s,o),Ro(f,s,o))}function Pv(s,o){if(s=s.memoizedState,s!==null&&s.dehydrated!==null){var f=s.retryLane;s.retryLane=f!==0&&f<o?f:o}}function Jf(s,o){Pv(s,o),(s=s.alternate)&&Pv(s,o)}function Bv(s){if(s.tag===13||s.tag===31){var o=yi(s,67108864);o!==null&&Yn(o,s,67108864),Jf(s,67108864)}}function $v(s){if(s.tag===13||s.tag===31){var o=or();o=nt(o);var f=yi(s,o);f!==null&&Yn(f,s,o),Jf(s,o)}}var au=!0;function kj(s,o,f,g){var k=G.T;G.T=null;var A=Z.p;try{Z.p=2,Zf(s,o,f,g)}finally{Z.p=A,G.T=k}}function Ej(s,o,f,g){var k=G.T;G.T=null;var A=Z.p;try{Z.p=8,Zf(s,o,f,g)}finally{Z.p=A,G.T=k}}function Zf(s,o,f,g){if(au){var k=em(g);if(k===null)$f(s,o,g,ou,f),Hv(s,g);else if(Nj(k,s,o,f,g))g.stopPropagation();else if(Hv(s,g),o&4&&-1<jj.indexOf(s)){for(;k!==null;){var A=na(k);if(A!==null)switch(A.tag){case 3:if(A=A.stateNode,A.current.memoizedState.isDehydrated){var F=ae(A.pendingLanes);if(F!==0){var Y=A;for(Y.pendingLanes|=2,Y.entangledLanes|=2;F;){var ie=1<<31-dt(F);Y.entanglements[1]|=ie,F&=~ie}Ur(A),(Et&6)===0&&(Fc=De()+500,Yo(0))}}break;case 31:case 13:Y=yi(A,2),Y!==null&&Yn(Y,A,2),Gc(),Jf(A,2)}if(A=em(g),A===null&&$f(s,o,g,ou,f),A===k)break;k=A}k!==null&&g.stopPropagation()}else $f(s,o,g,null,f)}}function em(s){return s=th(s),tm(s)}var ou=null;function tm(s){if(ou=null,s=ta(s),s!==null){var o=l(s);if(o===null)s=null;else{var f=o.tag;if(f===13){if(s=u(o),s!==null)return s;s=null}else if(f===31){if(s=c(o),s!==null)return s;s=null}else if(f===3){if(o.stateNode.current.memoizedState.isDehydrated)return o.tag===3?o.stateNode.containerInfo:null;s=null}else o!==s&&(s=null)}}return ou=s,null}function zv(s){switch(s){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Ue()){case re:return 2;case _e:return 8;case Le:case He:return 32;case qe:return 268435456;default:return 32}default:return 32}}var nm=!1,qs=null,Ks=null,Ys=null,nl=new Map,rl=new Map,Xs=[],jj="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function Hv(s,o){switch(s){case"focusin":case"focusout":qs=null;break;case"dragenter":case"dragleave":Ks=null;break;case"mouseover":case"mouseout":Ys=null;break;case"pointerover":case"pointerout":nl.delete(o.pointerId);break;case"gotpointercapture":case"lostpointercapture":rl.delete(o.pointerId)}}function sl(s,o,f,g,k,A){return s===null||s.nativeEvent!==A?(s={blockedOn:o,domEventName:f,eventSystemFlags:g,nativeEvent:A,targetContainers:[k]},o!==null&&(o=na(o),o!==null&&Bv(o)),s):(s.eventSystemFlags|=g,o=s.targetContainers,k!==null&&o.indexOf(k)===-1&&o.push(k),s)}function Nj(s,o,f,g,k){switch(o){case"focusin":return qs=sl(qs,s,o,f,g,k),!0;case"dragenter":return Ks=sl(Ks,s,o,f,g,k),!0;case"mouseover":return Ys=sl(Ys,s,o,f,g,k),!0;case"pointerover":var A=k.pointerId;return nl.set(A,sl(nl.get(A)||null,s,o,f,g,k)),!0;case"gotpointercapture":return A=k.pointerId,rl.set(A,sl(rl.get(A)||null,s,o,f,g,k)),!0}return!1}function Uv(s){var o=ta(s.target);if(o!==null){var f=l(o);if(f!==null){if(o=f.tag,o===13){if(o=u(f),o!==null){s.blockedOn=o,Zt(s.priority,function(){$v(f)});return}}else if(o===31){if(o=c(f),o!==null){s.blockedOn=o,Zt(s.priority,function(){$v(f)});return}}else if(o===3&&f.stateNode.current.memoizedState.isDehydrated){s.blockedOn=f.tag===3?f.stateNode.containerInfo:null;return}}}s.blockedOn=null}function lu(s){if(s.blockedOn!==null)return!1;for(var o=s.targetContainers;0<o.length;){var f=em(s.nativeEvent);if(f===null){f=s.nativeEvent;var g=new f.constructor(f.type,f);eh=g,f.target.dispatchEvent(g),eh=null}else return o=na(f),o!==null&&Bv(o),s.blockedOn=f,!1;o.shift()}return!0}function Fv(s,o,f){lu(s)&&f.delete(o)}function Tj(){nm=!1,qs!==null&&lu(qs)&&(qs=null),Ks!==null&&lu(Ks)&&(Ks=null),Ys!==null&&lu(Ys)&&(Ys=null),nl.forEach(Fv),rl.forEach(Fv)}function cu(s,o){s.blockedOn===o&&(s.blockedOn=null,nm||(nm=!0,e.unstable_scheduleCallback(e.unstable_NormalPriority,Tj)))}var uu=null;function Vv(s){uu!==s&&(uu=s,e.unstable_scheduleCallback(e.unstable_NormalPriority,function(){uu===s&&(uu=null);for(var o=0;o<s.length;o+=3){var f=s[o],g=s[o+1],k=s[o+2];if(typeof g!="function"){if(tm(g||f)===null)continue;break}var A=na(f);A!==null&&(s.splice(o,3),o-=3,Zh(A,{pending:!0,data:k,method:f.method,action:g},g,k))}}))}function Pa(s){function o(ie){return cu(ie,s)}qs!==null&&cu(qs,s),Ks!==null&&cu(Ks,s),Ys!==null&&cu(Ys,s),nl.forEach(o),rl.forEach(o);for(var f=0;f<Xs.length;f++){var g=Xs[f];g.blockedOn===s&&(g.blockedOn=null)}for(;0<Xs.length&&(f=Xs[0],f.blockedOn===null);)Uv(f),f.blockedOn===null&&Xs.shift();if(f=(s.ownerDocument||s).$$reactFormReplay,f!=null)for(g=0;g<f.length;g+=3){var k=f[g],A=f[g+1],F=k[Fn]||null;if(typeof A=="function")F||Vv(f);else if(F){var Y=null;if(A&&A.hasAttribute("formAction")){if(k=A,F=A[Fn]||null)Y=F.formAction;else if(tm(k)!==null)continue}else Y=F.action;typeof Y=="function"?f[g+1]=Y:(f.splice(g,3),g-=3),Vv(f)}}}function Gv(){function s(A){A.canIntercept&&A.info==="react-transition"&&A.intercept({handler:function(){return new Promise(function(F){return k=F})},focusReset:"manual",scroll:"manual"})}function o(){k!==null&&(k(),k=null),g||setTimeout(f,20)}function f(){if(!g&&!navigation.transition){var A=navigation.currentEntry;A&&A.url!=null&&navigation.navigate(A.url,{state:A.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var g=!1,k=null;return navigation.addEventListener("navigate",s),navigation.addEventListener("navigatesuccess",o),navigation.addEventListener("navigateerror",o),setTimeout(f,100),function(){g=!0,navigation.removeEventListener("navigate",s),navigation.removeEventListener("navigatesuccess",o),navigation.removeEventListener("navigateerror",o),k!==null&&(k(),k=null)}}}function rm(s){this._internalRoot=s}du.prototype.render=rm.prototype.render=function(s){var o=this._internalRoot;if(o===null)throw Error(r(409));var f=o.current,g=or();Mv(f,g,s,o,null,null)},du.prototype.unmount=rm.prototype.unmount=function(){var s=this._internalRoot;if(s!==null){this._internalRoot=null;var o=s.containerInfo;Mv(s.current,2,null,s,null,null),Gc(),o[ea]=null}};function du(s){this._internalRoot=s}du.prototype.unstable_scheduleHydration=function(s){if(s){var o=sn();s={blockedOn:null,target:s,priority:o};for(var f=0;f<Xs.length&&o!==0&&o<Xs[f].priority;f++);Xs.splice(f,0,s),f===0&&Uv(s)}};var Wv=t.version;if(Wv!=="19.2.4")throw Error(r(527,Wv,"19.2.4"));Z.findDOMNode=function(s){var o=s._reactInternals;if(o===void 0)throw typeof s.render=="function"?Error(r(188)):(s=Object.keys(s).join(","),Error(r(268,s)));return s=h(o),s=s!==null?p(s):null,s=s===null?null:s.stateNode,s};var Aj={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:G,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var hu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!hu.isDisabled&&hu.supportsFiber)try{_t=hu.inject(Aj),It=hu}catch{}}return al.createRoot=function(s,o){if(!a(s))throw Error(r(299));var f=!1,g="",k=Zy,A=eb,F=tb;return o!=null&&(o.unstable_strictMode===!0&&(f=!0),o.identifierPrefix!==void 0&&(g=o.identifierPrefix),o.onUncaughtError!==void 0&&(k=o.onUncaughtError),o.onCaughtError!==void 0&&(A=o.onCaughtError),o.onRecoverableError!==void 0&&(F=o.onRecoverableError)),o=Ov(s,1,!1,null,null,f,g,null,k,A,F,Gv),s[ea]=o.current,Bf(s),new rm(o)},al.hydrateRoot=function(s,o,f){if(!a(s))throw Error(r(299));var g=!1,k="",A=Zy,F=eb,Y=tb,ie=null;return f!=null&&(f.unstable_strictMode===!0&&(g=!0),f.identifierPrefix!==void 0&&(k=f.identifierPrefix),f.onUncaughtError!==void 0&&(A=f.onUncaughtError),f.onCaughtError!==void 0&&(F=f.onCaughtError),f.onRecoverableError!==void 0&&(Y=f.onRecoverableError),f.formState!==void 0&&(ie=f.formState)),o=Ov(s,1,!0,o,f??null,g,k,ie,A,F,Y,Gv),o.context=Iv(null),f=o.current,g=or(),g=nt(g),k=Is(g),k.callback=null,Ms(f,k,g),f=g,o.current.lanes=f,Ce(o,f),Ur(o),s[ea]=o.current,Bf(s),new du(o)},al.version="19.2.4",al}var s_;function Gj(){if(s_)return lm.exports;s_=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),lm.exports=Vj(),lm.exports}var Wj=Gj();const qj=xd(Wj);function Kj(e,t){if(e instanceof RegExp)return{keys:!1,pattern:e};var n,r,a,l,u=[],c="",d=e.split("/");for(d[0]||d.shift();a=d.shift();)n=a[0],n==="*"?(u.push(n),c+=a[1]==="?"?"(?:/(.*))?":"/(.*)"):n===":"?(r=a.indexOf("?",1),l=a.indexOf(".",1),u.push(a.substring(1,~r?r:~l?l:a.length)),c+=~r&&!~l?"(?:/([^/]+?))?":"/([^/]+?)",~l&&(c+=(~r?"?":"")+"\\"+a.substring(l))):c+="/"+a;return{keys:u,pattern:new RegExp("^"+c+(t?"(?=$|/)":"/?$"),"i")}}var hm={exports:{}},fm={};/**
51
51
  * @license React
52
52
  * use-sync-external-store-shim.production.js
@@ -55,7 +55,7 @@ Error generating stack: `+g.message+`
55
55
  *
56
56
  * This source code is licensed under the MIT license found in the
57
57
  * LICENSE file in the root directory of this source tree.
58
- */var i_;function Yj(){if(i_)return fm;i_=1;var e=yd();function t(m,x){return m===x&&(m!==0||1/m===1/x)||m!==m&&x!==x}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,a=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(m,x){var y=x(),w=r({inst:{value:y,getSnapshot:x}}),C=w[0].inst,_=w[1];return l(function(){C.value=y,C.getSnapshot=x,d(C)&&_({inst:C})},[m,y,x]),a(function(){return d(C)&&_({inst:C}),m(function(){d(C)&&_({inst:C})})},[m]),u(y),y}function d(m){var x=m.getSnapshot;m=m.value;try{var y=x();return!n(m,y)}catch{return!0}}function h(m,x){return x()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?h:c;return fm.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,fm}var a_;function Xj(){return a_||(a_=1,hm.exports=Yj()),hm.exports}var Qj=Xj();const Jj=zj.useInsertionEffect,Zj=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",eN=Zj?N.useLayoutEffect:N.useEffect,tN=Jj||eN,n1=e=>{const t=N.useRef([e,(...n)=>t[0](...n)]).current;return tN(()=>{t[0]=e}),t[1]},nN="popstate",Xp="pushState",Qp="replaceState",rN="hashchange",o_=[nN,Xp,Qp,rN],sN=e=>{for(const t of o_)addEventListener(t,e);return()=>{for(const t of o_)removeEventListener(t,e)}},r1=(e,t)=>Qj.useSyncExternalStore(sN,e,t),l_=()=>location.search,iN=({ssrSearch:e}={})=>r1(l_,e!=null?()=>e:l_),c_=()=>location.pathname,aN=({ssrPath:e}={})=>r1(c_,e!=null?()=>e:c_),oN=(e,{replace:t=!1,state:n=null}={})=>history[t?Qp:Xp](n,"",e),lN=(e={})=>[aN(e),oN],u_=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[u_]>"u"){for(const e of[Xp,Qp]){const t=history[e];history[e]=function(){const n=t.apply(this,arguments),r=new Event(e);return r.arguments=arguments,dispatchEvent(r),n}}Object.defineProperty(window,u_,{value:!0})}const cN=(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())?"~"+t:t.slice(e.length)||"/",s1=(e="")=>e==="/"?"":e,uN=(e,t)=>e[0]==="~"?e.slice(1):s1(t)+e,dN=(e="",t)=>cN(d_(s1(e)),d_(t)),d_=e=>{try{return decodeURI(e)}catch{return e}},i1={hook:lN,searchHook:iN,parser:Kj,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,t,n)=>e(t,n)},a1=N.createContext(i1),ao=()=>N.useContext(a1),o1={},l1=N.createContext(o1),hN=()=>N.useContext(l1),bd=e=>{const[t,n]=e.hook(e);return[dN(e.base,t),n1((r,a)=>e.aroundNav(n,uN(r,e.base),a))]},Ln=()=>bd(ao()),Jp=(e,t,n,r)=>{const{pattern:a,keys:l}=t instanceof RegExp?{keys:!1,pattern:t}:e(t||"*",r),u=a.exec(n)||[],[c,...d]=u;return c!==void 0?[!0,(()=>{const h=l!==!1?Object.fromEntries(l.map((m,x)=>[m,d[x]])):u.groups;let p={...d};return h&&Object.assign(p,h),p})(),...r?[c]:[]]:[!1,null]},oo=e=>Jp(ao().parser,e,Ln()[0]),c1=({children:e,...t})=>{var p,m,x;const n=ao(),r=t.hook?i1:n;let a=r;const[l,u=t.ssrSearch??""]=((p=t.ssrPath)==null?void 0:p.split("?"))??[];l&&(t.ssrSearch=u,t.ssrPath=l),t.hrefs=t.hrefs??((m=t.hook)==null?void 0:m.hrefs),t.searchHook=t.searchHook??((x=t.hook)==null?void 0:x.searchHook);let c=N.useRef({}),d=c.current,h=d;for(let y in r){const w=y==="base"?r[y]+(t[y]??""):t[y]??r[y];d===h&&w!==h[y]&&(c.current=h={...h}),h[y]=w,(w!==r[y]||w!==a[y])&&(a=h)}return N.createElement(a1.Provider,{value:a,children:e})},h_=({children:e,component:t},n)=>t?N.createElement(t,{params:n}):typeof e=="function"?e(n):e,fN=e=>{let t=N.useRef(o1);const n=t.current;return t.current=Object.keys(e).length!==Object.keys(n).length||Object.entries(e).some(([r,a])=>a!==n[r])?e:n},ol=({path:e,nest:t,match:n,...r})=>{const a=ao(),[l]=bd(a),[u,c,d]=n??Jp(a.parser,e,l,t),h=fN({...hN(),...c});if(!u)return null;const p=d?N.createElement(c1,{base:d},h_(r,h)):h_(r,h);return N.createElement(l1.Provider,{value:h,children:p})},Jn=N.forwardRef((e,t)=>{const n=ao(),[r,a]=bd(n),{to:l="",href:u=l,onClick:c,asChild:d,children:h,className:p,replace:m,state:x,transition:y,...w}=e,C=n1(S=>{S.ctrlKey||S.metaKey||S.altKey||S.shiftKey||S.button!==0||(c==null||c(S),S.defaultPrevented||(S.preventDefault(),a(u,e)))}),_=n.hrefs(u[0]==="~"?u.slice(1):n.base+u,n);return d&&N.isValidElement(h)?N.cloneElement(h,{onClick:C,href:_}):N.createElement("a",{...w,onClick:C,href:_,className:p!=null&&p.call?p(r===u):p,children:h,ref:t})}),u1=e=>Array.isArray(e)?e.flatMap(t=>u1(t&&t.type===N.Fragment?t.props.children:t)):[e],mN=({children:e,location:t})=>{const n=ao(),[r]=bd(n);for(const a of u1(e)){let l=0;if(N.isValidElement(a)&&(l=Jp(n.parser,a.props.path,t||r,a.props.nest))[0])return N.cloneElement(a,{match:l})}return null},f_=e=>{let t;const n=new Set,r=(h,p)=>{const m=typeof h=="function"?h(t):h;if(!Object.is(m,t)){const x=t;t=p??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(y=>y(t,x))}},a=()=>t,c={setState:r,getState:a,getInitialState:()=>d,subscribe:h=>(n.add(h),()=>n.delete(h))},d=t=e(r,a,c);return c},pN=(e=>e?f_(e):f_),gN=e=>e;function xN(e,t=gN){const n=si.useSyncExternalStore(e.subscribe,si.useCallback(()=>t(e.getState()),[e,t]),si.useCallback(()=>t(e.getInitialState()),[e,t]));return si.useDebugValue(n),n}const m_=e=>{const t=pN(e),n=r=>xN(t,r);return Object.assign(n,t),n},Mn=(e=>e?m_(e):m_);function yN(){if(typeof document>"u")return"";const e=Array.from(document.scripts).find(a=>{const l=new URL(a.src,window.location.href).pathname;return l.includes("/assets/")||l.endsWith("/src/main.tsx")});if(!e)return"";const t=new URL(e.src,window.location.href).pathname,n=t.includes("/assets/")?"/assets/":"/src/",r=t.indexOf(n);return r>0?t.slice(0,r):""}const d1=yN();function ks(e){return e.startsWith("/")?`${d1}${e}`||"/":e}async function Se(e,t={}){const n=localStorage.getItem("openfox_token"),r={...t.headers instanceof Headers?Object.fromEntries(t.headers.entries()):t.headers,...n?{"x-session-token":n}:{}};return fetch(ks(e),{...t,headers:r})}async function p_(e,t,n){try{return(await Se(`/api/sessions/${e}/replay`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:t,...n!==void 0?{content:n}:{}})})).ok}catch{return!1}}async function h1(e,t,n){try{const r=await Se(`/api/sessions/${e}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:t,...n!==void 0?{title:n}:{}})});return r.ok?await r.json():null}catch{return null}}const Te={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars",DISPLAY_SHOW_SYNTAX_HIGHLIGHTING:"display.showSyntaxHighlighting",DISPLAY_THEME:"display.theme",DISPLAY_USER_PRESETS:"display.userPresets",DISPLAY_FOLLOW_SYSTEM_THEME:"display.followSystemTheme",DISPLAY_SYSTEM_THEME_PREFS:"display.systemThemePrefs",DISPLAY_SHOW_OPEN_IN_EDITOR:"display.showOpenInEditorLinks",DISPLAY_SHOW_CHANGELOG_ON_UPDATE:"display.showChangelogOnUpdate",DISPLAY_MAX_VISIBLE_ITEMS:"display.maxVisibleItems",DISPLAY_CUSTOM_CSS:"display.customCss",LLM_DYNAMIC_SYSTEM_PROMPT:"llm.dynamicSystemPrompt",CACHE_WARMING:"cache.warming",KEYBINDINGS:"keybindings",RETRY_PATTERNS:"agent.retryPatterns",SKILLS_DIRECTORIES:"skills.directories",SEARCH_ENGINE:"search.engine",SEARCH_TAVILY_API_KEY:"search.tavilyApiKey",SEARCH_SEARXNG_URL:"search.searxngUrl",SEARCH_SEARXNG_API_KEY:"search.searxngApiKey",TOOLS_USE_RTK:"tools.useRtk",TOOLS_SHELL:"tools.shell",CONFIRM_ON_WORKSPACE_ACTIONS:"tools.confirmOnWorkspaceActions",FEATURES_PER_SESSION_MCP:"features.perSessionMcp",PROXY_URL:"network.proxyUrl",DEFAULT_AGENT:"agent.defaultAgent"};function fu(e,t){return n=>({loading:{...n.loading,[e]:t}})}function g_(e,t){return n=>({settings:{...n.settings,[e]:t},loading:{...n.loading,[e]:!1}})}const Zp=[Te.DISPLAY_SHOW_THINKING,Te.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Te.DISPLAY_SHOW_STATS,Te.DISPLAY_SHOW_AGENT_DEFINITIONS,Te.DISPLAY_SHOW_WORKFLOW_BARS,Te.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING,Te.DISPLAY_FOLLOW_SYSTEM_THEME,Te.DISPLAY_SHOW_OPEN_IN_EDITOR,Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,Te.DISPLAY_MAX_VISIBLE_ITEMS];function Xi(){return{showThinking:Ht(e=>e.settings[Te.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:Ht(e=>e.settings[Te.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:Ht(e=>e.settings[Te.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:Ht(e=>e.settings[Te.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:Ht(e=>e.settings[Te.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true",showSyntaxHighlighting:Ht(e=>e.settings[Te.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING]??"true")==="true",maxVisibleItems:Number(Ht(e=>e.settings[Te.DISPLAY_MAX_VISIBLE_ITEMS]??"300"))}}const Ht=Mn(e=>({settings:{},loading:{},getSetting:async t=>{e(fu(t,!0));try{const r=await(await Se(`/api/settings/${t}`)).json();return e(g_(t,r.value??"")),r.value}catch{return e(fu(t,!1)),null}},getSettings:async t=>{if(t.length!==0)try{const r=await(await Se(`/api/settings?keys=${encodeURIComponent(t.join(","))}`)).json();e({settings:r,loading:Object.fromEntries(t.map(a=>[a,!1]))})}catch{e({loading:Object.fromEntries(t.map(n=>[n,!1]))})}},setSetting:async(t,n)=>{e(fu(t,!0));try{const a=await(await Se(`/api/settings/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})})).json();e(g_(t,a.value??""))}catch{e(fu(t,!1))}}})),ll=Object.freeze(Object.defineProperty({__proto__:null,DISPLAY_SETTINGS_KEYS:Zp,SETTINGS_KEYS:Te,useDisplaySettings:Xi,useSettingsStore:Ht},Symbol.toStringTag,{value:"Module"}));function bN(){const[e,t]=N.useState({offsetTop:0,height:window.innerHeight,keyboardVisible:!1}),n=N.useRef(window.innerHeight);return N.useEffect(()=>{const r=window.visualViewport;if(!r)return;const a=()=>{const l=r.offsetTop,u=r.height,c=n.current-u>100;t({offsetTop:l,height:u,keyboardVisible:c})};return a(),r.addEventListener("resize",a),r.addEventListener("scroll",a),()=>{r.removeEventListener("resize",a),r.removeEventListener("scroll",a)}},[]),e}function vN(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function $u(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class _N{constructor(t){we(this,"ws",null);we(this,"handlers",new Set);we(this,"statusHandler",null);we(this,"baseUrl");we(this,"isReconnecting",!1);we(this,"connectingPromise",null);we(this,"lastCloseCode",0);we(this,"reconnectAttempts",0);we(this,"manualReconnectScheduled",!1);we(this,"pwaRecoveryAttempted",!1);this.baseUrl=t}getUrl(){const t=localStorage.getItem("openfox_token");if(t){const n=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${n}token=${encodeURIComponent(t)}`}return this.baseUrl}setToken(t){localStorage.setItem("openfox_token",t)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(t){this.statusHandler=t}connect(){var t,n,r;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((r=this.ws)==null?void 0:r.readyState)===WebSocket.CONNECTING?(console.warn("[WS CLIENT] Connection already in progress, returning existing promise"),this.connectingPromise):(this.connectingPromise=new Promise((a,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const c=setTimeout(()=>{var d;((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var d;clearTimeout(c),this.isReconnecting=!1,this.reconnectAttempts=0,this.connectingPromise=null,(d=this.statusHandler)==null||d.call(this,"connected"),a()},this.ws.onclose=d=>{var h,p,m;clearTimeout(c),this.lastCloseCode=d.code,((h=this.ws)==null?void 0:h.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${d.code}`))):(this.connectingPromise=null,(m=this.statusHandler)==null||m.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=d=>{clearTimeout(c),console.error("WebSocket error:",d),this.connectingPromise=null,l(d)},this.ws.onmessage=d=>{try{const h=JSON.parse(d.data);vN(h)&&this.handlers.forEach(p=>p(h))}catch(h){console.error("Failed to parse WebSocket message:",h)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise)))}async recoverPwaStuckConnection(){if(this.pwaRecoveryAttempted||!window.matchMedia("(display-mode: standalone)").matches||!("serviceWorker"in navigator))return;this.pwaRecoveryAttempted=!0;const n=await navigator.serviceWorker.getRegistrations();n.length!==0&&(console.warn("[WS] PWA mode detected with stale service worker — unregistering and reloading"),await Promise.all(n.map(r=>r.unregister())),window.location.reload())}attemptReconnect(){var r;if(this.lastCloseCode===4e3&&this.hasToken()){console.warn("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(r=this.statusHandler)==null||r.call(this,"reconnecting");const n=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{this.reconnectAttempts>=3&&this.recoverPwaStuckConnection()})},n)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{this.recoverPwaStuckConnection()})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const r=$u(),a={id:r,type:t,payload:n};return this.ws.send(JSON.stringify(a)),r}subscribe(t){return this.handlers.add(t),()=>this.handlers.delete(t)}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}}const SN=window.location.protocol==="https:"?"wss:":"ws:";let dp=window.location.port;dp||(dp=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?"10469":window.location.protocol==="https:"?"443":"80");const wN=`${SN}//${window.location.hostname}:${dp}${ks("/ws")}`,Pt=new _N(wN),CN=3e4;function f1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"lmstudio":return"LM Studio";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"unknown":return"Other"}}const Qt=Mn((e,t)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,platform:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const n=await Se("/api/config");if(!n.ok)throw new Error("Failed to fetch config");const r=await n.json(),a=r.platform&&typeof r.platform=="object"?{isWSL:!!r.platform.isWSL,wslDistro:String(r.platform.wslDistro??"")}:null;e({version:r.version,model:r.model,maxContext:r.maxContext,llmUrl:r.llmUrl,llmStatus:r.llmStatus,backend:r.backend,providers:r.providers??[],activeProviderId:r.activeProviderId??null,defaultModelSelection:r.defaultModelSelection??null,platform:a,loading:!1})}catch(n){e({error:n instanceof Error?n.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const n=await Se("/api/model/refresh",{method:"POST"});if(!n.ok)throw new Error("Failed to refresh model");const r=await n.json();e({model:r.model,llmStatus:r.llmStatus,backend:r.backend})}catch(n){console.error("Failed to refresh model:",n)}},activateProvider:async n=>{const{activeProviderId:r,providers:a}=t();if(n===r)return!0;e({activating:!0,error:null});try{const l=await Se(`/api/providers/${n}/activate`,{method:"POST"});if(!l.ok){const c=await l.json();throw new Error(c.error??"Failed to activate provider")}const u=await l.json();return e({activeProviderId:u.activeProviderId,model:u.model,backend:u.backend,providers:a.map(c=>({...c,isActive:c.id===u.activeProviderId})),activating:!1}),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to switch provider",activating:!1}),!1}},setDefaultModel:async(n,r)=>{const{providers:a}=t();try{const l=await Se("/api/default-model",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:n,model:r})});if(!l.ok)return!1;const u=await l.json();return e({activeProviderId:n,model:r,defaultModelSelection:u.defaultModelSelection,providers:a.map(c=>({...c,isActive:c.id===n}))}),!0}catch{return!1}},refreshProviderModels:async n=>{e({activating:!0,error:null});try{const r=await Se(`/api/providers/${n}/refresh`,{method:"POST"});if(!r.ok){const u=await r.json();throw new Error(u.error??"Failed to refresh models")}const a=await r.json(),{providers:l}=t();return e({providers:l.map(u=>u.id===n?{...u,models:a.models,status:a.status}:u),activating:!1}),!0}catch(r){return e({error:r instanceof Error?r.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:n,refreshModel:r}=t();if(n)return;const a=setInterval(()=>{r()},CN);e({autoRefreshInterval:a})},stopAutoRefresh:()=>{const{autoRefreshInterval:n}=t();n&&(clearInterval(n),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:n,activeProviderId:r}=t();return n.find(a=>a.id===r)},getModelContext:n=>{const{providers:r,activeProviderId:a}=t(),l=r.find(c=>c.id===a);if(!l)return 2e5;const u=l.models.find(c=>c.id===n);return(u==null?void 0:u.contextWindow)??2e5}})),Ft=Mn((e,t)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const r=await(await Se("/api/projects")).json();e({projects:r.projects??[],loading:!1})}catch(n){console.error("Failed to load projects:",n),e({loading:!1})}},createProject:async(n,r)=>{try{const a=await Se("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n,workdir:r})});if(!a.ok){const u=await a.json().catch(()=>({}));return{error:{code:u.code||"UNKNOWN",path:u.path,message:u.error}}}const l=await a.json();return await t().listProjects(),l.project}catch{return null}},loadProject:async n=>{try{const r=await Se(`/api/projects/${n}`);if(!r.ok)return null;const a=await r.json();return e({currentProject:a.project}),t().projects.length===0&&await t().listProjects(),a.project}catch{return null}},updateProject:async(n,r)=>{var a;try{const l=await Se(`/api/projects/${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!l.ok)return null;const u=await l.json();return((a=t().currentProject)==null?void 0:a.id)===n&&e({currentProject:u.project}),await t().listProjects(),u.project}catch{return null}},deleteProject:async n=>{var r;try{return(await Se(`/api/projects/${n}`,{method:"DELETE"})).ok?(await t().listProjects(),((r=t().currentProject)==null?void 0:r.id)===n&&e({currentProject:null}),!0):!1}catch{return!1}},toggleStar:async(n,r)=>{var a;try{const l=await Se(`/api/projects/${n}/star`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isStarred:r})});if(!l.ok)return!1;if(((a=t().currentProject)==null?void 0:a.id)===n){const u=await l.json();e({currentProject:u.project})}return await t().listProjects(),!0}catch{return!1}},clearProject:()=>{e({currentProject:null})}})),ui=async(e,t,n)=>{try{const r=await Se(t,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return r.ok?{success:!0}:{success:!1,error:(await r.json()).error}}catch{return{success:!1,error:"Network error"}}},vd=async(e,t,n)=>{try{const r=await Se(e,{method:"POST",body:n?JSON.stringify({destination:n}):void 0,headers:n?{"Content-Type":"application/json"}:void 0}),a=await r.json();return r.ok?(await t(),{success:!0}):{success:!1,error:a.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}};function m1(e){let t=null;function n(){t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))}return n}let mu=[];const wl=Mn()((e,t)=>{function n(){if(mu.length===0)return;const a=mu;mu=[],e(l=>{const u={...l.logs};for(const c of a){const d=u[c.processId]??[];u[c.processId]=[...d,{offset:d.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:u}})}const r=m1(n);return{processes:[],logs:{},loading:!1,setProcesses:a=>e({processes:a}),addProcess:a=>e(l=>({processes:[...l.processes,a]})),updateProcess:(a,l)=>e(u=>({processes:u.processes.map(c=>c.id===a?{...c,...l}:c)})),removeProcess:a=>e(l=>({processes:l.processes.filter(u=>u.id!==a),logs:Object.fromEntries(Object.entries(l.logs).filter(([u])=>u!==a))})),stopProcess:async(a,l)=>{try{(await Se(`/api/sessions/${l}/background-process/${a}/stop`,{method:"POST"})).ok&&t().removeProcess(a)}catch{}},appendLog:(a,l,u)=>{mu.push({processId:a,stream:l,content:u}),r()},setLogs:(a,l)=>e(u=>({logs:{...u.logs,[a]:l}})),clearLogs:a=>e(l=>({logs:{...l.logs,[a]:[]}})),handleMessage:(a,l)=>{switch(a){case"backgroundProcess.started":{const{processId:u,name:c,pid:d,status:h}=l;e(p=>({processes:[...p.processes,{id:u,sessionId:"",name:c,command:"",cwd:"",pid:d,status:h,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const u=l.processId,c=l.stream,d=l.content;t().appendLog(u,c,d);break}case"backgroundProcess.exited":{const u=l.processId,c=l.exitCode;e(d=>({processes:d.processes.map(h=>h.id===u?{...h,status:"exited",exitCode:c}:h)}));break}case"backgroundProcess.removed":{const u=l.processId;t().removeProcess(u);break}}}}}),kN={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let zu=null;function EN(e){zu=e}function Pi(){return kN}function mm(){zu==null||zu()}let pu=[];const Qn=Mn()((e,t)=>{function n(){if(pu.length===0)return;const a=pu;pu=[],e(l=>({logs:[...l.logs,...a]}))}const r=m1(n);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:a=>{t().workdir!==a&&(e({workdir:a,status:null,logs:[],config:null,loading:!0}),a&&(t().fetchStatus(),t().fetchConfig()))},fetchStatus:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server?workdir=${encodeURIComponent(a)}`)).json();e({status:u,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/config?workdir=${encodeURIComponent(a)}`)).json();e({config:u.config??null})}catch{}},fetchLogs:async()=>{const a=t().workdir;if(a)try{const c=(await(await Se(`/api/dev-server/logs?workdir=${encodeURIComponent(a)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:c})}catch{}},start:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/start?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},stop:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/stop?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u})}catch{}},restart:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/restart?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},saveConfig:async a=>{const l=t().workdir;if(l)try{const c=await(await Se(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();e({config:c.config??a}),t().fetchStatus()}catch{}},handleMessage:a=>{const l=t().workdir;if(l)switch(a.type){case"devServer.output":{const u=a.payload;if(u.workdir!==l)return;pu.push({stream:u.stream,content:u.content}),r();break}case"devServer.state":{const u=a.payload;if(u.workdir!==l)return;e(c=>({status:c.status?{...c.status,state:u.state,errorMessage:u.errorMessage,...u.url!==void 0?{url:u.url}:{},...u.inspectProxyPort!==void 0?{inspectProxyPort:u.inspectProxyPort}:{}}:{state:u.state,url:u.url??null,hotReload:!1,config:null,errorMessage:u.errorMessage,inspectProxyPort:u.inspectProxyPort??null}}));break}}}}}),jN=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],NN=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],p1={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ii={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},g1={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},hp={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ii},waiting_for_user:{...ii},phase_done:{...ii},phase_blocked:{...ii},new_message:{...g1}},agentOverrides:{}};function x1(e,t,n){var l;const r=e.events[t];if(!n)return r;const a=(l=e.agentOverrides[n])==null?void 0:l[t];return a?{soundEnabled:a.soundEnabled??r.soundEnabled,browserNotification:a.browserNotification??r.browserNotification,customSoundUrl:a.customSoundUrl!==void 0?a.customSoundUrl:r.customSoundUrl}:r}const Bi=Mn((e,t)=>({settings:hp,loaded:!1,load:()=>{Ht.getState().getSetting(Te.NOTIFICATION_SETTINGS);const r=Ht.subscribe(l=>{const u=l.settings[Te.NOTIFICATION_SETTINGS];if(u!==void 0)try{const c=JSON.parse(u);e({settings:x_(c),loaded:!0})}catch{e({loaded:!0})}}),a=Ht.getState().settings[Te.NOTIFICATION_SETTINGS];if(a)try{const l=JSON.parse(a);e({settings:x_(l),loaded:!0})}catch{e({loaded:!0})}return r},update:n=>{e({settings:n}),pm(n)},updateEvent:(n,r)=>{const a=t().settings,l={...a,events:{...a.events,[n]:{...a.events[n],...r}}};e({settings:l}),pm(l)},updateAgentOverride:(n,r,a)=>{var d;const l=t().settings,u={...l.agentOverrides};if(a===null){if(u[n]){const h={...u[n]};delete h[r],Object.keys(h).length===0?delete u[n]:u[n]=h}}else u[n]={...u[n],[r]:{...((d=u[n])==null?void 0:d[r])??{},...a}};const c={...l,agentOverrides:u};e({settings:c}),pm(c)}}));function pm(e){Ht.getState().setSetting(Te.NOTIFICATION_SETTINGS,JSON.stringify(e))}function x_(e){var t,n,r,a,l;return{soundEnabled:e.soundEnabled??hp.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??hp.browserNotificationEnabled,events:{complete:{...ii,...(t=e.events)==null?void 0:t.complete},waiting_for_user:{...ii,...(n=e.events)==null?void 0:n.waiting_for_user},phase_done:{...ii,...(r=e.events)==null?void 0:r.phase_done},phase_blocked:{...ii,...(a=e.events)==null?void 0:a.phase_blocked},new_message:{...g1,...(l=e.events)==null?void 0:l.new_message}},agentOverrides:e.agentOverrides??{}}}const y_=new Map;function TN(e){let t=y_.get(e);return t||(t=new Audio(ks(e)),t.volume=.5,y_.set(e,t)),t}let y1=typeof Notification<"u"?Notification.permission:"denied";function AN(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(y1=e,e))}const LN={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},DN={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function RN(e){typeof Notification>"u"||y1==="granted"&&(document.hasFocus()||new Notification(LN[e],{body:DN[e],icon:ks("/fox.svg"),tag:`openfox-${e}`}))}function Vl(e,t){const{settings:n}=Bi.getState(),r=x1(n,e,t);if(n.soundEnabled&&r.soundEnabled){const a=r.customSoundUrl??p1[e],l=TN(a);l.currentTime=0,l.play().catch(()=>{})}n.browserNotificationEnabled&&r.browserNotification&&RN(e)}const ON=e=>Vl("complete",e),IN=e=>Vl("phase_done",e),MN=e=>Vl("phase_blocked",e),gm=e=>Vl("waiting_for_user",e),PN=e=>Vl("new_message",e),b_=new Map;function Wa(e,t){var l;const n=t===((l=e.currentSession)==null?void 0:l.id)?e.currentSession:null,r=e.sessions.find(u=>u.id===t),a=(n==null?void 0:n.mode)??(r==null?void 0:r.mode);return a==="planner"?"planner":a==="builder"?"build":"planner"}function BN(e,t){if(e.type==="chat.done"){const n=e.payload,r=Wa(t,e.sessionId),a=n.agentType??r;n.reason==="complete"&&ON(a),n.reason==="waiting_for_user"&&gm(a);return}if(e.type==="chat.path_confirmation"){const n=Wa(t,e.sessionId);gm(n);return}if(e.type==="session.confirmation_pending"){const n=Wa(t,e.sessionId);gm(n);return}if(e.type==="task.completed"){const n=Wa(t,e.sessionId);IN(n);return}if(e.type==="phase.changed"&&e.sessionId){const n=e.payload,r=b_.get(e.sessionId)??null;if(b_.set(e.sessionId,n.phase),r===n.phase)return;const a=Wa(t,e.sessionId);n.phase==="blocked"&&MN(a)}}const Al=Mn(e=>({servers:[],setServers:t=>e({servers:t}),fetchServers:async()=>{try{const t=await Se("/api/mcp/servers");if(!t.ok)return;const r=((await t.json()).servers??[]).sort((a,l)=>a.name.localeCompare(l.name));e({servers:r})}catch{}}})),xm=new Set;function dn(e,t){return t!==null&&e.sessionId===t}function $N(e,t,n){return e.id!==void 0||dn(e,t)||n===!0&&e.sessionId!==void 0}function zN(e,t){return e.includes(t)?e:[...e,t]}function v_(e,t){return e.filter(n=>n!==t)}function HN(e,t){const n=e.find(l=>l.id===t.id),r=t.messageCount??t.messages.length,a=n?{...n,projectId:t.projectId,workdir:t.workdir,workspace:t.workspace,branch:t.branch,mode:t.mode,phase:t.phase,isRunning:t.isRunning&&n.isRunning!==!1,messageCount:r,criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length}:{id:t.id,projectId:t.projectId,workdir:t.workdir,workspace:t.workspace,branch:t.branch,mode:t.mode,phase:t.phase,isRunning:t.isRunning,createdAt:"",updatedAt:"",criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length,messageCount:r};return n?e.map(l=>l.id===t.id?a:l):[a,...e]}function ym(e,t){const n=e.findIndex(r=>r.callId===t.callId);if(n>=0){const r=[...e];return r[n]=t,r}return[...e,t]}function UN(e,t,n){return e.map(r=>{const a=(n==null?void 0:n.id)===r.id?n:null,l=t.find(u=>u.id===r.id);return{...r,title:r.title??(l==null?void 0:l.title),mode:(a==null?void 0:a.mode)??(l==null?void 0:l.mode)??r.mode,phase:(a==null?void 0:a.phase)??(l==null?void 0:l.phase)??r.phase,isRunning:r.isRunning&&(l==null?void 0:l.isRunning)!==!1,messageCount:r.messageCount,recentUserPrompts:r.recentUserPrompts}})}function __(e,t,n,r){var c;const a=e.sessionId,l=(c=n().currentSession)==null?void 0:c.id,u=a&&a!==l;if(t(d=>({sessions:d.sessions.map(h=>h.id===a?r(h):h)})),!u){const d=n().currentSession;if(d){const h=r(d);t(()=>({currentSession:h}))}}}function S_(e,t,n){var c,d,h,p,m,x,y,w,C,_,S,v,b,E,j,T,D,L,I,P,W,H;const r=n();BN(e,r);const a=((c=r.currentSession)==null?void 0:c.id)??null,l=()=>{const R=e.sessionId;!R||R===a||t(U=>({unreadSessionIds:zN(U.unreadSessionIds,R)}))},u=(R,U,V)=>({messages:R.messages.map(G=>G.id===U?V(G):G)});switch(e.type){case"session.state":{const R=e.payload;if(!$N(e,a,r.pendingSessionCreate))break;const U=n().pendingSessionCreate===!0,V=R.pendingConfirmations??[],G=R.session.id,Z={...n().crossSessionConfirmations};delete Z[G],t({currentSession:R.session,sessions:HN(n().sessions,R.session),unreadSessionIds:v_(n().unreadSessionIds,G),messages:R.messages,hiddenCount:R.hiddenCount??0,currentTodos:[],pendingPathConfirmations:V,crossSessionConfirmations:Z,sessionsWithPendingConfirmations:Object.keys(Z),pendingQuestions:R.pendingQuestions??[],...U?{pendingSessionCreate:R.session.id}:{}});break}case"session.list":{const R=e.payload;t(U=>({sessions:UN(R.sessions,U.sessions,U.currentSession)}));break}case"session.created":{const R=e.payload;t(U=>({sessions:U.sessions.some(V=>V.id===R.session.id)?U.sessions.map(V=>V.id===R.session.id?{...V,...R.session}:V):[R.session,...U.sessions]}));break}case"session.deleted":{const R=e.payload;t(U=>({unreadSessionIds:v_(U.unreadSessionIds,R.sessionId)})),n().listSessions();break}case"session.deletedAll":{n().listSessions();break}case"session.running":{const R=e.payload;__(e,t,n,U=>({...U,isRunning:R.isRunning})),R.isRunning||t({abortInProgress:!1,queuedMessages:[]}),R.isRunning&&t({restoredInput:null});break}case"chat.message":{if(!dn(e,((d=n().currentSession)==null?void 0:d.id)??null)){l();break}const R=e.payload;t(U=>{if(U.messages.some(G=>G.id===R.message.id))return U;const V=R.message.role==="user";return{messages:[...U.messages,R.message],sessions:U.sessions.map(G=>G.id===e.sessionId&&V?{...G,messageCount:G.messageCount+1}:G)}});break}case"chat.message_updated":{if(!dn(e,((h=n().currentSession)==null?void 0:h.id)??null)){l();break}const R=e.payload,U=n().messages.find(V=>V.id===R.messageId);R.updates.isStreaming===!1&&(U==null||U.isStreaming),t(V=>({messages:V.messages.map(G=>G.id===R.messageId?{...G,...R.updates}:G)}));break}case"chat.delta":{if(!dn(e,((p=n().currentSession)==null?void 0:p.id)??null)){l();break}const R=e.payload;if(!xm.has(R.messageId)){xm.add(R.messageId);const V=R.subAgentType?"sub-agent":Wa(n(),e.sessionId);PN(V)}const U=Pi();U.messageId=R.messageId,U.deltaContent+=R.content,mm();break}case"chat.thinking":{if(!dn(e,((m=n().currentSession)==null?void 0:m.id)??null)){l();break}const R=e.payload,U=Pi();U.messageId=R.messageId,U.thinkingContent+=R.content,mm();break}case"chat.tool_preparing":{if(!dn(e,((x=n().currentSession)==null?void 0:x.id)??null)){l();break}const R=e.payload;t(U=>{var O;const V=U.messages.find(M=>M.id===R.messageId);if(!V)return{};if((O=V.toolCalls)==null?void 0:O.find((M,q)=>q===R.index))return{};const Z=V.preparingToolCalls??[],X=Z.findIndex(M=>M.index===R.index);let $;return X>=0?$=Z.map((M,q)=>q===X?{...M,arguments:R.arguments}:M):$=[...Z,{index:R.index,name:R.name,...R.arguments?{arguments:R.arguments}:{}}],{messages:U.messages.map(M=>M.id===R.messageId?{...M,preparingToolCalls:$}:M)}});break}case"chat.tool_call":{if(!dn(e,((y=n().currentSession)==null?void 0:y.id)??null)){l();break}const R=e.payload,U=V=>{var O;const G=(V.toolCalls??[]).length,Z=(O=V.preparingToolCalls)==null?void 0:O.filter(M=>M.index!==G),X=Pi(),$=X.toolOutput.filter(M=>M.callId===R.callId);return $.length>0&&(X.toolOutput=X.toolOutput.filter(M=>M.callId!==R.callId)),{...V,toolCalls:[...V.toolCalls??[],{id:R.callId,name:R.tool,arguments:R.args,startedAt:Date.now(),...$.length>0?{streamingOutput:$.map(M=>({stream:M.stream,content:M.content,timestamp:Date.now()}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};t(V=>u(V,R.messageId,U));break}case"chat.tool_output":{if(!dn(e,((w=n().currentSession)==null?void 0:w.id)??null)){l();break}const R=e.payload,U=Pi();U.messageId=R.messageId,U.toolOutput.push({messageId:R.messageId,callId:R.callId,stream:R.stream,content:R.output}),mm();break}case"chat.tool_result":{if(!dn(e,((C=n().currentSession)==null?void 0:C.id)??null)){l();break}const R=e.payload,U=V=>{var Z;const G=(Z=V.toolCalls)==null?void 0:Z.map(X=>X.id===R.callId?{...X,result:R.result}:X);return{...V,toolCalls:G}};t(V=>u(V,R.messageId,U));break}case"chat.vision_fallback":{if(!dn(e,((_=n().currentSession)==null?void 0:_.id)??null)){l();break}const R=e.payload;t(U=>{const V=`${R.messageId}-${R.attachmentId}`,G={...U.visionFallbackByMessage};return G[V]={type:R.type,attachmentId:R.attachmentId,filename:R.filename,description:R.description},{visionFallbackByMessage:G}});break}case"chat.todo":{if(!dn(e,((S=n().currentSession)==null?void 0:S.id)??null)){l();break}const R=e.payload;t({currentTodos:R.todos});break}case"chat.progress":{if(!dn(e,((v=n().currentSession)==null?void 0:v.id)??null)){l();break}const R=e.payload;console.warn("Progress:",R.message,R.phase);break}case"chat.format_retry":{if(!dn(e,((b=n().currentSession)==null?void 0:b.id)??null)){l();break}const R=e.payload;console.warn("Format retry:",R.attempt,"/",R.maxAttempts);break}case"chat.done":{if(!dn(e,((E=n().currentSession)==null?void 0:E.id)??null)){l();break}const R=Pi();R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[],xm.delete(e.payload.messageId);const U=e.payload,V=U.stats;t(G=>({messages:G.messages.map(Z=>Z.id===U.messageId?{...Z,isStreaming:!1,stats:V??Z.stats,completeReason:U.reason,preparingToolCalls:void 0}:Z),visionFallbackByMessage:{}}));break}case"chat.error":{if(!dn(e,((j=n().currentSession)==null?void 0:j.id)??null)){l();break}const R=Pi(),U=e.payload;console.error("Chat error:",U.error,"recoverable:",U.recoverable),U.recoverable||(R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[]),t(V=>({error:{code:"CHAT_ERROR",message:U.error},...U.recoverable?{}:{messages:V.messages}}));break}case"chat.path_confirmation":{const R=e.sessionId,U=R===(((T=n().currentSession)==null?void 0:T.id)??null),V=e.payload,G={callId:V.callId,tool:V.tool,paths:V.paths,workdir:V.workdir,reason:V.reason};if(!U){l(),R&&t(Z=>({crossSessionConfirmations:{...Z.crossSessionConfirmations,[R]:ym(Z.crossSessionConfirmations[R]??[],G)},sessionsWithPendingConfirmations:Z.sessionsWithPendingConfirmations.includes(R)?Z.sessionsWithPendingConfirmations:[...Z.sessionsWithPendingConfirmations,R]}));break}t(Z=>({pendingPathConfirmations:ym(Z.pendingPathConfirmations,G)}));break}case"session.confirmation_pending":{const R=e.sessionId,U=e.payload,V={callId:U.callId,tool:U.tool,paths:U.paths,workdir:U.workdir,reason:U.reason};R&&t(G=>({crossSessionConfirmations:{...G.crossSessionConfirmations,[R]:ym(G.crossSessionConfirmations[R]??[],V)},sessionsWithPendingConfirmations:G.sessionsWithPendingConfirmations.includes(R)?G.sessionsWithPendingConfirmations:[...G.sessionsWithPendingConfirmations,R]}));break}case"session.confirmation_resolved":{const R=e.sessionId,U=e.payload;R&&t(V=>{const Z=(V.crossSessionConfirmations[R]??[]).filter($=>$.callId!==U.callId),X={...V.crossSessionConfirmations};return Z.length===0?delete X[R]:X[R]=Z,{crossSessionConfirmations:X,sessionsWithPendingConfirmations:Object.keys(X)}});break}case"chat.ask_user":{if(!dn(e,((D=n().currentSession)==null?void 0:D.id)??null)){l();return}const R=e.payload,U={callId:R.callId,question:R.question,type:R.type??"text",options:R.options??void 0};t(V=>({pendingQuestions:[...V.pendingQuestions.filter(G=>G.callId!==R.callId),U]}));break}case"mode.changed":{if(!dn(e,((L=n().currentSession)==null?void 0:L.id)??null)){l();break}const R=e.payload;t(U=>({currentSession:U.currentSession?{...U.currentSession,mode:R.mode}:null}));break}case"phase.changed":{const R=e.payload;__(e,t,n,U=>({...U,phase:R.phase}));break}case"criteria.updated":{if(!dn(e,((I=n().currentSession)==null?void 0:I.id)??null)){l();break}const R=e.payload;t(U=>({currentSession:U.currentSession?{...U.currentSession,criteria:R.criteria}:null}));break}case"metadata.updated":{if(!dn(e,((P=n().currentSession)==null?void 0:P.id)??null)){l();break}const R=e.payload;t(U=>({currentSession:U.currentSession?{...U.currentSession,metadataEntries:{...U.currentSession.metadataEntries,[R.key]:R.entries}}:null}));break}case"context.state":{const R=e.payload,U=dn(e,((W=n().currentSession)==null?void 0:W.id)??null);R.subAgentId?U&&n().updateSubAgentContextState(R.subAgentId,R.context):U?t({contextState:R.context}):l();break}case"session.name_generated":{const R=e.payload,U=e.sessionId,V=(H=n().currentSession)==null?void 0:H.id;t(G=>{const Z=G.sessions.map($=>$.id===U?{...$,title:R.name,updatedAt:new Date().toISOString()}:$),X=V===U?G.currentSession?{...G.currentSession,title:R.name,updatedAt:new Date().toISOString()}:null:G.currentSession;return{sessions:Z,currentSession:X}});break}case"queue.state":{const R=e.payload;t({queuedMessages:R.messages??[]});break}case"mcp.servers.changed":{const R=e.payload;if(R!=null&&R.servers){const U=[...R.servers].sort((V,G)=>V.name.localeCompare(G.name));Al.getState().setServers(U)}else window.dispatchEvent(new CustomEvent("mcp-servers-changed"));break}case"git.status":{const R=e.payload;t({gitStatus:{branch:R.branch,diff:R.diff}});break}case"devServer.output":case"devServer.state":{Qn.getState().handleMessage(e);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{wl.getState().handleMessage(e.type,e.payload);break}case"error":{const R=e.payload;console.error("Server error:",R),t({error:{code:R.code,message:R.message}});break}}}let cl=!1,Fr=null;const bm=new Set,gu=new Map;function w_(e,t,n){return e==null?void 0:e.map(r=>{const a=t.filter(l=>l.callId===r.id);return a.length===0?r:(n.add(r.id),{...r,streamingOutput:[...r.streamingOutput??[],...a.map(l=>({stream:l.stream,content:l.content,timestamp:Date.now()}))]})})}async function C_(e,t,n,r,a){try{const u=await(await Se(`/api/sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,attachments:n,messageKind:r})})).json();u.queueState&&a({queuedMessages:u.queueState})}catch(l){console.error("Error queueing message:",l)}}const Re=Mn((e,t)=>(EN(()=>{const n=Pi();if(!n.messageId)return;const r=n.deltaContent.length>0,a=n.thinkingContent.length>0,l=n.toolOutput.length>0;if(!r&&!a&&!l)return;const u=n.deltaContent,c=n.thinkingContent,d=n.toolOutput;n.deltaContent="",n.thinkingContent="",n.toolOutput=[],e(h=>{const p=h.messages.find(m=>m.id===n.messageId);if(p){const m={...p};if(r&&(m.content=m.content+u),a&&(m.thinkingContent=(m.thinkingContent??"")+c),l){const x=new Set;m.toolCalls=w_(m.toolCalls,d,x);const y=d.filter(w=>!x.has(w.callId));y.length>0&&n.toolOutput.push(...y)}return{messages:h.messages.map(x=>x.id===n.messageId?m:x)}}if(l){const m=new Set,x=h.messages.map(w=>w.id!==n.messageId?w:{...w,toolCalls:w_(w.toolCalls,d,m)}),y=d.filter(w=>!m.has(w.callId));return y.length>0&&n.toolOutput.push(...y),{messages:x}}return h})}),{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],hiddenCount:0,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmations:[],crossSessionConfirmations:{},sessionsWithPendingConfirmations:[],pendingQuestions:[],visionFallbackByMessage:{},gitStatus:null,queuedMessages:[],abortInProgress:!1,restoredInput:null,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,pendingUpdate:!1,connect:async()=>{if(t().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let r=!1;try{r=(await(await Se("/api/auth")).json()).requiresAuth}catch{}if(r&&!Pt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Pt.onStatusChange(a=>{var l;if(e({connectionStatus:a}),a==="connected"){t().listSessions(void 0),Ft.getState().listProjects();const u=(l=t().currentSession)==null?void 0:l.id;u&&t().loadSession(u)}});try{await Pt.connect(),cl||(cl=!0,Fr=Pt.subscribe(a=>{S_(a,e,t)}))}catch(a){console.error("Failed to connect:",a);const l=Pt.getLastCloseCode();if(!Pt.hasToken()&&(l===1006||l===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}Fr&&(Fr(),Fr=null),cl=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Pt.disconnect(),Fr&&(Fr(),Fr=null),cl=!1,e({connectionStatus:"disconnected"}),t().connect()},disconnect:()=>{Pt.disconnect(),Fr&&(Fr(),Fr=null),cl=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async n=>{try{const r=await fetch(ks("/api/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n})});if(!r.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:a}=await r.json();Pt.setToken(a),e({showPasswordModal:!1}),t().connect();const{listProjects:l}=Ft.getState(),{fetchConfig:u}=Qt.getState();l(),u(),t().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Pt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(n,r)=>{if(t().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const l=await Se("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:n,title:r})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();try{Pt.send("session.load",{sessionId:u.session.id})}catch{}return u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async n=>{if(!bm.has(n)){bm.add(n);try{const r=t().currentSession;if(!r||r.id!==n){const d=r==null?void 0:r.id,h=t().pendingPathConfirmations,m={...t().crossSessionConfirmations};d&&h.length>0&&(m[d]=[...m[d]??[],...h]),e({currentSession:null,unreadSessionIds:t().unreadSessionIds.filter(x=>x!==n),subAgentContextStates:{},messages:[],currentTodos:[],contextState:null,pendingPathConfirmations:[],pendingQuestions:[],queuedMessages:[],abortInProgress:!1,restoredInput:null,error:null,gitStatus:null,pendingSessionCreate:!1,crossSessionConfirmations:m,sessionsWithPendingConfirmations:Object.keys(m)})}else e({unreadSessionIds:t().unreadSessionIds.filter(d=>d!==n)});const a=await Se(`/api/sessions/${n}`);if(!a.ok)return;const l=await a.json(),u=l.messages??[],c={...t().crossSessionConfirmations};delete c[n],e({currentSession:l.session,messages:u,hiddenCount:l.hiddenCount??0,contextState:l.contextState,queuedMessages:l.queueState??[],pendingPathConfirmations:l.pendingConfirmations??[],pendingQuestions:l.pendingQuestions??[],crossSessionConfirmations:c,sessionsWithPendingConfirmations:Object.keys(c)}),Pt.send("session.load",{sessionId:n});try{const d=await Se(`/api/sessions/${n}/background-processes`);if(d.ok){const h=await d.json();wl.getState().setProcesses(h.processes??[])}}catch{}}catch{}finally{bm.delete(n)}}},listSessions:async(n,r=20)=>{const a=n??"global";if(gu.has(a))return gu.get(a);const l=(async()=>{var u;try{const c=new URLSearchParams;c.set("limit",String(r)),n&&c.set("projectId",n);const h=await(await Se(`/api/sessions?${c.toString()}`)).json(),p=h.sessions??[];e(x=>({sessions:p.map(y=>{var C,_;const w=x.sessions.find(S=>S.id===y.id);return{...y,title:y.title??(w==null?void 0:w.title),mode:((C=x.currentSession)==null?void 0:C.id)===y.id?x.currentSession.mode:(w==null?void 0:w.mode)??y.mode,phase:((_=x.currentSession)==null?void 0:_.id)===y.id?x.currentSession.phase:(w==null?void 0:w.phase)??y.phase,isRunning:y.isRunning&&(w==null?void 0:w.isRunning)!==!1,messageCount:y.messageCount,recentUserPrompts:y.recentUserPrompts}}),sessionsHasMore:n?h.hasMore??!1:!0}));const m=h.pendingConfirmationsBySession;if(m){const x=(u=t().currentSession)==null?void 0:u.id,y={};for(const[w,C]of Object.entries(m))w!==x&&(y[w]=C);e({crossSessionConfirmations:y,sessionsWithPendingConfirmations:Object.keys(y)})}}catch{}finally{gu.delete(a)}})();return gu.set(a,l),l},loadMoreSessions:async n=>{const r=t();if(!(r.sessionsPaginationLoading||!r.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const a=new URLSearchParams;a.set("limit","20"),a.set("offset",String(r.sessions.length)),a.set("projectId",n);const u=await(await Se(`/api/sessions?${a.toString()}`)).json(),c=u.sessions??[];e(d=>({sessions:[...d.sessions,...c.map(h=>{const p=d.sessions.find(m=>m.id===h.id);return(p==null?void 0:p.isRunning)===!1?{...h,isRunning:!1}:h})],sessionsHasMore:u.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async n=>{var r;try{return(await Se(`/api/sessions/${n}`,{method:"DELETE"})).ok?(await t().listSessions(),((r=t().currentSession)==null?void 0:r.id)===n&&t().clearSession(),!0):!1}catch{return!1}},renameSession:async(n,r)=>{var a;try{const l=await Se(`/api/sessions/${n}/title`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:r})});if(!l.ok)return!1;if(await t().listSessions(),((a=t().currentSession)==null?void 0:a.id)===n){const c=await l.json();c.session&&e({currentSession:c.session})}return!0}catch{return!1}},deleteAllSessions:async n=>{try{return(await Se(`/api/projects/${n}/sessions`,{method:"DELETE"})).ok?(await t().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{e(n=>({currentSession:null,messages:[],hiddenCount:0,currentTodos:[],contextState:null,restoredInput:null,pendingSessionCreate:!1,unreadSessionIds:n.currentSession?n.unreadSessionIds.filter(r=>r!==n.currentSession.id):n.unreadSessionIds}))},sendMessage:async(n,r,a)=>{var u;e({error:null});const l=(u=t().currentSession)==null?void 0:u.id;if(l)try{const c=n==null?void 0:n.trim(),d=r&&r.length>0,h={};c&&(h.content=n),d&&(h.attachments=r),a!=null&&a.messageKind&&(h.messageKind=a.messageKind);const m=await(await Se(`/api/sessions/${l}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})).json();m.queueState&&e({queuedMessages:m.queueState})}catch(c){console.error("Error sending message:",c)}},stopGeneration:async()=>{var r;const n=(r=t().currentSession)==null?void 0:r.id;if(n&&!t().abortInProgress){e({abortInProgress:!0});try{const l=await(await Se(`/api/sessions/${n}/stop`,{method:"POST"})).json();if(l.queuedMessages&&l.queuedMessages.length>0){const u=l.queuedMessages.map(c=>c.content).join(`
58
+ */var i_;function Yj(){if(i_)return fm;i_=1;var e=yd();function t(m,x){return m===x&&(m!==0||1/m===1/x)||m!==m&&x!==x}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,a=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(m,x){var y=x(),w=r({inst:{value:y,getSnapshot:x}}),C=w[0].inst,_=w[1];return l(function(){C.value=y,C.getSnapshot=x,d(C)&&_({inst:C})},[m,y,x]),a(function(){return d(C)&&_({inst:C}),m(function(){d(C)&&_({inst:C})})},[m]),u(y),y}function d(m){var x=m.getSnapshot;m=m.value;try{var y=x();return!n(m,y)}catch{return!0}}function h(m,x){return x()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?h:c;return fm.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,fm}var a_;function Xj(){return a_||(a_=1,hm.exports=Yj()),hm.exports}var Qj=Xj();const Jj=zj.useInsertionEffect,Zj=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",eN=Zj?N.useLayoutEffect:N.useEffect,tN=Jj||eN,n1=e=>{const t=N.useRef([e,(...n)=>t[0](...n)]).current;return tN(()=>{t[0]=e}),t[1]},nN="popstate",Xp="pushState",Qp="replaceState",rN="hashchange",o_=[nN,Xp,Qp,rN],sN=e=>{for(const t of o_)addEventListener(t,e);return()=>{for(const t of o_)removeEventListener(t,e)}},r1=(e,t)=>Qj.useSyncExternalStore(sN,e,t),l_=()=>location.search,iN=({ssrSearch:e}={})=>r1(l_,e!=null?()=>e:l_),c_=()=>location.pathname,aN=({ssrPath:e}={})=>r1(c_,e!=null?()=>e:c_),oN=(e,{replace:t=!1,state:n=null}={})=>history[t?Qp:Xp](n,"",e),lN=(e={})=>[aN(e),oN],u_=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[u_]>"u"){for(const e of[Xp,Qp]){const t=history[e];history[e]=function(){const n=t.apply(this,arguments),r=new Event(e);return r.arguments=arguments,dispatchEvent(r),n}}Object.defineProperty(window,u_,{value:!0})}const cN=(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())?"~"+t:t.slice(e.length)||"/",s1=(e="")=>e==="/"?"":e,uN=(e,t)=>e[0]==="~"?e.slice(1):s1(t)+e,dN=(e="",t)=>cN(d_(s1(e)),d_(t)),d_=e=>{try{return decodeURI(e)}catch{return e}},i1={hook:lN,searchHook:iN,parser:Kj,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,t,n)=>e(t,n)},a1=N.createContext(i1),ao=()=>N.useContext(a1),o1={},l1=N.createContext(o1),hN=()=>N.useContext(l1),bd=e=>{const[t,n]=e.hook(e);return[dN(e.base,t),n1((r,a)=>e.aroundNav(n,uN(r,e.base),a))]},Ln=()=>bd(ao()),Jp=(e,t,n,r)=>{const{pattern:a,keys:l}=t instanceof RegExp?{keys:!1,pattern:t}:e(t||"*",r),u=a.exec(n)||[],[c,...d]=u;return c!==void 0?[!0,(()=>{const h=l!==!1?Object.fromEntries(l.map((m,x)=>[m,d[x]])):u.groups;let p={...d};return h&&Object.assign(p,h),p})(),...r?[c]:[]]:[!1,null]},oo=e=>Jp(ao().parser,e,Ln()[0]),c1=({children:e,...t})=>{var p,m,x;const n=ao(),r=t.hook?i1:n;let a=r;const[l,u=t.ssrSearch??""]=((p=t.ssrPath)==null?void 0:p.split("?"))??[];l&&(t.ssrSearch=u,t.ssrPath=l),t.hrefs=t.hrefs??((m=t.hook)==null?void 0:m.hrefs),t.searchHook=t.searchHook??((x=t.hook)==null?void 0:x.searchHook);let c=N.useRef({}),d=c.current,h=d;for(let y in r){const w=y==="base"?r[y]+(t[y]??""):t[y]??r[y];d===h&&w!==h[y]&&(c.current=h={...h}),h[y]=w,(w!==r[y]||w!==a[y])&&(a=h)}return N.createElement(a1.Provider,{value:a,children:e})},h_=({children:e,component:t},n)=>t?N.createElement(t,{params:n}):typeof e=="function"?e(n):e,fN=e=>{let t=N.useRef(o1);const n=t.current;return t.current=Object.keys(e).length!==Object.keys(n).length||Object.entries(e).some(([r,a])=>a!==n[r])?e:n},ol=({path:e,nest:t,match:n,...r})=>{const a=ao(),[l]=bd(a),[u,c,d]=n??Jp(a.parser,e,l,t),h=fN({...hN(),...c});if(!u)return null;const p=d?N.createElement(c1,{base:d},h_(r,h)):h_(r,h);return N.createElement(l1.Provider,{value:h,children:p})},Jn=N.forwardRef((e,t)=>{const n=ao(),[r,a]=bd(n),{to:l="",href:u=l,onClick:c,asChild:d,children:h,className:p,replace:m,state:x,transition:y,...w}=e,C=n1(S=>{S.ctrlKey||S.metaKey||S.altKey||S.shiftKey||S.button!==0||(c==null||c(S),S.defaultPrevented||(S.preventDefault(),a(u,e)))}),_=n.hrefs(u[0]==="~"?u.slice(1):n.base+u,n);return d&&N.isValidElement(h)?N.cloneElement(h,{onClick:C,href:_}):N.createElement("a",{...w,onClick:C,href:_,className:p!=null&&p.call?p(r===u):p,children:h,ref:t})}),u1=e=>Array.isArray(e)?e.flatMap(t=>u1(t&&t.type===N.Fragment?t.props.children:t)):[e],mN=({children:e,location:t})=>{const n=ao(),[r]=bd(n);for(const a of u1(e)){let l=0;if(N.isValidElement(a)&&(l=Jp(n.parser,a.props.path,t||r,a.props.nest))[0])return N.cloneElement(a,{match:l})}return null},f_=e=>{let t;const n=new Set,r=(h,p)=>{const m=typeof h=="function"?h(t):h;if(!Object.is(m,t)){const x=t;t=p??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(y=>y(t,x))}},a=()=>t,c={setState:r,getState:a,getInitialState:()=>d,subscribe:h=>(n.add(h),()=>n.delete(h))},d=t=e(r,a,c);return c},pN=(e=>e?f_(e):f_),gN=e=>e;function xN(e,t=gN){const n=si.useSyncExternalStore(e.subscribe,si.useCallback(()=>t(e.getState()),[e,t]),si.useCallback(()=>t(e.getInitialState()),[e,t]));return si.useDebugValue(n),n}const m_=e=>{const t=pN(e),n=r=>xN(t,r);return Object.assign(n,t),n},Mn=(e=>e?m_(e):m_);function yN(){if(typeof document>"u")return"";const e=Array.from(document.scripts).find(a=>{const l=new URL(a.src,window.location.href).pathname;return l.includes("/assets/")||l.endsWith("/src/main.tsx")});if(!e)return"";const t=new URL(e.src,window.location.href).pathname,n=t.includes("/assets/")?"/assets/":"/src/",r=t.indexOf(n);return r>0?t.slice(0,r):""}const d1=yN();function ks(e){return e.startsWith("/")?`${d1}${e}`||"/":e}async function Se(e,t={}){const n=localStorage.getItem("openfox_token"),r={...t.headers instanceof Headers?Object.fromEntries(t.headers.entries()):t.headers,...n?{"x-session-token":n}:{}};return fetch(ks(e),{...t,headers:r})}async function p_(e,t,n){try{return(await Se(`/api/sessions/${e}/replay`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:t,...n!==void 0?{content:n}:{}})})).ok}catch{return!1}}async function h1(e,t,n){try{const r=await Se(`/api/sessions/${e}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messageId:t,...n!==void 0?{title:n}:{}})});return r.ok?await r.json():null}catch{return null}}const Te={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars",DISPLAY_SHOW_SYNTAX_HIGHLIGHTING:"display.showSyntaxHighlighting",DISPLAY_THEME:"display.theme",DISPLAY_USER_PRESETS:"display.userPresets",DISPLAY_FOLLOW_SYSTEM_THEME:"display.followSystemTheme",DISPLAY_SYSTEM_THEME_PREFS:"display.systemThemePrefs",DISPLAY_SHOW_OPEN_IN_EDITOR:"display.showOpenInEditorLinks",DISPLAY_SHOW_CHANGELOG_ON_UPDATE:"display.showChangelogOnUpdate",DISPLAY_MAX_VISIBLE_ITEMS:"display.maxVisibleItems",DISPLAY_CUSTOM_CSS:"display.customCss",LLM_DYNAMIC_SYSTEM_PROMPT:"llm.dynamicSystemPrompt",CACHE_WARMING:"cache.warming",KEYBINDINGS:"keybindings",RETRY_PATTERNS:"agent.retryPatterns",SKILLS_DIRECTORIES:"skills.directories",SEARCH_ENGINE:"search.engine",SEARCH_TAVILY_API_KEY:"search.tavilyApiKey",SEARCH_SEARXNG_URL:"search.searxngUrl",SEARCH_SEARXNG_API_KEY:"search.searxngApiKey",TOOLS_USE_RTK:"tools.useRtk",TOOLS_SHELL:"tools.shell",CONFIRM_ON_WORKSPACE_ACTIONS:"tools.confirmOnWorkspaceActions",FEATURES_PER_SESSION_MCP:"features.perSessionMcp",PROXY_URL:"network.proxyUrl",DEFAULT_AGENT:"agent.defaultAgent"};function fu(e,t){return n=>({loading:{...n.loading,[e]:t}})}function g_(e,t){return n=>({settings:{...n.settings,[e]:t},loading:{...n.loading,[e]:!1}})}const Zp=[Te.DISPLAY_SHOW_THINKING,Te.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Te.DISPLAY_SHOW_STATS,Te.DISPLAY_SHOW_AGENT_DEFINITIONS,Te.DISPLAY_SHOW_WORKFLOW_BARS,Te.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING,Te.DISPLAY_FOLLOW_SYSTEM_THEME,Te.DISPLAY_SHOW_OPEN_IN_EDITOR,Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,Te.DISPLAY_MAX_VISIBLE_ITEMS];function Xi(){return{showThinking:Ht(e=>e.settings[Te.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:Ht(e=>e.settings[Te.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:Ht(e=>e.settings[Te.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:Ht(e=>e.settings[Te.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:Ht(e=>e.settings[Te.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true",showSyntaxHighlighting:Ht(e=>e.settings[Te.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING]??"true")==="true",maxVisibleItems:Number(Ht(e=>e.settings[Te.DISPLAY_MAX_VISIBLE_ITEMS]??"300"))}}const Ht=Mn(e=>({settings:{},loading:{},getSetting:async t=>{e(fu(t,!0));try{const r=await(await Se(`/api/settings/${t}`)).json();return e(g_(t,r.value??"")),r.value}catch{return e(fu(t,!1)),null}},getSettings:async t=>{if(t.length!==0)try{const r=await(await Se(`/api/settings?keys=${encodeURIComponent(t.join(","))}`)).json();e({settings:r,loading:Object.fromEntries(t.map(a=>[a,!1]))})}catch{e({loading:Object.fromEntries(t.map(n=>[n,!1]))})}},setSetting:async(t,n)=>{e(fu(t,!0));try{const a=await(await Se(`/api/settings/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})})).json();e(g_(t,a.value??""))}catch{e(fu(t,!1))}}})),ll=Object.freeze(Object.defineProperty({__proto__:null,DISPLAY_SETTINGS_KEYS:Zp,SETTINGS_KEYS:Te,useDisplaySettings:Xi,useSettingsStore:Ht},Symbol.toStringTag,{value:"Module"}));function bN(){const[e,t]=N.useState({offsetTop:0,height:window.innerHeight,keyboardVisible:!1}),n=N.useRef(window.innerHeight);return N.useEffect(()=>{const r=window.visualViewport;if(!r)return;const a=()=>{const l=r.offsetTop,u=r.height,c=n.current-u>100;t({offsetTop:l,height:u,keyboardVisible:c})};return a(),r.addEventListener("resize",a),r.addEventListener("scroll",a),()=>{r.removeEventListener("resize",a),r.removeEventListener("scroll",a)}},[]),e}function vN(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function $u(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class _N{constructor(t){we(this,"ws",null);we(this,"handlers",new Set);we(this,"statusHandler",null);we(this,"baseUrl");we(this,"isReconnecting",!1);we(this,"connectingPromise",null);we(this,"lastCloseCode",0);we(this,"reconnectAttempts",0);we(this,"manualReconnectScheduled",!1);we(this,"pwaRecoveryAttempted",!1);this.baseUrl=t}getUrl(){const t=localStorage.getItem("openfox_token");if(t){const n=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${n}token=${encodeURIComponent(t)}`}return this.baseUrl}setToken(t){localStorage.setItem("openfox_token",t)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(t){this.statusHandler=t}connect(){var t,n,r;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((r=this.ws)==null?void 0:r.readyState)===WebSocket.CONNECTING?(console.warn("[WS CLIENT] Connection already in progress, returning existing promise"),this.connectingPromise):(this.connectingPromise=new Promise((a,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const c=setTimeout(()=>{var d;((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var d;clearTimeout(c),this.isReconnecting=!1,this.reconnectAttempts=0,this.connectingPromise=null,(d=this.statusHandler)==null||d.call(this,"connected"),a()},this.ws.onclose=d=>{var h,p,m;clearTimeout(c),this.lastCloseCode=d.code,((h=this.ws)==null?void 0:h.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${d.code}`))):(this.connectingPromise=null,(m=this.statusHandler)==null||m.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=d=>{clearTimeout(c),console.error("WebSocket error:",d),this.connectingPromise=null,l(d)},this.ws.onmessage=d=>{try{const h=JSON.parse(d.data);vN(h)&&this.handlers.forEach(p=>p(h))}catch(h){console.error("Failed to parse WebSocket message:",h)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise)))}async recoverPwaStuckConnection(){if(this.pwaRecoveryAttempted||!window.matchMedia("(display-mode: standalone)").matches||!("serviceWorker"in navigator))return;this.pwaRecoveryAttempted=!0;const n=await navigator.serviceWorker.getRegistrations();n.length!==0&&(console.warn("[WS] PWA mode detected with stale service worker — unregistering and reloading"),await Promise.all(n.map(r=>r.unregister())),window.location.reload())}attemptReconnect(){var r;if(this.lastCloseCode===4e3&&this.hasToken()){console.warn("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(r=this.statusHandler)==null||r.call(this,"reconnecting");const n=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{this.reconnectAttempts>=3&&this.recoverPwaStuckConnection()})},n)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{this.recoverPwaStuckConnection()})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const r=$u(),a={id:r,type:t,payload:n};return this.ws.send(JSON.stringify(a)),r}subscribe(t){return this.handlers.add(t),()=>this.handlers.delete(t)}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}}const SN=window.location.protocol==="https:"?"wss:":"ws:";let dp=window.location.port;dp||(dp=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?"10469":window.location.protocol==="https:"?"443":"80");const wN=`${SN}//${window.location.hostname}:${dp}${ks("/ws")}`,Pt=new _N(wN),CN=3e4;function f1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"lmstudio":return"LM Studio";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"unknown":return"Other"}}const Kt=Mn((e,t)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,platform:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const n=await Se("/api/config");if(!n.ok)throw new Error("Failed to fetch config");const r=await n.json(),a=r.platform&&typeof r.platform=="object"?{isWSL:!!r.platform.isWSL,wslDistro:String(r.platform.wslDistro??"")}:null;e({version:r.version,model:r.model,maxContext:r.maxContext,llmUrl:r.llmUrl,llmStatus:r.llmStatus,backend:r.backend,providers:r.providers??[],activeProviderId:r.activeProviderId??null,defaultModelSelection:r.defaultModelSelection??null,platform:a,loading:!1})}catch(n){e({error:n instanceof Error?n.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const n=await Se("/api/model/refresh",{method:"POST"});if(!n.ok)throw new Error("Failed to refresh model");const r=await n.json();e({model:r.model,llmStatus:r.llmStatus,backend:r.backend})}catch(n){console.error("Failed to refresh model:",n)}},activateProvider:async n=>{const{activeProviderId:r,providers:a}=t();if(n===r)return!0;e({activating:!0,error:null});try{const l=await Se(`/api/providers/${n}/activate`,{method:"POST"});if(!l.ok){const c=await l.json();throw new Error(c.error??"Failed to activate provider")}const u=await l.json();return e({activeProviderId:u.activeProviderId,model:u.model,backend:u.backend,providers:a.map(c=>({...c,isActive:c.id===u.activeProviderId})),activating:!1}),!0}catch(l){return e({error:l instanceof Error?l.message:"Failed to switch provider",activating:!1}),!1}},setDefaultModel:async(n,r)=>{const{providers:a}=t();try{const l=await Se("/api/default-model",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:n,model:r})});if(!l.ok)return!1;const u=await l.json();return e({activeProviderId:n,model:r,defaultModelSelection:u.defaultModelSelection,providers:a.map(c=>({...c,isActive:c.id===n}))}),!0}catch{return!1}},refreshProviderModels:async n=>{e({activating:!0,error:null});try{const r=await Se(`/api/providers/${n}/refresh`,{method:"POST"});if(!r.ok){const u=await r.json();throw new Error(u.error??"Failed to refresh models")}const a=await r.json(),{providers:l}=t();return e({providers:l.map(u=>u.id===n?{...u,models:a.models,status:a.status}:u),activating:!1}),!0}catch(r){return e({error:r instanceof Error?r.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:n,refreshModel:r}=t();if(n)return;const a=setInterval(()=>{r()},CN);e({autoRefreshInterval:a})},stopAutoRefresh:()=>{const{autoRefreshInterval:n}=t();n&&(clearInterval(n),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:n,activeProviderId:r}=t();return n.find(a=>a.id===r)},getModelContext:n=>{const{providers:r,activeProviderId:a}=t(),l=r.find(c=>c.id===a);if(!l)return 2e5;const u=l.models.find(c=>c.id===n);return(u==null?void 0:u.contextWindow)??2e5}})),Ft=Mn((e,t)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const r=await(await Se("/api/projects")).json();e({projects:r.projects??[],loading:!1})}catch(n){console.error("Failed to load projects:",n),e({loading:!1})}},createProject:async(n,r)=>{try{const a=await Se("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n,workdir:r})});if(!a.ok){const u=await a.json().catch(()=>({}));return{error:{code:u.code||"UNKNOWN",path:u.path,message:u.error}}}const l=await a.json();return await t().listProjects(),l.project}catch{return null}},loadProject:async n=>{try{const r=await Se(`/api/projects/${n}`);if(!r.ok)return null;const a=await r.json();return e({currentProject:a.project}),t().projects.length===0&&await t().listProjects(),a.project}catch{return null}},updateProject:async(n,r)=>{var a;try{const l=await Se(`/api/projects/${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!l.ok)return null;const u=await l.json();return((a=t().currentProject)==null?void 0:a.id)===n&&e({currentProject:u.project}),await t().listProjects(),u.project}catch{return null}},deleteProject:async n=>{var r;try{return(await Se(`/api/projects/${n}`,{method:"DELETE"})).ok?(await t().listProjects(),((r=t().currentProject)==null?void 0:r.id)===n&&e({currentProject:null}),!0):!1}catch{return!1}},toggleStar:async(n,r)=>{var a;try{const l=await Se(`/api/projects/${n}/star`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isStarred:r})});if(!l.ok)return!1;if(((a=t().currentProject)==null?void 0:a.id)===n){const u=await l.json();e({currentProject:u.project})}return await t().listProjects(),!0}catch{return!1}},clearProject:()=>{e({currentProject:null})}})),ui=async(e,t,n)=>{try{const r=await Se(t,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return r.ok?{success:!0}:{success:!1,error:(await r.json()).error}}catch{return{success:!1,error:"Network error"}}},vd=async(e,t,n)=>{try{const r=await Se(e,{method:"POST",body:n?JSON.stringify({destination:n}):void 0,headers:n?{"Content-Type":"application/json"}:void 0}),a=await r.json();return r.ok?(await t(),{success:!0}):{success:!1,error:a.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}};function m1(e){let t=null;function n(){t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))}return n}let mu=[];const wl=Mn()((e,t)=>{function n(){if(mu.length===0)return;const a=mu;mu=[],e(l=>{const u={...l.logs};for(const c of a){const d=u[c.processId]??[];u[c.processId]=[...d,{offset:d.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:u}})}const r=m1(n);return{processes:[],logs:{},loading:!1,setProcesses:a=>e({processes:a}),addProcess:a=>e(l=>({processes:[...l.processes,a]})),updateProcess:(a,l)=>e(u=>({processes:u.processes.map(c=>c.id===a?{...c,...l}:c)})),removeProcess:a=>e(l=>({processes:l.processes.filter(u=>u.id!==a),logs:Object.fromEntries(Object.entries(l.logs).filter(([u])=>u!==a))})),stopProcess:async(a,l)=>{try{(await Se(`/api/sessions/${l}/background-process/${a}/stop`,{method:"POST"})).ok&&t().removeProcess(a)}catch{}},appendLog:(a,l,u)=>{mu.push({processId:a,stream:l,content:u}),r()},setLogs:(a,l)=>e(u=>({logs:{...u.logs,[a]:l}})),clearLogs:a=>e(l=>({logs:{...l.logs,[a]:[]}})),handleMessage:(a,l)=>{switch(a){case"backgroundProcess.started":{const{processId:u,name:c,pid:d,status:h}=l;e(p=>({processes:[...p.processes,{id:u,sessionId:"",name:c,command:"",cwd:"",pid:d,status:h,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const u=l.processId,c=l.stream,d=l.content;t().appendLog(u,c,d);break}case"backgroundProcess.exited":{const u=l.processId,c=l.exitCode;e(d=>({processes:d.processes.map(h=>h.id===u?{...h,status:"exited",exitCode:c}:h)}));break}case"backgroundProcess.removed":{const u=l.processId;t().removeProcess(u);break}}}}}),kN={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let zu=null;function EN(e){zu=e}function Pi(){return kN}function mm(){zu==null||zu()}let pu=[];const Qn=Mn()((e,t)=>{function n(){if(pu.length===0)return;const a=pu;pu=[],e(l=>({logs:[...l.logs,...a]}))}const r=m1(n);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:a=>{t().workdir!==a&&(e({workdir:a,status:null,logs:[],config:null,loading:!0}),a&&(t().fetchStatus(),t().fetchConfig()))},fetchStatus:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server?workdir=${encodeURIComponent(a)}`)).json();e({status:u,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/config?workdir=${encodeURIComponent(a)}`)).json();e({config:u.config??null})}catch{}},fetchLogs:async()=>{const a=t().workdir;if(a)try{const c=(await(await Se(`/api/dev-server/logs?workdir=${encodeURIComponent(a)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:c})}catch{}},start:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/start?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},stop:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/stop?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u})}catch{}},restart:async()=>{const a=t().workdir;if(a)try{const u=await(await Se(`/api/dev-server/restart?workdir=${encodeURIComponent(a)}`,{method:"POST"})).json();e({status:u,logs:[]})}catch{}},saveConfig:async a=>{const l=t().workdir;if(l)try{const c=await(await Se(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();e({config:c.config??a}),t().fetchStatus()}catch{}},handleMessage:a=>{const l=t().workdir;if(l)switch(a.type){case"devServer.output":{const u=a.payload;if(u.workdir!==l)return;pu.push({stream:u.stream,content:u.content}),r();break}case"devServer.state":{const u=a.payload;if(u.workdir!==l)return;e(c=>({status:c.status?{...c.status,state:u.state,errorMessage:u.errorMessage,...u.url!==void 0?{url:u.url}:{},...u.inspectProxyPort!==void 0?{inspectProxyPort:u.inspectProxyPort}:{}}:{state:u.state,url:u.url??null,hotReload:!1,config:null,errorMessage:u.errorMessage,inspectProxyPort:u.inspectProxyPort??null}}));break}}}}}),jN=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],NN=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],p1={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ii={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},g1={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},hp={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ii},waiting_for_user:{...ii},phase_done:{...ii},phase_blocked:{...ii},new_message:{...g1}},agentOverrides:{}};function x1(e,t,n){var l;const r=e.events[t];if(!n)return r;const a=(l=e.agentOverrides[n])==null?void 0:l[t];return a?{soundEnabled:a.soundEnabled??r.soundEnabled,browserNotification:a.browserNotification??r.browserNotification,customSoundUrl:a.customSoundUrl!==void 0?a.customSoundUrl:r.customSoundUrl}:r}const Bi=Mn((e,t)=>({settings:hp,loaded:!1,load:()=>{Ht.getState().getSetting(Te.NOTIFICATION_SETTINGS);const r=Ht.subscribe(l=>{const u=l.settings[Te.NOTIFICATION_SETTINGS];if(u!==void 0)try{const c=JSON.parse(u);e({settings:x_(c),loaded:!0})}catch{e({loaded:!0})}}),a=Ht.getState().settings[Te.NOTIFICATION_SETTINGS];if(a)try{const l=JSON.parse(a);e({settings:x_(l),loaded:!0})}catch{e({loaded:!0})}return r},update:n=>{e({settings:n}),pm(n)},updateEvent:(n,r)=>{const a=t().settings,l={...a,events:{...a.events,[n]:{...a.events[n],...r}}};e({settings:l}),pm(l)},updateAgentOverride:(n,r,a)=>{var d;const l=t().settings,u={...l.agentOverrides};if(a===null){if(u[n]){const h={...u[n]};delete h[r],Object.keys(h).length===0?delete u[n]:u[n]=h}}else u[n]={...u[n],[r]:{...((d=u[n])==null?void 0:d[r])??{},...a}};const c={...l,agentOverrides:u};e({settings:c}),pm(c)}}));function pm(e){Ht.getState().setSetting(Te.NOTIFICATION_SETTINGS,JSON.stringify(e))}function x_(e){var t,n,r,a,l;return{soundEnabled:e.soundEnabled??hp.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??hp.browserNotificationEnabled,events:{complete:{...ii,...(t=e.events)==null?void 0:t.complete},waiting_for_user:{...ii,...(n=e.events)==null?void 0:n.waiting_for_user},phase_done:{...ii,...(r=e.events)==null?void 0:r.phase_done},phase_blocked:{...ii,...(a=e.events)==null?void 0:a.phase_blocked},new_message:{...g1,...(l=e.events)==null?void 0:l.new_message}},agentOverrides:e.agentOverrides??{}}}const y_=new Map;function TN(e){let t=y_.get(e);return t||(t=new Audio(ks(e)),t.volume=.5,y_.set(e,t)),t}let y1=typeof Notification<"u"?Notification.permission:"denied";function AN(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(y1=e,e))}const LN={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},DN={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function RN(e){typeof Notification>"u"||y1==="granted"&&(document.hasFocus()||new Notification(LN[e],{body:DN[e],icon:ks("/fox.svg"),tag:`openfox-${e}`}))}function Vl(e,t){const{settings:n}=Bi.getState(),r=x1(n,e,t);if(n.soundEnabled&&r.soundEnabled){const a=r.customSoundUrl??p1[e],l=TN(a);l.currentTime=0,l.play().catch(()=>{})}n.browserNotificationEnabled&&r.browserNotification&&RN(e)}const ON=e=>Vl("complete",e),IN=e=>Vl("phase_done",e),MN=e=>Vl("phase_blocked",e),gm=e=>Vl("waiting_for_user",e),PN=e=>Vl("new_message",e),b_=new Map;function Wa(e,t){var l;const n=t===((l=e.currentSession)==null?void 0:l.id)?e.currentSession:null,r=e.sessions.find(u=>u.id===t),a=(n==null?void 0:n.mode)??(r==null?void 0:r.mode);return a==="planner"?"planner":a==="builder"?"build":"planner"}function BN(e,t){if(e.type==="chat.done"){const n=e.payload,r=Wa(t,e.sessionId),a=n.agentType??r;n.reason==="complete"&&ON(a),n.reason==="waiting_for_user"&&gm(a);return}if(e.type==="chat.path_confirmation"){const n=Wa(t,e.sessionId);gm(n);return}if(e.type==="session.confirmation_pending"){const n=Wa(t,e.sessionId);gm(n);return}if(e.type==="task.completed"){const n=Wa(t,e.sessionId);IN(n);return}if(e.type==="phase.changed"&&e.sessionId){const n=e.payload,r=b_.get(e.sessionId)??null;if(b_.set(e.sessionId,n.phase),r===n.phase)return;const a=Wa(t,e.sessionId);n.phase==="blocked"&&MN(a)}}const Al=Mn(e=>({servers:[],setServers:t=>e({servers:t}),fetchServers:async()=>{try{const t=await Se("/api/mcp/servers");if(!t.ok)return;const r=((await t.json()).servers??[]).sort((a,l)=>a.name.localeCompare(l.name));e({servers:r})}catch{}}})),xm=new Set;function dn(e,t){return t!==null&&e.sessionId===t}function $N(e,t,n){return e.id!==void 0||dn(e,t)||n===!0&&e.sessionId!==void 0}function zN(e,t){return e.includes(t)?e:[...e,t]}function v_(e,t){return e.filter(n=>n!==t)}function HN(e,t){const n=e.find(l=>l.id===t.id),r=t.messageCount??t.messages.length,a=n?{...n,projectId:t.projectId,workdir:t.workdir,workspace:t.workspace,branch:t.branch,mode:t.mode,phase:t.phase,isRunning:t.isRunning&&n.isRunning!==!1,messageCount:r,criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length}:{id:t.id,projectId:t.projectId,workdir:t.workdir,workspace:t.workspace,branch:t.branch,mode:t.mode,phase:t.phase,isRunning:t.isRunning,createdAt:"",updatedAt:"",criteriaCount:t.criteria.length,criteriaCompleted:t.criteria.filter(l=>l.status.type==="passed").length,messageCount:r};return n?e.map(l=>l.id===t.id?a:l):[a,...e]}function ym(e,t){const n=e.findIndex(r=>r.callId===t.callId);if(n>=0){const r=[...e];return r[n]=t,r}return[...e,t]}function UN(e,t,n){return e.map(r=>{const a=(n==null?void 0:n.id)===r.id?n:null,l=t.find(u=>u.id===r.id);return{...r,title:r.title??(l==null?void 0:l.title),mode:(a==null?void 0:a.mode)??(l==null?void 0:l.mode)??r.mode,phase:(a==null?void 0:a.phase)??(l==null?void 0:l.phase)??r.phase,isRunning:r.isRunning&&(l==null?void 0:l.isRunning)!==!1,messageCount:r.messageCount,recentUserPrompts:r.recentUserPrompts}})}function __(e,t,n,r){var c;const a=e.sessionId,l=(c=n().currentSession)==null?void 0:c.id,u=a&&a!==l;if(t(d=>({sessions:d.sessions.map(h=>h.id===a?r(h):h)})),!u){const d=n().currentSession;if(d){const h=r(d);t(()=>({currentSession:h}))}}}function S_(e,t,n){var c,d,h,p,m,x,y,w,C,_,S,v,b,E,j,T,D,L,I,P,W,H;const r=n();BN(e,r);const a=((c=r.currentSession)==null?void 0:c.id)??null,l=()=>{const R=e.sessionId;!R||R===a||t(U=>({unreadSessionIds:zN(U.unreadSessionIds,R)}))},u=(R,U,V)=>({messages:R.messages.map(G=>G.id===U?V(G):G)});switch(e.type){case"session.state":{const R=e.payload;if(!$N(e,a,r.pendingSessionCreate))break;const U=n().pendingSessionCreate===!0,V=R.pendingConfirmations??[],G=R.session.id,Z={...n().crossSessionConfirmations};delete Z[G],t({currentSession:R.session,sessions:HN(n().sessions,R.session),unreadSessionIds:v_(n().unreadSessionIds,G),messages:R.messages,hiddenCount:R.hiddenCount??0,currentTodos:[],pendingPathConfirmations:V,crossSessionConfirmations:Z,sessionsWithPendingConfirmations:Object.keys(Z),pendingQuestions:R.pendingQuestions??[],...U?{pendingSessionCreate:R.session.id}:{}});break}case"session.list":{const R=e.payload;t(U=>({sessions:UN(R.sessions,U.sessions,U.currentSession)}));break}case"session.created":{const R=e.payload;t(U=>({sessions:U.sessions.some(V=>V.id===R.session.id)?U.sessions.map(V=>V.id===R.session.id?{...V,...R.session}:V):[R.session,...U.sessions]}));break}case"session.deleted":{const R=e.payload;t(U=>({unreadSessionIds:v_(U.unreadSessionIds,R.sessionId)})),n().listSessions();break}case"session.deletedAll":{n().listSessions();break}case"session.running":{const R=e.payload;__(e,t,n,U=>({...U,isRunning:R.isRunning})),R.isRunning||t({abortInProgress:!1,queuedMessages:[]}),R.isRunning&&t({restoredInput:null});break}case"chat.message":{if(!dn(e,((d=n().currentSession)==null?void 0:d.id)??null)){l();break}const R=e.payload;t(U=>{if(U.messages.some(G=>G.id===R.message.id))return U;const V=R.message.role==="user";return{messages:[...U.messages,R.message],sessions:U.sessions.map(G=>G.id===e.sessionId&&V?{...G,messageCount:G.messageCount+1}:G)}});break}case"chat.message_updated":{if(!dn(e,((h=n().currentSession)==null?void 0:h.id)??null)){l();break}const R=e.payload,U=n().messages.find(V=>V.id===R.messageId);R.updates.isStreaming===!1&&(U==null||U.isStreaming),t(V=>({messages:V.messages.map(G=>G.id===R.messageId?{...G,...R.updates}:G)}));break}case"chat.delta":{if(!dn(e,((p=n().currentSession)==null?void 0:p.id)??null)){l();break}const R=e.payload;if(!xm.has(R.messageId)){xm.add(R.messageId);const V=R.subAgentType?"sub-agent":Wa(n(),e.sessionId);PN(V)}const U=Pi();U.messageId=R.messageId,U.deltaContent+=R.content,mm();break}case"chat.thinking":{if(!dn(e,((m=n().currentSession)==null?void 0:m.id)??null)){l();break}const R=e.payload,U=Pi();U.messageId=R.messageId,U.thinkingContent+=R.content,mm();break}case"chat.tool_preparing":{if(!dn(e,((x=n().currentSession)==null?void 0:x.id)??null)){l();break}const R=e.payload;t(U=>{var O;const V=U.messages.find(M=>M.id===R.messageId);if(!V)return{};if((O=V.toolCalls)==null?void 0:O.find((M,q)=>q===R.index))return{};const Z=V.preparingToolCalls??[],X=Z.findIndex(M=>M.index===R.index);let $;return X>=0?$=Z.map((M,q)=>q===X?{...M,arguments:R.arguments}:M):$=[...Z,{index:R.index,name:R.name,...R.arguments?{arguments:R.arguments}:{}}],{messages:U.messages.map(M=>M.id===R.messageId?{...M,preparingToolCalls:$}:M)}});break}case"chat.tool_call":{if(!dn(e,((y=n().currentSession)==null?void 0:y.id)??null)){l();break}const R=e.payload,U=V=>{var O;const G=(V.toolCalls??[]).length,Z=(O=V.preparingToolCalls)==null?void 0:O.filter(M=>M.index!==G),X=Pi(),$=X.toolOutput.filter(M=>M.callId===R.callId);return $.length>0&&(X.toolOutput=X.toolOutput.filter(M=>M.callId!==R.callId)),{...V,toolCalls:[...V.toolCalls??[],{id:R.callId,name:R.tool,arguments:R.args,startedAt:Date.now(),...$.length>0?{streamingOutput:$.map(M=>({stream:M.stream,content:M.content,timestamp:Date.now()}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};t(V=>u(V,R.messageId,U));break}case"chat.tool_output":{if(!dn(e,((w=n().currentSession)==null?void 0:w.id)??null)){l();break}const R=e.payload,U=Pi();U.messageId=R.messageId,U.toolOutput.push({messageId:R.messageId,callId:R.callId,stream:R.stream,content:R.output}),mm();break}case"chat.tool_result":{if(!dn(e,((C=n().currentSession)==null?void 0:C.id)??null)){l();break}const R=e.payload,U=V=>{var Z;const G=(Z=V.toolCalls)==null?void 0:Z.map(X=>X.id===R.callId?{...X,result:R.result}:X);return{...V,toolCalls:G}};t(V=>u(V,R.messageId,U));break}case"chat.vision_fallback":{if(!dn(e,((_=n().currentSession)==null?void 0:_.id)??null)){l();break}const R=e.payload;t(U=>{const V=`${R.messageId}-${R.attachmentId}`,G={...U.visionFallbackByMessage};return G[V]={type:R.type,attachmentId:R.attachmentId,filename:R.filename,description:R.description},{visionFallbackByMessage:G}});break}case"chat.todo":{if(!dn(e,((S=n().currentSession)==null?void 0:S.id)??null)){l();break}const R=e.payload;t({currentTodos:R.todos});break}case"chat.progress":{if(!dn(e,((v=n().currentSession)==null?void 0:v.id)??null)){l();break}const R=e.payload;console.warn("Progress:",R.message,R.phase);break}case"chat.format_retry":{if(!dn(e,((b=n().currentSession)==null?void 0:b.id)??null)){l();break}const R=e.payload;console.warn("Format retry:",R.attempt,"/",R.maxAttempts);break}case"chat.done":{if(!dn(e,((E=n().currentSession)==null?void 0:E.id)??null)){l();break}const R=Pi();R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[],xm.delete(e.payload.messageId);const U=e.payload,V=U.stats;t(G=>({messages:G.messages.map(Z=>Z.id===U.messageId?{...Z,isStreaming:!1,stats:V??Z.stats,completeReason:U.reason,preparingToolCalls:void 0}:Z),visionFallbackByMessage:{}}));break}case"chat.error":{if(!dn(e,((j=n().currentSession)==null?void 0:j.id)??null)){l();break}const R=Pi(),U=e.payload;console.error("Chat error:",U.error,"recoverable:",U.recoverable),U.recoverable||(R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[]),t(V=>({error:{code:"CHAT_ERROR",message:U.error},...U.recoverable?{}:{messages:V.messages}}));break}case"chat.path_confirmation":{const R=e.sessionId,U=R===(((T=n().currentSession)==null?void 0:T.id)??null),V=e.payload,G={callId:V.callId,tool:V.tool,paths:V.paths,workdir:V.workdir,reason:V.reason};if(!U){l(),R&&t(Z=>({crossSessionConfirmations:{...Z.crossSessionConfirmations,[R]:ym(Z.crossSessionConfirmations[R]??[],G)},sessionsWithPendingConfirmations:Z.sessionsWithPendingConfirmations.includes(R)?Z.sessionsWithPendingConfirmations:[...Z.sessionsWithPendingConfirmations,R]}));break}t(Z=>({pendingPathConfirmations:ym(Z.pendingPathConfirmations,G)}));break}case"session.confirmation_pending":{const R=e.sessionId,U=e.payload,V={callId:U.callId,tool:U.tool,paths:U.paths,workdir:U.workdir,reason:U.reason};R&&t(G=>({crossSessionConfirmations:{...G.crossSessionConfirmations,[R]:ym(G.crossSessionConfirmations[R]??[],V)},sessionsWithPendingConfirmations:G.sessionsWithPendingConfirmations.includes(R)?G.sessionsWithPendingConfirmations:[...G.sessionsWithPendingConfirmations,R]}));break}case"session.confirmation_resolved":{const R=e.sessionId,U=e.payload;R&&t(V=>{const Z=(V.crossSessionConfirmations[R]??[]).filter($=>$.callId!==U.callId),X={...V.crossSessionConfirmations};return Z.length===0?delete X[R]:X[R]=Z,{crossSessionConfirmations:X,sessionsWithPendingConfirmations:Object.keys(X)}});break}case"chat.ask_user":{if(!dn(e,((D=n().currentSession)==null?void 0:D.id)??null)){l();return}const R=e.payload,U={callId:R.callId,question:R.question,type:R.type??"text",options:R.options??void 0};t(V=>({pendingQuestions:[...V.pendingQuestions.filter(G=>G.callId!==R.callId),U]}));break}case"mode.changed":{if(!dn(e,((L=n().currentSession)==null?void 0:L.id)??null)){l();break}const R=e.payload;t(U=>({currentSession:U.currentSession?{...U.currentSession,mode:R.mode}:null}));break}case"phase.changed":{const R=e.payload;__(e,t,n,U=>({...U,phase:R.phase}));break}case"criteria.updated":{if(!dn(e,((I=n().currentSession)==null?void 0:I.id)??null)){l();break}const R=e.payload;t(U=>({currentSession:U.currentSession?{...U.currentSession,criteria:R.criteria}:null}));break}case"metadata.updated":{if(!dn(e,((P=n().currentSession)==null?void 0:P.id)??null)){l();break}const R=e.payload;t(U=>({currentSession:U.currentSession?{...U.currentSession,metadataEntries:{...U.currentSession.metadataEntries,[R.key]:R.entries}}:null}));break}case"context.state":{const R=e.payload,U=dn(e,((W=n().currentSession)==null?void 0:W.id)??null);R.subAgentId?U&&n().updateSubAgentContextState(R.subAgentId,R.context):U?t({contextState:R.context}):l();break}case"session.name_generated":{const R=e.payload,U=e.sessionId,V=(H=n().currentSession)==null?void 0:H.id;t(G=>{const Z=G.sessions.map($=>$.id===U?{...$,title:R.name,updatedAt:new Date().toISOString()}:$),X=V===U?G.currentSession?{...G.currentSession,title:R.name,updatedAt:new Date().toISOString()}:null:G.currentSession;return{sessions:Z,currentSession:X}});break}case"queue.state":{const R=e.payload;t({queuedMessages:R.messages??[]});break}case"mcp.servers.changed":{const R=e.payload;if(R!=null&&R.servers){const U=[...R.servers].sort((V,G)=>V.name.localeCompare(G.name));Al.getState().setServers(U)}else window.dispatchEvent(new CustomEvent("mcp-servers-changed"));break}case"git.status":{const R=e.payload;t({gitStatus:{branch:R.branch,diff:R.diff}});break}case"devServer.output":case"devServer.state":{Qn.getState().handleMessage(e);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{wl.getState().handleMessage(e.type,e.payload);break}case"error":{const R=e.payload;console.error("Server error:",R),t({error:{code:R.code,message:R.message}});break}}}let cl=!1,Fr=null;const bm=new Set,gu=new Map;function w_(e,t,n){return e==null?void 0:e.map(r=>{const a=t.filter(l=>l.callId===r.id);return a.length===0?r:(n.add(r.id),{...r,streamingOutput:[...r.streamingOutput??[],...a.map(l=>({stream:l.stream,content:l.content,timestamp:Date.now()}))]})})}async function C_(e,t,n,r,a){try{const u=await(await Se(`/api/sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,attachments:n,messageKind:r})})).json();u.queueState&&a({queuedMessages:u.queueState})}catch(l){console.error("Error queueing message:",l)}}const Re=Mn((e,t)=>(EN(()=>{const n=Pi();if(!n.messageId)return;const r=n.deltaContent.length>0,a=n.thinkingContent.length>0,l=n.toolOutput.length>0;if(!r&&!a&&!l)return;const u=n.deltaContent,c=n.thinkingContent,d=n.toolOutput;n.deltaContent="",n.thinkingContent="",n.toolOutput=[],e(h=>{const p=h.messages.find(m=>m.id===n.messageId);if(p){const m={...p};if(r&&(m.content=m.content+u),a&&(m.thinkingContent=(m.thinkingContent??"")+c),l){const x=new Set;m.toolCalls=w_(m.toolCalls,d,x);const y=d.filter(w=>!x.has(w.callId));y.length>0&&n.toolOutput.push(...y)}return{messages:h.messages.map(x=>x.id===n.messageId?m:x)}}if(l){const m=new Set,x=h.messages.map(w=>w.id!==n.messageId?w:{...w,toolCalls:w_(w.toolCalls,d,m)}),y=d.filter(w=>!m.has(w.callId));return y.length>0&&n.toolOutput.push(...y),{messages:x}}return h})}),{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],hiddenCount:0,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmations:[],crossSessionConfirmations:{},sessionsWithPendingConfirmations:[],pendingQuestions:[],visionFallbackByMessage:{},gitStatus:null,queuedMessages:[],abortInProgress:!1,restoredInput:null,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,pendingUpdate:!1,connect:async()=>{if(t().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let r=!1;try{r=(await(await Se("/api/auth")).json()).requiresAuth}catch{}if(r&&!Pt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Pt.onStatusChange(a=>{var l;if(e({connectionStatus:a}),a==="connected"){t().listSessions(void 0),Ft.getState().listProjects();const u=(l=t().currentSession)==null?void 0:l.id;u&&t().loadSession(u)}});try{await Pt.connect(),cl||(cl=!0,Fr=Pt.subscribe(a=>{S_(a,e,t)}))}catch(a){console.error("Failed to connect:",a);const l=Pt.getLastCloseCode();if(!Pt.hasToken()&&(l===1006||l===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}Fr&&(Fr(),Fr=null),cl=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Pt.disconnect(),Fr&&(Fr(),Fr=null),cl=!1,e({connectionStatus:"disconnected"}),t().connect()},disconnect:()=>{Pt.disconnect(),Fr&&(Fr(),Fr=null),cl=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async n=>{try{const r=await fetch(ks("/api/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n})});if(!r.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:a}=await r.json();Pt.setToken(a),e({showPasswordModal:!1}),t().connect();const{listProjects:l}=Ft.getState(),{fetchConfig:u}=Kt.getState();l(),u(),t().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Pt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(n,r)=>{if(t().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const l=await Se("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:n,title:r})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();try{Pt.send("session.load",{sessionId:u.session.id})}catch{}return u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async n=>{if(!bm.has(n)){bm.add(n);try{const r=t().currentSession;if(!r||r.id!==n){const d=r==null?void 0:r.id,h=t().pendingPathConfirmations,m={...t().crossSessionConfirmations};d&&h.length>0&&(m[d]=[...m[d]??[],...h]),e({currentSession:null,unreadSessionIds:t().unreadSessionIds.filter(x=>x!==n),subAgentContextStates:{},messages:[],currentTodos:[],contextState:null,pendingPathConfirmations:[],pendingQuestions:[],queuedMessages:[],abortInProgress:!1,restoredInput:null,error:null,gitStatus:null,pendingSessionCreate:!1,crossSessionConfirmations:m,sessionsWithPendingConfirmations:Object.keys(m)})}else e({unreadSessionIds:t().unreadSessionIds.filter(d=>d!==n)});const a=await Se(`/api/sessions/${n}`);if(!a.ok)return;const l=await a.json(),u=l.messages??[],c={...t().crossSessionConfirmations};delete c[n],e({currentSession:l.session,messages:u,hiddenCount:l.hiddenCount??0,contextState:l.contextState,queuedMessages:l.queueState??[],pendingPathConfirmations:l.pendingConfirmations??[],pendingQuestions:l.pendingQuestions??[],crossSessionConfirmations:c,sessionsWithPendingConfirmations:Object.keys(c)}),Pt.send("session.load",{sessionId:n});try{const d=await Se(`/api/sessions/${n}/background-processes`);if(d.ok){const h=await d.json();wl.getState().setProcesses(h.processes??[])}}catch{}}catch{}finally{bm.delete(n)}}},listSessions:async(n,r=20)=>{const a=n??"global";if(gu.has(a))return gu.get(a);const l=(async()=>{var u;try{const c=new URLSearchParams;c.set("limit",String(r)),n&&c.set("projectId",n);const h=await(await Se(`/api/sessions?${c.toString()}`)).json(),p=h.sessions??[];e(x=>({sessions:p.map(y=>{var C,_;const w=x.sessions.find(S=>S.id===y.id);return{...y,title:y.title??(w==null?void 0:w.title),mode:((C=x.currentSession)==null?void 0:C.id)===y.id?x.currentSession.mode:(w==null?void 0:w.mode)??y.mode,phase:((_=x.currentSession)==null?void 0:_.id)===y.id?x.currentSession.phase:(w==null?void 0:w.phase)??y.phase,isRunning:y.isRunning&&(w==null?void 0:w.isRunning)!==!1,messageCount:y.messageCount,recentUserPrompts:y.recentUserPrompts}}),sessionsHasMore:n?h.hasMore??!1:!0}));const m=h.pendingConfirmationsBySession;if(m){const x=(u=t().currentSession)==null?void 0:u.id,y={};for(const[w,C]of Object.entries(m))w!==x&&(y[w]=C);e({crossSessionConfirmations:y,sessionsWithPendingConfirmations:Object.keys(y)})}}catch{}finally{gu.delete(a)}})();return gu.set(a,l),l},loadMoreSessions:async n=>{const r=t();if(!(r.sessionsPaginationLoading||!r.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const a=new URLSearchParams;a.set("limit","20"),a.set("offset",String(r.sessions.length)),a.set("projectId",n);const u=await(await Se(`/api/sessions?${a.toString()}`)).json(),c=u.sessions??[];e(d=>({sessions:[...d.sessions,...c.map(h=>{const p=d.sessions.find(m=>m.id===h.id);return(p==null?void 0:p.isRunning)===!1?{...h,isRunning:!1}:h})],sessionsHasMore:u.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async n=>{var r;try{return(await Se(`/api/sessions/${n}`,{method:"DELETE"})).ok?(await t().listSessions(),((r=t().currentSession)==null?void 0:r.id)===n&&t().clearSession(),!0):!1}catch{return!1}},renameSession:async(n,r)=>{var a;try{const l=await Se(`/api/sessions/${n}/title`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:r})});if(!l.ok)return!1;if(await t().listSessions(),((a=t().currentSession)==null?void 0:a.id)===n){const c=await l.json();c.session&&e({currentSession:c.session})}return!0}catch{return!1}},deleteAllSessions:async n=>{try{return(await Se(`/api/projects/${n}/sessions`,{method:"DELETE"})).ok?(await t().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{e(n=>({currentSession:null,messages:[],hiddenCount:0,currentTodos:[],contextState:null,restoredInput:null,pendingSessionCreate:!1,unreadSessionIds:n.currentSession?n.unreadSessionIds.filter(r=>r!==n.currentSession.id):n.unreadSessionIds}))},sendMessage:async(n,r,a)=>{var u;e({error:null});const l=(u=t().currentSession)==null?void 0:u.id;if(l)try{const c=n==null?void 0:n.trim(),d=r&&r.length>0,h={};c&&(h.content=n),d&&(h.attachments=r),a!=null&&a.messageKind&&(h.messageKind=a.messageKind);const m=await(await Se(`/api/sessions/${l}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})).json();m.queueState&&e({queuedMessages:m.queueState})}catch(c){console.error("Error sending message:",c)}},stopGeneration:async()=>{var r;const n=(r=t().currentSession)==null?void 0:r.id;if(n&&!t().abortInProgress){e({abortInProgress:!0});try{const l=await(await Se(`/api/sessions/${n}/stop`,{method:"POST"})).json();if(l.queuedMessages&&l.queuedMessages.length>0){const u=l.queuedMessages.map(c=>c.content).join(`
59
59
  `);e({restoredInput:u})}}catch(a){console.error("Error stopping generation:",a)}}},continueGeneration:async()=>{var r;const n=(r=t().currentSession)==null?void 0:r.id;if(n)try{await Se(`/api/sessions/${n}/continue`,{method:"POST"})}catch(a){console.error("Error continuing generation:",a)}},launchWorkflow:(n,r,a,l)=>{const u={};n!=null&&n.trim()&&(u.content=n),r&&r.length>0&&(u.attachments=r),a&&(u.workflowId=a),l&&(u.subGroup=l),Pt.send("runner.launch",u)},switchMode:async n=>{var a;const r=(a=t().currentSession)==null?void 0:a.id;if(r)try{const l=await Se(`/api/sessions/${r}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:n})});if(!l.ok){console.error("Failed to switch mode:",await l.json());return}const u=await l.json();u.session&&e({currentSession:u.session}),u.messages&&e({messages:u.messages,hiddenCount:u.hiddenCount??0})}catch(l){console.error("Error switching mode:",l)}},switchDangerLevel:async n=>{var a;const r=(a=t().currentSession)==null?void 0:a.id;if(r)try{const l=await Se(`/api/sessions/${r}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:n})});if(!l.ok){console.error("Failed to switch danger level:",await l.json());return}const u=await l.json();u.session&&e({currentSession:u.session})}catch(l){console.error("Error switching danger level:",l)}},editCriteria:async n=>{var a;const r=(a=t().currentSession)==null?void 0:a.id;if(r)try{const l=await Se(`/api/sessions/${r}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:n})});l.ok||console.error("Failed to update criteria:",await l.json())}catch(l){console.error("Error updating criteria:",l)}},compactContext:()=>{Pt.send("context.compact",{})},setSessionProvider:async(n,r)=>{var a;try{const l=(a=t().currentSession)==null?void 0:a.id;if(!l)return null;const u=await Se(`/api/sessions/${l}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:n,...r?{model:r}:{}})});if(!u.ok)return null;const c=await u.json();return e({currentSession:c.session,messages:c.messages??[],hiddenCount:c.hiddenCount??0,contextState:c.contextState}),c.session}catch{return null}},updateContextState:n=>{e({contextState:n})},updateSubAgentContextState:(n,r)=>{e(a=>({subAgentContextStates:{...a.subAgentContextStates,[n]:r}}))},clearSubAgentContextState:n=>{e(r=>{const a={...r.subAgentContextStates};return delete a[n],{subAgentContextStates:a}})},confirmPath:async(n,r,a=!1)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;if(l)try{const c=await Se(`/api/sessions/${l}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:n,approved:r,alwaysAllow:a})});if(!c.ok){const d=await c.json().catch(()=>({}));console.error("Error confirming path:",d.error??`HTTP ${c.status}`)}}catch(c){console.error("Error confirming path:",c)}},answerQuestion:async(n,r,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;if(l){try{await Se(`/api/sessions/${l}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:n,answer:r,skip:a})})}catch(c){console.error("Error answering question:",c)}e(c=>({pendingQuestions:c.pendingQuestions.filter(d=>d.callId!==n)}))}},queueAsap:async(n,r,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;l&&await C_(l,n,r,a,e)},queueCompletion:async(n,r,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;l&&await C_(l,n,r,a,e)},cancelQueued:async n=>{var a;const r=(a=t().currentSession)==null?void 0:a.id;if(r)try{const u=await(await Se(`/api/sessions/${r}/queue/${n}`,{method:"DELETE"})).json();u.queueState&&e({queuedMessages:u.queueState})}catch(l){console.error("Error canceling queued message:",l)}},clearError:()=>{e({error:null})},clearRestoredInput:()=>{e({restoredInput:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},queueUpdate:()=>{e({pendingUpdate:!0})},triggerPendingUpdate:()=>{t().pendingUpdate&&(e({pendingUpdate:!1}),Pt.send("context.applyDynamic",{}))},handleServerMessage:n=>{S_(n,e,t)}}));function _d(){return Re(e=>{var t;return((t=e.currentSession)==null?void 0:t.isRunning)??!1})}function FN(){return Re(e=>e.abortInProgress)}function VN(){const e=Re(a=>a.connect),t=Re(a=>a.connectionStatus),n=Bi(a=>a.load),r=oo("/p/:projectId/s/:sessionId/readonly")[0];return N.useEffect(()=>{r||e()},[e,r]),N.useEffect(()=>{r||t==="connected"&&n()},[t,n,r]),{connectionStatus:t}}const GN="modulepreload",WN=function(e){return"/"+e},k_={},J=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){let u=function(h){return Promise.all(h.map(p=>Promise.resolve(p).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=u(n.map(h=>{if(h=WN(h),h in k_)return;k_[h]=!0;const p=h.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${m}`))return;const x=document.createElement("link");if(x.rel=p?"stylesheet":GN,p||(x.as="script"),x.crossOrigin="",x.href=h,d&&x.setAttribute("nonce",d),document.head.appendChild(x),p)return new Promise((y,w)=>{x.addEventListener("load",y),x.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${h}`)))})}))}function l(u){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=u,window.dispatchEvent(c),!c.defaultPrevented)throw u}return a.then(u=>{for(const c of u||[])c.status==="rejected"&&l(c.reason);return t().catch(l)})},qN=[{key:"color-bg-primary",category:"background",label:"Primary Background",defaultValue:"13 17 23"},{key:"color-bg-secondary",category:"background",label:"Secondary Background",defaultValue:"22 27 34"},{key:"color-bg-tertiary",category:"background",label:"Tertiary Background",defaultValue:"33 38 45"},{key:"color-primary",category:"surface",label:"Primary Surface",defaultValue:"10 10 10"},{key:"color-secondary",category:"surface",label:"Secondary Surface",defaultValue:"20 20 20"},{key:"color-text-primary",category:"text",label:"Primary Text",defaultValue:"139 148 158"},{key:"color-text-secondary",category:"text",label:"Secondary Text",defaultValue:"139 148 158"},{key:"color-text-muted",category:"text",label:"Muted Text",defaultValue:"72 79 88"},{key:"color-accent-primary",category:"accent",label:"Primary Accent",defaultValue:"88 166 255"},{key:"color-accent-success",category:"accent",label:"Success Accent",defaultValue:"63 185 80"},{key:"color-accent-warning",category:"accent",label:"Warning Accent",defaultValue:"210 153 34"},{key:"color-accent-error",category:"accent",label:"Error Accent",defaultValue:"248 81 73"},{key:"color-border",category:"border",label:"Border",defaultValue:"48 53 60"},{key:"color-text-heading",category:"text",label:"Heading Text",defaultValue:"56 189 248"},{key:"color-text-bold",category:"text",label:"Bold Text",defaultValue:"251 191 36"},{key:"color-text-code",category:"text",label:"Inline Code Text",defaultValue:"88 166 255"},{key:"color-text-link",category:"text",label:"Link Text",defaultValue:"88 166 255"},{key:"color-bg-system",category:"background",label:"System Message Background",defaultValue:"40 35 28"},{key:"color-border-system",category:"border",label:"System Message Border",defaultValue:"65 55 25"},{key:"color-text-system",category:"text",label:"System Message Text",defaultValue:"253 230 138"},{key:"color-text-thinking",category:"text",label:"Thinking Label",defaultValue:"192 132 252"},{key:"color-text-truncated",category:"text",label:"Truncation Warning",defaultValue:"251 191 36"},{key:"color-text-tool-error",category:"text",label:"Tool Error Text",defaultValue:"248 81 73"}],KN=JSON.parse('[{"id":"system","name":"System","tokens":{}},{"id":"dark","name":"Dark","tokens":{"color-bg-primary":"13 17 23","color-bg-secondary":"22 27 34","color-bg-tertiary":"33 38 45","color-primary":"10 10 10","color-secondary":"20 20 20","color-text-primary":"255 255 255","color-text-secondary":"139 148 158","color-text-muted":"72 79 88","color-accent-primary":"88 166 255","color-accent-success":"63 185 80","color-accent-warning":"210 153 34","color-accent-error":"248 81 73","color-border":"48 53 60","color-text-heading":"56 189 248","color-text-bold":"251 191 36","color-text-code":"255 255 255","color-text-link":"88 166 255","color-bg-system":"40 35 28","color-border-system":"65 55 25","color-text-system":"253 230 138","color-text-thinking":"192 132 252","color-text-truncated":"251 191 36","color-text-tool-error":"248 113 113"},"mode":"dark"},{"id":"light","name":"Light","tokens":{"color-bg-primary":"255 255 255","color-bg-secondary":"250 251 252","color-bg-tertiary":"243 244 246","color-primary":"245 245 245","color-secondary":"229 229 229","color-text-primary":"15 23 42","color-text-secondary":"30 41 59","color-text-muted":"100 116 139","color-accent-primary":"37 99 235","color-accent-success":"22 163 74","color-accent-warning":"217 119 6","color-accent-error":"220 38 38","color-border":"203 213 225","color-text-heading":"2 132 199","color-text-bold":"217 119 6","color-text-code":"37 99 235","color-text-link":"37 99 235","color-bg-system":"254 243 199","color-border-system":"252 211 77","color-text-system":"146 100 30","color-text-thinking":"147 51 234","color-text-truncated":"217 119 6","color-text-tool-error":"220 38 38"},"mode":"light"},{"id":"monokai","name":"Monokai","tokens":{"color-bg-primary":"39 40 34","color-bg-secondary":"30 31 28","color-bg-tertiary":"62 61 50","color-primary":"30 31 28","color-secondary":"45 46 39","color-text-primary":"248 248 242","color-text-secondary":"207 207 194","color-text-muted":"117 113 94","color-accent-primary":"102 217 239","color-accent-success":"166 226 46","color-accent-warning":"230 219 116","color-accent-error":"249 38 114","color-border":"73 72 62","color-text-heading":"56 189 248","color-text-bold":"251 191 36","color-text-code":"248 248 242","color-text-link":"102 217 239","color-bg-system":"62 57 40","color-border-system":"85 75 40","color-text-system":"230 219 116","color-text-thinking":"192 132 252","color-text-truncated":"251 191 36","color-text-tool-error":"248 113 113"},"mode":"dark"},{"id":"dracula","name":"Dracula","tokens":{"color-bg-primary":"40 42 54","color-bg-secondary":"33 34 44","color-bg-tertiary":"68 71 90","color-primary":"30 31 41","color-secondary":"44 46 61","color-text-primary":"248 248 242","color-text-secondary":"230 230 230","color-text-muted":"98 114 164","color-accent-primary":"189 147 249","color-accent-success":"80 250 123","color-accent-warning":"255 184 108","color-accent-error":"255 85 85","color-border":"68 71 90","color-text-heading":"189 147 249","color-text-bold":"255 184 108","color-text-code":"189 147 249","color-text-link":"189 147 249","color-bg-system":"68 64 50","color-border-system":"90 80 60","color-text-system":"255 184 108","color-text-thinking":"255 121 198","color-text-truncated":"255 184 108","color-text-tool-error":"255 85 85"},"mode":"dark"},{"id":"nord","name":"Nord","tokens":{"color-bg-primary":"46 52 64","color-bg-secondary":"59 66 82","color-bg-tertiary":"67 76 94","color-primary":"46 52 64","color-secondary":"59 66 82","color-text-primary":"236 239 244","color-text-secondary":"229 233 240","color-text-muted":"121 133 160","color-accent-primary":"129 161 193","color-accent-success":"163 190 140","color-accent-warning":"235 203 139","color-accent-error":"191 97 106","color-border":"121 133 160","color-text-heading":"129 161 193","color-text-bold":"235 203 139","color-text-code":"129 161 193","color-text-link":"129 161 193","color-bg-system":"67 62 50","color-border-system":"85 80 60","color-text-system":"235 203 139","color-text-thinking":"184 142 173","color-text-truncated":"235 203 139","color-text-tool-error":"191 97 106"},"mode":"dark"},{"id":"rose-pine-dawn","name":"Rose Pine Dawn","tokens":{"color-bg-primary":"250 244 237","color-bg-secondary":"244 237 228","color-bg-tertiary":"235 226 216","color-primary":"250 244 237","color-secondary":"244 237 228","color-text-primary":"87 82 95","color-text-secondary":"111 105 120","color-text-muted":"175 170 180","color-accent-primary":"215 130 126","color-accent-success":"104 157 153","color-accent-warning":"234 157 84","color-accent-error":"215 85 112","color-border":"230 218 206","color-text-heading":"215 130 126","color-text-bold":"234 157 84","color-text-code":"145 117 186","color-text-link":"215 130 126","color-bg-system":"244 237 228","color-border-system":"230 218 206","color-text-system":"162 137 123","color-text-thinking":"145 117 186","color-text-truncated":"234 157 84","color-text-tool-error":"215 85 112"},"mode":"light"},{"id":"everforest-light","name":"Everforest Light","tokens":{"color-bg-primary":"255 248 235","color-bg-secondary":"245 238 220","color-bg-tertiary":"237 228 208","color-primary":"255 248 235","color-secondary":"245 238 220","color-text-primary":"91 105 86","color-text-secondary":"127 139 116","color-text-muted":"179 181 158","color-accent-primary":"100 153 117","color-accent-success":"141 169 73","color-accent-warning":"224 146 66","color-accent-error":"203 97 80","color-border":"230 216 194","color-text-heading":"100 153 117","color-text-bold":"224 146 66","color-text-code":"146 131 176","color-text-link":"100 153 117","color-bg-system":"245 238 220","color-border-system":"230 216 194","color-text-system":"163 147 121","color-text-thinking":"146 131 176","color-text-truncated":"224 146 66","color-text-tool-error":"203 97 80"},"mode":"light"},{"id":"synthwave-84","name":"Synthwave-84","tokens":{"color-bg-primary":"13 15 26","color-bg-secondary":"20 24 41","color-bg-tertiary":"26 31 51","color-primary":"10 12 20","color-secondary":"20 24 41","color-text-primary":"212 230 255","color-text-secondary":"136 153 187","color-text-muted":"68 85 119","color-accent-primary":"0 229 255","color-accent-success":"0 255 65","color-accent-warning":"255 106 0","color-accent-error":"255 0 60","color-border":"26 51 102","color-text-heading":"0 229 255","color-text-bold":"255 140 0","color-text-code":"0 255 170","color-text-link":"0 229 255","color-bg-system":"26 20 10","color-border-system":"51 40 20","color-text-system":"255 170 80","color-text-thinking":"191 0 255","color-text-truncated":"255 140 0","color-text-tool-error":"255 0 60"},"mode":"dark"},{"id":"one-dark-pro","name":"One Dark Pro","tokens":{"color-bg-primary":"40 44 52","color-bg-secondary":"33 37 43","color-bg-tertiary":"47 52 62","color-primary":"28 31 37","color-secondary":"33 37 43","color-text-primary":"171 178 191","color-text-secondary":"150 155 168","color-text-muted":"92 99 112","color-accent-primary":"97 175 239","color-accent-success":"152 195 121","color-accent-warning":"209 154 102","color-accent-error":"224 108 117","color-border":"57 62 72","color-text-heading":"97 175 239","color-text-bold":"209 154 102","color-text-code":"198 120 221","color-text-link":"97 175 239","color-bg-system":"47 42 32","color-border-system":"68 60 46","color-text-system":"224 190 79","color-text-thinking":"198 120 221","color-text-truncated":"209 154 102","color-text-tool-error":"224 108 117"},"mode":"dark"},{"id":"night-owl","name":"Night Owl","tokens":{"color-bg-primary":"1 22 39","color-bg-secondary":"0 30 55","color-bg-tertiary":"11 41 66","color-primary":"1 20 33","color-secondary":"0 30 55","color-text-primary":"214 222 235","color-text-secondary":"162 176 196","color-text-muted":"82 98 126","color-accent-primary":"130 170 255","color-accent-success":"34 218 110","color-accent-warning":"247 140 108","color-accent-error":"239 83 80","color-border":"30 56 85","color-text-heading":"130 170 255","color-text-bold":"247 140 108","color-text-code":"199 146 234","color-text-link":"130 170 255","color-bg-system":"30 25 20","color-border-system":"60 50 40","color-text-system":"247 199 120","color-text-thinking":"199 146 234","color-text-truncated":"247 140 108","color-text-tool-error":"239 83 80"},"mode":"dark"},{"id":"catppuccin-mocha","name":"Catppuccin Mocha","tokens":{"color-bg-primary":"30 30 46","color-bg-secondary":"24 24 37","color-bg-tertiary":"49 50 68","color-primary":"17 17 27","color-secondary":"24 24 37","color-text-primary":"205 214 244","color-text-secondary":"186 194 222","color-text-muted":"108 112 134","color-accent-primary":"137 180 250","color-accent-success":"166 227 161","color-accent-warning":"249 226 175","color-accent-error":"243 139 168","color-border":"69 71 90","color-text-heading":"137 180 250","color-text-bold":"249 226 175","color-text-code":"203 166 247","color-text-link":"137 180 250","color-bg-system":"37 37 54","color-border-system":"69 71 90","color-text-system":"250 179 135","color-text-thinking":"203 166 247","color-text-truncated":"249 226 175","color-text-tool-error":"243 139 168"},"mode":"dark"},{"id":"rose-pine","name":"Rose Pine","tokens":{"color-bg-primary":"25 23 36","color-bg-secondary":"31 29 46","color-bg-tertiary":"38 35 58","color-primary":"20 18 30","color-secondary":"31 29 46","color-text-primary":"224 222 244","color-text-secondary":"196 194 220","color-text-muted":"110 106 134","color-accent-primary":"235 188 186","color-accent-success":"156 207 216","color-accent-warning":"246 193 119","color-accent-error":"235 111 146","color-border":"44 40 67","color-text-heading":"235 188 186","color-text-bold":"246 193 119","color-text-code":"196 167 231","color-text-link":"235 188 186","color-bg-system":"44 38 36","color-border-system":"60 52 50","color-text-system":"246 193 119","color-text-thinking":"196 167 231","color-text-truncated":"246 193 119","color-text-tool-error":"235 111 146"},"mode":"dark"},{"id":"kanagawa-wave","name":"Kanagawa Wave","tokens":{"color-bg-primary":"31 34 44","color-bg-secondary":"25 28 36","color-bg-tertiary":"42 47 58","color-primary":"25 28 36","color-secondary":"25 28 36","color-text-primary":"220 224 206","color-text-secondary":"188 193 178","color-text-muted":"108 112 99","color-accent-primary":"133 189 168","color-accent-success":"157 198 113","color-accent-warning":"226 190 107","color-accent-error":"227 116 102","color-border":"51 59 72","color-text-heading":"133 189 168","color-text-bold":"226 190 107","color-text-code":"194 160 191","color-text-link":"133 189 168","color-bg-system":"42 38 30","color-border-system":"60 54 44","color-text-system":"226 190 107","color-text-thinking":"194 160 191","color-text-truncated":"226 190 107","color-text-tool-error":"227 116 102"},"mode":"dark"},{"id":"light-plus","name":"Light Plus","tokens":{"color-bg-primary":"255 255 255","color-bg-secondary":"243 244 245","color-bg-tertiary":"233 235 238","color-primary":"255 255 255","color-secondary":"243 244 245","color-text-primary":"0 0 0","color-text-secondary":"80 80 80","color-text-muted":"140 140 140","color-accent-primary":"0 92 197","color-accent-success":"0 128 0","color-accent-warning":"178 110 0","color-accent-error":"204 0 0","color-border":"217 217 217","color-text-heading":"0 0 0","color-text-bold":"0 0 0","color-text-code":"204 0 0","color-text-link":"0 92 197","color-bg-system":"255 243 207","color-border-system":"255 220 150","color-text-system":"130 80 0","color-text-thinking":"130 50 180","color-text-truncated":"178 110 0","color-text-tool-error":"204 0 0"},"mode":"light"}]'),b1={tokens:qN,presets:KN},v1=b1.tokens,zn=b1.presets;function E_(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}function YN(){try{const e=localStorage.getItem("openfox:systemThemePrefs");if(e)return JSON.parse(e)}catch{}return{darkPreset:"dark",lightPreset:"light"}}const Rt=Mn((e,t)=>{const n=YN();return{currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:E_(),followSystemTheme:!0,isSystem:!1,systemDarkPreset:n.darkPreset,systemLightPreset:n.lightPreset,activeUserPresetId:null,applySavedTheme:()=>{const{getSavedTheme:r,applyPreset:a,applyTokens:l}=t(),u=r();if(u)try{const c=JSON.parse(u);c.preset&&c.tokens?(a(c.preset),e({basePreset:c.preset}),l(c.tokens)):c.preset?a(c.preset):c.tokens&&l(c.tokens)}catch{a("dark")}else a("dark")},applyPreset:r=>{if(zn.find(l=>l.id===r))if(r==="system"){const l=window.matchMedia("(prefers-color-scheme: dark)"),{systemDarkPreset:u,systemLightPreset:c,userPresets:d}=t(),h=l.matches?u:c,p=d.find(m=>m.id===h);e(p?{basePreset:"system",currentPreset:p.basePreset,customTokens:{...p.tokens},isCustom:!0,isCustomizing:!1,isSystem:!0,activeUserPresetId:p.id}:{basePreset:"system",currentPreset:h,customTokens:{},isCustom:!1,isCustomizing:!1,isSystem:!0,activeUserPresetId:null}),t().applyTheme()}else e({currentPreset:r,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,isSystem:!1,activeUserPresetId:null}),t().applyTheme()},startCustomizing:()=>{var l;const{currentPreset:r}=t(),a=((l=zn.find(u=>u.id===r))==null?void 0:l.tokens)??{};e({basePreset:r,customTokens:{...a},isCustom:!0,isCustomizing:!0})},setCustomToken:(r,a)=>{e(l=>({customTokens:{...l.customTokens,[r]:a}})),t().applyTheme()},cancelCustomizing:()=>{t().applyPreset(t().basePreset||t().currentPreset)},saveCustomTheme:()=>{const{customTokens:r}=t();t().saveTheme(JSON.stringify({tokens:r})).catch(()=>{}),e({isCustomizing:!1})},applyTokens:r=>{e({customTokens:r,isCustom:!0,isCustomizing:!1}),t().applyTheme()},getActiveTheme:()=>{var c,d;const{basePreset:r,customTokens:a,isCustom:l}=t();if(l&&r)return{...((c=zn.find(p=>p.id===r))==null?void 0:c.tokens)??{},...a};if(l)return{...v1.reduce((h,p)=>({...h,[p.key]:p.defaultValue}),{}),...a};const u=zn.find(h=>h.id===t().currentPreset);return(u==null?void 0:u.tokens)??((d=zn[0])==null?void 0:d.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const r=t().getActiveTheme(),a=document.documentElement;Object.entries(r).forEach(([l,u])=>{a.style.setProperty(`--${l}`,u)})},getSavedTheme:()=>{try{const r=localStorage.getItem("openfox:theme");if(!r)return null;if(r[0]!=="{")return JSON.stringify({preset:r});const a=JSON.parse(r);if(a.preset)return JSON.stringify({preset:a.preset});if(a.tokens)return JSON.stringify({tokens:a.tokens})}catch{return null}return null},saveTheme:async r=>{localStorage.setItem("openfox:theme",r);const{useSettingsStore:a}=await J(async()=>{const{useSettingsStore:l}=await Promise.resolve().then(()=>ll);return{useSettingsStore:l}},void 0);await a.getState().setSetting(Te.DISPLAY_THEME,r)},clearCustomTheme:()=>{localStorage.removeItem("openfox:theme"),e({isCustom:!1,isCustomizing:!1,basePreset:""})},setFollowSystemTheme:r=>{e({followSystemTheme:r}),J(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ll);return{useSettingsStore:a,SETTINGS_KEYS:l}},void 0).then(({useSettingsStore:a,SETTINGS_KEYS:l})=>{a.getState().setSetting(l.DISPLAY_FOLLOW_SYSTEM_THEME,String(r))})},initSystemThemeListener:()=>{if(typeof window>"u")return()=>{};const r=window.matchMedia("(prefers-color-scheme: dark)"),a=u=>{const{followSystemTheme:c,systemDarkPreset:d,systemLightPreset:h}=t();if(!c)return;const p=u?d:h;t().applyPreset(p),t().saveTheme(JSON.stringify({preset:p}))},l=u=>a(u.matches);return r.addEventListener("change",l),()=>r.removeEventListener("change",l)},reset:()=>{e({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:[],followSystemTheme:!0,systemDarkPreset:"dark",systemLightPreset:"light",activeUserPresetId:null})},addUserPreset:r=>{const{basePreset:a,customTokens:l,currentPreset:u}=t(),c=a||u,d=zn.find(m=>m.id===c),h={id:"custom-"+Date.now(),name:r,basePreset:c,mode:d==null?void 0:d.mode,tokens:{...l}},p=[...t().userPresets,h];e({userPresets:p}),t().saveUserPresets()},applyUserPreset:r=>{const a=t().userPresets[r];a&&(e({currentPreset:a.basePreset,basePreset:a.basePreset,customTokens:{...a.tokens},isCustom:!0,isCustomizing:!1,activeUserPresetId:a.id}),t().applyTheme(),t().saveTheme(JSON.stringify({preset:a.basePreset,tokens:a.tokens})).catch(()=>{}))},deleteUserPreset:r=>{const a=t().userPresets.filter((l,u)=>u!==r);e({userPresets:a}),t().saveUserPresets()},loadUserPresets:()=>{e({userPresets:E_()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(t().userPresets)),J(async()=>{const{useSettingsStore:r}=await Promise.resolve().then(()=>ll);return{useSettingsStore:r}},void 0).then(({useSettingsStore:r})=>{r.getState().setSetting(Te.DISPLAY_USER_PRESETS,JSON.stringify(t().userPresets)).catch(()=>{})})},setSystemDarkPreset:r=>{e({systemDarkPreset:r}),localStorage.setItem("openfox:systemThemePrefs",JSON.stringify({darkPreset:r,lightPreset:t().systemLightPreset})),J(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ll);return{useSettingsStore:a,SETTINGS_KEYS:l}},void 0).then(({useSettingsStore:a,SETTINGS_KEYS:l})=>{a.getState().setSetting(l.DISPLAY_SYSTEM_THEME_PREFS,JSON.stringify({darkPreset:r,lightPreset:t().systemLightPreset}))}),t().isSystem&&t().applyPreset("system")},setSystemLightPreset:r=>{e({systemLightPreset:r}),localStorage.setItem("openfox:systemThemePrefs",JSON.stringify({darkPreset:t().systemDarkPreset,lightPreset:r})),J(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ll);return{useSettingsStore:a,SETTINGS_KEYS:l}},void 0).then(({useSettingsStore:a,SETTINGS_KEYS:l})=>{a.getState().setSetting(l.DISPLAY_SYSTEM_THEME_PREFS,JSON.stringify({darkPreset:t().systemDarkPreset,lightPreset:r}))}),t().isSystem&&t().applyPreset("system")}}});function XN({canLoad:e,projectId:t,currentProjectId:n}){const r=Ft(u=>u.loadProject),a=Re(u=>u.listSessions),l=Re(u=>u.clearSession);N.useEffect(()=>{e&&t&&(n!==t&&r(t),a(t),l())},[e,t,n,r,a,l])}function QN({canLoad:e,projectId:t,sessionId:n,currentProjectId:r,currentSessionId:a}){const l=Re(h=>h.loadSession),u=Ft(h=>h.loadProject),c=Re(h=>h.listSessions),d=Re(h=>h.pendingSessionCreate);N.useEffect(()=>{e&&t&&r!==t&&u(t)},[e,t,r,u]),N.useEffect(()=>{e&&n&&a!==n&&l(n),e&&t&&c(t)},[e,n,a,l,c,d,t])}function JN({className:e="w-5 h-5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function _1({className:e="w-3.5 h-3.5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function ZN({className:e="w-5 h-5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function eT({className:e="w-3 h-3 text-text-muted"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function Vi({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Pr({className:e="w-3.5 h-3.5 text-text-muted"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function S1({className:e="w-3 h-3 text-text-muted",rotate:t,direction:n="down"}){return i.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:t!==void 0?{transform:`rotate(${t}deg)`}:void 0,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:n==="up"?"M5 15l7-7 7 7":"M19 9l-7 7-7-7"})})}function yn(e){return i.jsx(S1,{direction:"down",...e})}function tT(e){return i.jsx(S1,{direction:"up",...e})}function nT({className:e="w-4 h-4"}){return i.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[i.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),i.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function Ll({className:e="w-3.5 h-3.5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function w1({className:e="w-3 h-3"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function C1({className:e="w-4 h-4"}){return i.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[i.jsx("circle",{cx:"12",cy:"5",r:"2"}),i.jsx("circle",{cx:"12",cy:"12",r:"2"}),i.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function eg({className:e="w-3.5 h-3.5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function Or({className:e="w-5 h-5 text-accent-primary"}){return i.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function rT({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function sT({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function iT({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function tg({className:e="w-3 h-3"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function aT({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function j_({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function k1({className:e="w-[18px] h-[18px]"}){return i.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),i.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),i.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function E1({className:e="w-4 h-4"}){return i.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),i.jsx("path",{d:"M9.5 2h4.5v4.5"}),i.jsx("path",{d:"M14 2L7.5 8.5"})]})}function j1({className:e="w-3 h-3",color:t}){return i.jsx("svg",{className:e,fill:t??"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{d:"M8 5v14l11-7z"})})}function Es({className:e="w-3 h-3 text-accent-primary"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function oT({className:e="w-5 h-5"}){return i.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:i.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function Sd({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function lT({className:e="w-4 h-4"}){return i.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function cT({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return i.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[i.jsx("title",{children:"Running"}),i.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),i.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function N1({className:e="w-3.5 h-3.5 text-text-muted"}){return i.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{d:"M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.007 5.404.433c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.433 2.082-5.006z"})})}function T1({className:e="w-3.5 h-3.5 text-text-muted"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})}function ng({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function uT({className:e="w-3.5 h-3.5 shrink-0",color:t}){return i.jsx("svg",{className:e,fill:"none",stroke:t,viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function dT({className:e="w-4 h-4"}){return i.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polyline",{points:"4 17 10 11 4 5"}),i.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function lo({className:e="w-3.5 h-3.5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function Wi({className:e="w-3.5 h-3.5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}function hT({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function fp({className:e="w-2.5 h-2.5"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function js({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:i.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function rg({className:e="w-4 h-4"}){return i.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function fT({className:e="w-3.5 h-3.5 text-text-muted"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})})}function mT({className:e="w-3.5 h-3.5 text-text-muted"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}function N_({className:e="w-3.5 h-3.5 text-text-muted"}){return i.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})})}function mp(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function T_(e,t){const n=Pt.ws;!n||n.readyState!==WebSocket.OPEN||n.send(JSON.stringify({id:mp(),type:e,payload:t}))}const Dr=Mn((e,t)=>({isOpen:!1,sessions:[],workdir:null,setOpen:n=>e({isOpen:n}),toggleOpen:()=>e(n=>({isOpen:!n.isOpen})),setWorkdir:n=>e({workdir:n}),fetchSessions:async n=>{if(!n){e({sessions:[]});return}try{const r=await Se(`/api/terminals?projectId=${encodeURIComponent(n)}`);if(r.ok){const a=await r.json();e({sessions:a});const l=Pt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of a)l.send(JSON.stringify({id:mp(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(r){console.error("Failed to fetch terminals:",r)}},createSession:async(n,r)=>{try{const a=await Se("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:n??t().workdir??void 0,projectId:r})});if(a.ok){const l=await a.json();e(c=>({sessions:[...c.sessions,l]}));const u=Pt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:mp(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(a){console.error("Failed to create terminal:",a)}},writeSession:(n,r)=>{T_("terminal.write",{sessionId:n,data:r})},resizeSession:(n,r,a)=>{T_("terminal.resize",{sessionId:n,cols:r,rows:a})},killSession:async n=>{try{(await Se(`/api/terminals/${n}`,{method:"DELETE"})).ok&&e(a=>({sessions:a.sessions.filter(l=>l.id!==n)}))}catch(r){console.error("Failed to kill terminal:",r)}},handleMessage:n=>{switch(n.type){case"terminal.exit":{const{sessionId:r}=n.payload||{};r&&e(a=>{const l=a.sessions.filter(u=>u.id!==r);return l.length===0&&a.isOpen?{sessions:[],isOpen:!1}:{sessions:l}});break}}}}));Pt.subscribe(e=>{var t;(t=e.type)!=null&&t.startsWith("terminal.")&&Dr.getState().handleMessage(e)});const Cs=Mn((e,t)=>({status:"idle",current:null,latest:null,check:async n=>{if(!(!n&&t().status==="checking")){e({status:"checking"});try{const r=await fetch(ks(`/api/auto-update/check${n?"?force=true":""}`));if(!r.ok)throw new Error(`HTTP ${r.status}`);const a=await r.json();e({status:a.isUpdateAvailable?"available":"upToDate",current:a.current,latest:a.latest})}catch{e({status:"error"})}}}})),qr={terminalToggle:{type:"double-press",key:"Control",threshold:300},quickAction:{type:"double-press",key:"Shift",threshold:300},modelSelector:{type:"chord",key:"m",modifiers:["ctrl"]},sessionSearch:{type:"chord",key:"s",modifiers:["ctrl"]},criteriaSidebar:{type:"chord",key:"d",modifiers:["ctrl"]},agentSwitching:[{type:"chord",key:"1",modifiers:["ctrl"]},{type:"chord",key:"2",modifiers:["ctrl"]},{type:"chord",key:"3",modifiers:["ctrl"]},{type:"chord",key:"4",modifiers:["ctrl"]}]};function pp(e){if(!e)return structuredClone(qr);try{const t=JSON.parse(e),n=r=>t[r]===void 0?structuredClone(qr[r]):t[r];return{terminalToggle:n("terminalToggle"),quickAction:n("quickAction"),modelSelector:n("modelSelector"),sessionSearch:n("sessionSearch"),criteriaSidebar:n("criteriaSidebar"),agentSwitching:n("agentSwitching")}}catch{return structuredClone(qr)}}function A_(e){return e.code.startsWith("Digit")?e.code.slice(-1):/^[a-zA-Z]$/.test(e.key)?e.key.toLowerCase():e.key}function qu(e){if(e.type==="double-press")return`Double ${e.key==="Control"?"Ctrl":e.key==="Shift"?"Shift":e.key==="Alt"?"Alt":e.key==="Meta"?"Meta":e.key}`;const t=e.modifiers.map(r=>{switch(r){case"ctrl":return"Ctrl";case"meta":return"⌘";case"alt":return"Alt";case"shift":return"Shift"}}),n=e.key.length===1?e.key.toUpperCase():e.key;return[...t,n].join("+")}function pT(e){return e.type==="double-press"}function A1(e){return e.type==="chord"}function gT(e,t){return t.length===1&&/^[a-z]$/i.test(t)?e.key.toLowerCase()===t.toLowerCase():t.length===1&&/^[0-9]$/.test(t)?e.code===`Digit${t}`:e.key.toLowerCase()===t.toLowerCase()}function L1(e,t){const n=t.modifiers.includes("ctrl"),r=t.modifiers.includes("meta"),a=t.modifiers.includes("alt"),l=t.modifiers.includes("shift");return gT(e,t.key)&&e.ctrlKey===n&&e.metaKey===r&&e.altKey===a&&e.shiftKey===l}function Gl(){const e=Ht(t=>t.settings[Te.KEYBINDINGS]);return pp(e)}function xT(e,t,n){const r=N.useRef(0),a=N.useRef(t);a.current=t,N.useEffect(()=>{if(!e)return;const l=e.threshold??300,u=c=>{if(c.key!==e.key)return;const d=e.key==="Control",h=e.key==="Shift",p=e.key==="Alt",m=e.key==="Meta";if(!d&&c.ctrlKey||!h&&c.shiftKey||!p&&c.altKey||!m&&c.metaKey)return;const x=Date.now();x-r.current<l?(c.preventDefault(),c.stopPropagation(),a.current(),r.current=0):r.current=x};return window.addEventListener("keydown",u,n!=null&&n.capture?!0:void 0),()=>window.removeEventListener("keydown",u,n!=null&&n.capture?!0:void 0)},[e,n==null?void 0:n.capture])}function yT(e,t){const n=N.useRef(t);n.current=t,N.useEffect(()=>{if(!e)return;const r=a=>{L1(a,e)&&(a.preventDefault(),n.current())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e])}function Dl(e,t,n){xT(e&&pT(e)?e:void 0,t,n),yT(e&&A1(e)?e:void 0,t)}function bT(e,t,n){const r=N.useRef(n);r.current=n,N.useEffect(()=>{const a=l=>{for(let u=0;u<e.length;u++){const c=e[u];if(!c)continue;const d=t[u];if(d&&A1(c)&&L1(l,c)){l.preventDefault(),r.current(d.id);return}}};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,t])}var di=t1();const wd=N.forwardRef(({icon:e,iconSize:t="w-3.5 h-3.5",className:n="",...r},a)=>i.jsx("button",{ref:a,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${n}`,...r,children:i.jsx("svg",{className:t,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));wd.displayName="IconButton";const vT="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",qi=N.forwardRef((e,t)=>i.jsx(wd,{ref:t,icon:vT,title:"Edit",...e}));qi.displayName="EditButton";const _T="M6 18L18 6M6 6l12 12",sg=N.forwardRef((e,t)=>i.jsx(wd,{ref:t,icon:_T,...e}));sg.displayName="CloseButton";const ST={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function wt({label:e,title:t,headerRight:n,size:r="md",minHeight:a,children:l,footer:u,className:c,onClose:d,isOpen:h,closeOnBackdropClick:p=!0,closeOnEscape:m=!0,showCloseButton:x=!0,scrollable:y=!0}){const[w,C]=N.useState(!1),_=h!==void 0,S=_?h:w,v=N.useCallback(()=>{_||C(!0)},[_]),b=N.useCallback(()=>{_||C(!1),d==null||d()},[_,d]);N.useEffect(()=>{if(!S||!m)return;const j=T=>{if(T.key==="Escape"){const D=document.activeElement;if(D&&(D.tagName==="INPUT"||D.tagName==="TEXTAREA"))return;T.stopPropagation(),b()}};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[S,b,m]);const E=e&&(typeof e=="string"?i.jsx("button",{type:"button",onClick:v,className:c,children:e}):i.jsx("span",{onClick:v,className:c,style:{cursor:"pointer"},children:e}));return i.jsxs(i.Fragment,{children:[E,S&&(typeof document<"u"?di.createPortal(i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?b:void 0}),i.jsxs("div",{role:"dialog",className:`relative w-full ${ST[r]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(t||n||x)&&i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[t&&i.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:t}),i.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[n,x&&i.jsx(sg,{onClick:b,"aria-label":"Close"})]})]}),i.jsx("div",{className:`p-4 flex-1 min-h-0${y?" overflow-y-auto":" overflow-hidden flex flex-col"}`,style:a?{minHeight:a}:void 0,children:l}),u&&i.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}function wT({value:e,defaultUrl:t,disabled:n,onChange:r}){const a=e??t;return i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:a,disabled:n,onChange:l=>{const u=l.target.value;r(u===t?null:u)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:NN.map(({url:l,label:u})=>i.jsx("option",{value:l,title:u,children:u.split(" ")[0]},l))}),i.jsx(yn,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const L_=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function CT(){const e=Bi(d=>d.settings),t=Bi(d=>d.update),n=Bi(d=>d.updateEvent),r=Bi(d=>d.updateAgentOverride),a=Bi(d=>d.load);N.useEffect(()=>{a()},[a]);const l=async()=>{await AN()==="granted"&&t({...e,browserNotificationEnabled:!0})},u=(d,h,p,m)=>{d==="general"?n(h,{[p]:m}):r(d,h,{[p]:m})},c=(d,h,p)=>{d==="general"?n(h,{customSoundUrl:p}):r(d,h,{customSoundUrl:p})};return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"space-y-3",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),i.jsx(D_,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>t({...e,soundEnabled:d})}),i.jsx(D_,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?l():t({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&i.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),i.jsx("div",{className:"border border-border rounded overflow-hidden",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:i.jsxs("tr",{className:"border-b border-border",children:[i.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),L_.map(d=>i.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),i.jsx("tbody",{children:jN.map(d=>i.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[i.jsx("td",{className:"px-3 py-2",children:i.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),L_.map(h=>{const p=x1(e,d.key,h.key==="general"?void 0:h.key),m=p1[d.key];return i.jsx("td",{className:"px-2 py-2 align-top",children:i.jsxs("div",{className:"flex flex-col items-center gap-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:i.jsx("input",{type:"checkbox",checked:p.soundEnabled,onChange:x=>u(h.key,d.key,"soundEnabled",x.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),i.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:i.jsx("input",{type:"checkbox",checked:p.browserNotification,onChange:x=>u(h.key,d.key,"browserNotification",x.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),p.soundEnabled&&e.soundEnabled&&i.jsx(wT,{value:p.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:x=>c(h.key,d.key,x)})]})},h.key)})]},d.key))})]})})]})]})}function D_({label:e,description:t,checked:n,onChange:r}){return i.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer group",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),i.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:t})]}),i.jsx("div",{className:"flex-shrink-0 pt-0.5",children:i.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${n?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:a=>{a.preventDefault(),r(!n)},children:i.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${n?"translate-x-4":"translate-x-0.5"}`})})})]})}const Ze=N.forwardRef(({variant:e="secondary",size:t="md",className:n="",children:r,...a},l)=>{const u="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return i.jsx("button",{ref:l,className:`${u} ${c[e]} ${d[t]} ${n}`,...a,children:r})});Ze.displayName="Button";async function R_(e,t,n){try{const r=await Se(e,t);return r.ok?(await n(),{success:!0}):{success:!1,error:(await r.json()).error}}catch{return{success:!1,error:"Network error"}}}const An=Mn((e,t)=>({defaults:[],userItems:[],projectItems:[],items:[],selectedDirectory:null,diagnostics:[],loading:!1,fetchSkills:async()=>{e({loading:!0});try{const r=await(await Se("/api/skills")).json();e({defaults:r.defaults??[],userItems:r.userItems??[],projectItems:r.projectItems??[],items:r.items??[],selectedDirectory:r.selectedDirectory??null,diagnostics:r.diagnostics??[],loading:!1})}catch{e({loading:!1})}},toggleSkill:async n=>{try{const a=await(await Se(`/api/skills/${n}/toggle`,{method:"POST"})).json();e(l=>({defaults:l.defaults.map(u=>u.id===n?{...u,enabled:a.enabled}:u),userItems:l.userItems.map(u=>u.id===n?{...u,enabled:a.enabled}:u),projectItems:l.projectItems.map(u=>u.id===n?{...u,enabled:a.enabled}:u),items:l.items.map(u=>u.id===n?{...u,enabled:a.enabled}:u)}))}catch{}},fetchSkill:async n=>{try{const r=await Se(`/api/skills/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await Se(`/api/skills/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createSkill:async(n,r)=>{const a=await ui("POST","/api/skills",{...n,destination:r});return a.success&&await t().fetchSkills(),a},updateSkill:async(n,r)=>{const a=await ui("PUT",`/api/skills/${n}`,r);return a.success&&await t().fetchSkills(),a},deleteSkill:async n=>{try{const r=await Se(`/api/skills/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async(n,r)=>vd(`/api/skills/${n}/duplicate`,()=>t().fetchSkills(),r),selectDirectory:async n=>R_("/api/skills/library",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})},t().fetchSkills),removeDirectory:async()=>{await Se("/api/skills/library",{method:"DELETE"}),await t().fetchSkills()},installSkill:async n=>{const r=new FormData;r.append("packageName",n.packageName),r.append("paths",JSON.stringify(n.files.map(a=>a.path)));for(const a of n.files)r.append("files",a.file,a.file.name);return R_("/api/skills/install",{method:"POST",body:r},t().fetchSkills)}}));function Wl(){const[e,t]=N.useState({id:null,type:null}),n=N.useCallback(l=>t({id:l,type:"delete"}),[]),r=N.useCallback(()=>t({id:null,type:null}),[]),a=N.useCallback((l,u)=>e.id===l&&e.type===u,[e.id,e.type]);return{requestDelete:n,clearConfirm:r,isConfirming:a}}function ig({onConfirm:e,onCancel:t}){return i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),i.jsx("button",{onClick:t,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function ag({onClick:e}){return i.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:i.jsx(lo,{})})}function Ku({onClick:e}){return i.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:i.jsx(Ll,{})})}function kr({label:e,value:t,onChange:n,placeholder:r,readOnly:a,hint:l,mono:u}){return i.jsxs("div",{children:[i.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,l&&i.jsx("span",{className:"text-text-muted ml-1",children:l})]}),i.jsx("input",{value:t,onChange:c=>n(c.target.value),readOnly:a,placeholder:r,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${u?"font-mono":""} ${a?"opacity-60":""}`})]})}function kT({onCancel:e,onSave:t,saving:n,saveDisabled:r}){return i.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[i.jsx(Ze,{variant:"secondary",onClick:e,children:"Cancel"}),i.jsx(Ze,{variant:"primary",onClick:t,disabled:n||r,children:n?"Saving...":"Save"})]})}function Qa({message:e}){return i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function D1({description:e,onNew:t,loading:n,hasItems:r,children:a}){return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("p",{className:"text-text-secondary text-sm",children:e}),i.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:i.jsx(Ze,{variant:"primary",size:"sm",onClick:t,children:"+ New"})})]}),n&&!r?i.jsx("div",{className:"text-text-muted text-sm",children:"Loading..."}):r?a:i.jsx("div",{className:"text-text-muted text-sm",children:"No items defined."})]})}function R1({label:e="Custom",children:t}){return i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsx("div",{className:"space-y-2",children:t})]})}function O1({description:e,onNew:t,newLabel:n="+ New"}){return i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("p",{className:"text-text-secondary text-sm",children:e}),i.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:i.jsx(Ze,{variant:"primary",size:"sm",onClick:t,children:n})})]})}function og({loading:e,hasItems:t,loadingLabel:n,emptyLabel:r,children:a}){return e&&!t?i.jsx("div",{className:"text-text-muted text-sm",children:n}):t?i.jsx("div",{className:"space-y-4",children:a}):r?i.jsx("div",{className:"text-text-muted text-sm",children:r}):null}function I1({name:e,id:t,nameLabel:n="Name",idLabel:r="ID",namePlaceholder:a="My Item",idPlaceholder:l="my-item",nameHint:u,readOnlyId:c=!1,readOnlyHint:d="(read-only)",onNameChange:h,onIdChange:p}){return i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(kr,{label:n,value:e,onChange:h,placeholder:a,hint:u}),i.jsx(kr,{label:r,value:t,onChange:p,readOnly:c,placeholder:l,hint:c?d:void 0,mono:!0})]})}function M1(e={}){const{initialData:t={}}=e,[n,r]=N.useState("list"),[a,l]=N.useState(null),[u,c]=N.useState(""),[d,h]=N.useState(!1),[p,m]=N.useState(t),x=N.useCallback(()=>{m(t),c(""),l(null)},[t]),y=N.useCallback(S=>{r(S),S==="list"&&x()},[x]),w=N.useCallback(S=>{m(v=>typeof S=="function"?S(v):S)},[]),C=N.useCallback((S,v={})=>{l(S),r("edit"),m({...v}),c("")},[]),_=N.useCallback(()=>{l(null),r("edit"),m(t),c("")},[t]);return{view:n,editingId:a,formError:u,saving:d,formData:p,setView:y,setEditingId:l,setFormError:c,setFormData:w,setSaving:h,resetForm:x,startEditing:C,startNew:_}}function Rl({isOpen:e,onClose:t,onConfirm:n,title:r,message:a,confirmLabel:l="Confirm",confirmVariant:u="primary",disabled:c=!1}){return i.jsx(wt,{isOpen:e,onClose:t,title:r,size:"sm",children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"text-text-secondary",children:a}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ze,{variant:"secondary",onClick:t,disabled:c,children:"Cancel"}),i.jsx(Ze,{variant:u,onClick:n,disabled:c,autoFocus:!0,children:l})]})]})})}const ET={sm:"w-4 h-4",md:"w-8 h-8",lg:"w-12 h-12"};function hi({size:e="md",className:t=""}){return i.jsx("div",{className:`animate-spin border-2 border-accent-primary border-t-transparent rounded-full ${ET[e]} ${t}`})}function jT({text:e,...t}){return i.jsxs("div",{className:"text-center",children:[i.jsx(hi,{...t,className:"mx-auto mb-4"}),e&&i.jsx("div",{className:"text-text-secondary",children:e})]})}function P1(e){return e.split(/[\\/]/).filter(Boolean).pop()??""}function NT(e){const t=e.includes("\\")?"\\":"/";return e.split(/[\\/]/).filter(Boolean).map((n,r,a)=>({name:n,path:t==="/"?"/"+a.slice(0,r+1).join("/"):a.slice(0,r+1).join("\\")+(r===0?"\\":"")}))}function B1(e,t=28){if(e.length<=t)return e;const n=e.split("/").filter(Boolean);if(n.length<=2)return e;const r=n[0],a=n[n.length-1],l=n.slice(1,-1).join("/"),u=t-r.length-a.length-3;if(u<0)return e;const c=l.slice(0,Math.floor(u/2)),d=l.slice(-Math.ceil(u/2));return`/${r}/${c}...${d}/${a}`}const oi=N.forwardRef(({className:e="",...t},n)=>i.jsx("input",{ref:n,className:`bg-bg-tertiary border border-border rounded px-3 py-2 text-text-primary placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 focus:border-accent-primary ${e}`,...t}));oi.displayName="Input";function Cd({onSelect:e,onClose:t,initialPath:n}){const[r,a]=N.useState(null),[l,u]=N.useState(!0),[c,d]=N.useState(""),[h,p]=N.useState(-1),m=N.useRef(null),x=N.useRef(null),y=N.useCallback(async b=>{u(!0),d(""),p(-1);try{const E=b?`/api/directories?path=${encodeURIComponent(b)}`:"/api/directories",T=await(await Se(E)).json();a(T)}catch(E){console.error("Failed to load directories:",E)}finally{u(!1)}},[]);N.useEffect(()=>{y(n)},[n,y]);const w=NT((r==null?void 0:r.current)??""),C=(r==null?void 0:r.directories.filter(b=>c===""||b.name.toLowerCase().includes(c.toLowerCase())))??[],_=[...!c&&(r!=null&&r.parent)?[{type:"parent",path:r.parent,name:".."}]:[],...C.map(b=>({type:"dir",path:b.path,name:b.name}))];N.useEffect(()=>{p(c?0:-1)},[c,C.length]),N.useEffect(()=>{if(h>=0&&x.current){const b=x.current.querySelector(`[data-index="${h}"]`);b==null||b.scrollIntoView({block:"nearest"})}},[h]);const S=b=>{var E;if(b.key==="ArrowDown")b.preventDefault(),p(j=>Math.min(j+1,_.length-1));else if(b.key==="ArrowUp")b.preventDefault(),p(j=>Math.max(j-1,0));else if(b.key==="Enter"){if(h<0||!_[h]||b.target instanceof HTMLElement&&b.target.dataset.select==="true")return;b.preventDefault(),b.shiftKey?y(_[h].path):e(_[h].path)}else b.key==="Escape"&&(d(""),(E=m.current)==null||E.focus())},v=i.jsx("div",{className:"flex flex-col gap-2",children:i.jsx("button",{onClick:t,className:"w-full text-center text-text-muted hover:text-text-secondary text-sm",children:"Cancel"})});return i.jsx(wt,{isOpen:!0,onClose:t,title:"Select Folder",size:"lg",footer:v,scrollable:!1,children:i.jsxs("div",{ref:x,className:"flex flex-col flex-1 min-h-0 -m-4",onKeyDown:S,children:[i.jsxs("div",{className:"flex-shrink-0 bg-bg-secondary border-b border-border",children:[r&&i.jsx("div",{className:"px-3 pt-3 pb-1",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsxs("div",{className:"flex items-center flex-wrap min-w-0",children:[w.map((b,E)=>i.jsxs("span",{className:"flex items-center shrink-0",children:[i.jsx("span",{className:"text-text-muted",children:"/"}),i.jsx("button",{onClick:()=>y(b.path),className:`px-1 ${E===w.length-1?"text-accent-primary font-medium":"text-text-secondary hover:text-accent-primary"}`,children:b.name})]},b.path)),w.length===0&&i.jsx("button",{onClick:()=>y("/"),className:"text-text-muted hover:text-accent-primary",children:"/"})]}),(r==null?void 0:r.current)&&i.jsx("button",{onClick:()=>e(r.current),className:"ml-auto shrink-0 px-4 py-2 text-sm font-medium rounded-lg bg-accent-primary text-text-primary hover:bg-accent-primary/90",children:"Select"})]})}),i.jsx("div",{className:"px-4 py-2",children:i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted pointer-events-none flex items-center justify-center",children:i.jsx(Wi,{})}),i.jsx(oi,{autoFocus:!0,ref:m,value:c,onChange:b=>d(b.target.value),placeholder:"Filter directories...",className:"w-full pl-9"})]})})]}),i.jsx("div",{className:"flex-1 overflow-y-auto",children:l?i.jsx("div",{className:"p-8 text-center",children:i.jsx(hi,{size:"sm"})}):_.length===0?i.jsx("div",{className:"p-8 text-center text-text-muted text-sm",children:c?"No matching directories":"No subdirectories"}):i.jsx("div",{className:"divide-y divide-border",children:_.map((b,E)=>i.jsxs("div",{"data-index":E,className:`group flex items-center ${E===h?"bg-accent-primary/20":"hover:bg-bg-tertiary/50"}`,children:[i.jsxs("button",{onClick:()=>{y(b.path)},className:"flex-1 flex items-center gap-3 p-3 text-left min-w-0",tabIndex:-1,children:[b.type==="parent"?i.jsx(JN,{className:"w-5 h-5 text-text-muted shrink-0"}):i.jsx(Or,{className:"w-5 h-5 shrink-0"}),i.jsx("span",{className:"truncate",children:b.name}),b.type==="dir"&&i.jsx(yn,{className:`w-5 h-5 text-text-muted shrink-0 ml-1 ${E===h?"opacity-100":"opacity-0 group-hover:opacity-100"}`,rotate:-90})]}),b.type==="dir"&&i.jsx("button",{"data-select":"true",tabIndex:E===h?0:-1,onClick:j=>{j.stopPropagation(),e(b.path)},className:`mr-2 shrink-0 px-4 py-2 text-sm font-medium rounded-lg bg-accent-primary text-text-primary hover:bg-accent-primary/90 ${E===h?"opacity-100":"opacity-0 group-hover:opacity-100"}`,"aria-label":`Select ${b.name}`,children:"Select"})]},b.path))})})]})})}function $1(e,t){if(!e||!t.some(n=>n.path==="SKILL.md"))throw new Error("Drop one folder containing SKILL.md.");return{packageName:e,files:t}}function TT(e){const t=[...e];if(!t.length)throw new Error("Choose one skill folder.");const n=new Set(t.map(a=>a.webkitRelativePath.split("/")[0]).filter(Boolean));if(n.size!==1)throw new Error("Choose exactly one skill folder.");const r=[...n][0];return $1(r,t.map(a=>({path:a.webkitRelativePath.slice(r.length+1),file:a})))}function AT(e){return new Promise((t,n)=>e.file(t,n))}async function z1(e,t=""){const n=e.createReader(),r=[];for(;;){const l=await new Promise((u,c)=>n.readEntries(u,c));if(!l.length)break;r.push(...l)}return(await Promise.all(r.map(async l=>{const u=t?`${t}/${l.name}`:l.name;return l.isDirectory?z1(l,u):[{path:u,file:await AT(l)}]}))).flat()}async function LT(e){const t=[...e.items].filter(r=>r.kind==="file").map(r=>{var a;return((a=r.webkitGetAsEntry)==null?void 0:a.call(r))??null}).filter(r=>!!r);if(t.length!==1||!t[0].isDirectory)throw new Error("Drop exactly one skill folder.");const n=t[0];return $1(n.name,await z1(n))}function DT({selectedDirectory:e,onSelect:t,onRemove:n,onRefresh:r,onInstall:a}){const[l,u]=N.useState(!1),[c,d]=N.useState(!1),[h,p]=N.useState(""),[m,x]=N.useState(null),[y,w]=N.useState(!1),C=N.useRef(null);N.useEffect(()=>{var E;(E=C.current)==null||E.setAttribute("webkitdirectory","")},[]);const _=E=>{x(E)},S=async()=>{if(!m||y)return;w(!0);const E=await t(m);if(E&&!E.success){p(E.error??"Cannot use selected folder."),w(!1);return}x(null),u(!1),w(!1)},v=async E=>{d(!0),p("");const j=await a(E);d(!1),j.success||p(j.error??"Failed to install skill package.")},b=async E=>{if(E.preventDefault(),!(!(e!=null&&e.available)||c))try{await v(await LT(E.dataTransfer))}catch(j){p(j instanceof Error?j.message:"Invalid skill folder.")}};return i.jsxs("section",{className:"mb-4 rounded border border-border bg-bg-tertiary/30 p-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Skills folder"}),i.jsx("p",{className:"mt-1 truncate text-xs text-text-muted",children:(e==null?void 0:e.configuredPath)??"No shared folder selected"})]}),i.jsxs("div",{className:"flex shrink-0 gap-2",children:[i.jsx(Ze,{variant:"secondary",onClick:()=>u(!0),children:"Change folder"}),e&&i.jsxs(i.Fragment,{children:[i.jsx(Ze,{variant:"secondary",onClick:r,children:"Refresh"}),e.custom&&i.jsx(Ze,{variant:"secondary",onClick:n,children:"Use default"})]})]})]}),i.jsx("button",{type:"button",disabled:!(e!=null&&e.available)||c,onClick:()=>{var E;return(E=C.current)==null?void 0:E.click()},onDragOver:E=>E.preventDefault(),onDrop:b,className:"mt-3 w-full rounded border border-dashed border-border px-4 py-5 text-center text-xs text-text-secondary disabled:cursor-not-allowed disabled:opacity-50",children:e!=null&&e.available?c?"Installing skill package...":"Drop one skill folder here":"Choose a skills folder to enable drag and drop."}),i.jsx("input",{ref:C,hidden:!0,type:"file",multiple:!0,onChange:E=>{var j;if((j=E.target.files)!=null&&j.length)try{v(TT(E.target.files))}catch(T){p(T instanceof Error?T.message:"Invalid skill folder.")}finally{E.target.value=""}}}),h&&i.jsx("p",{className:"mt-2 text-xs text-error",children:h}),l&&i.jsx(Cd,{initialPath:(e==null?void 0:e.resolvedPath)??void 0,onSelect:_,onClose:()=>u(!1)}),i.jsx(Rl,{isOpen:m!==null,onClose:()=>x(null),onConfirm:S,title:"Trust this folder?",message:"Skills may contain instructions and scripts. Select this folder for discovery without executing package content?",confirmLabel:"Trust folder",disabled:y})]})}function Yr({enabled:e,onClick:t,label:n,disabled:r}){return i.jsx("button",{type:"button",role:"switch","aria-checked":e,"aria-label":n,onClick:r?void 0:t,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${e?"bg-accent-primary":"bg-bg-tertiary"} ${r?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${e?"translate-x-6":"translate-x-1"}`})})}function H1({isBuiltIn:e,isConfirmingDelete:t,onView:n,onEdit:r,onDuplicate:a,onDelete:l,onCancelDelete:u,actions:c,children:d}){return i.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[i.jsx("div",{className:"min-w-0 flex-1 mr-3",children:d}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&n&&i.jsx("button",{onClick:n,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:i.jsx(eg,{})}),i.jsx(Ku,{onClick:a}),!e&&r&&i.jsx(qi,{onClick:r}),!e&&l&&(t?i.jsx(ig,{onConfirm:()=>{l==null||l()},onCancel:()=>u==null?void 0:u()}):i.jsx(ag,{onClick:()=>l==null?void 0:l()})),c]})]})}function RT({id:e,name:t,description:n,isBuiltIn:r,isConfirmingDelete:a,onView:l,onEdit:u,onDuplicate:c,onDelete:d,onCancelDelete:h,actions:p}){return i.jsxs(H1,{isBuiltIn:r,isConfirmingDelete:a,onView:l,onEdit:u,onDuplicate:c,onDelete:d,onCancelDelete:h,actions:p,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-primary text-sm font-medium",children:t}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),n&&i.jsx("p",{className:"text-text-muted text-xs truncate",children:n})]})}function O_({skill:e,isBuiltIn:t,isConfirmingDelete:n,onView:r,onEdit:a,onDuplicate:l,onDelete:u,onToggle:c,readOnly:d=!1}){return i.jsx(RT,{id:e.id,name:e.name,description:e.description,isBuiltIn:t,isConfirmingDelete:n,onView:r,onEdit:d?void 0:a,onDuplicate:l,onDelete:d?void 0:u,actions:i.jsx(Yr,{enabled:e.enabled,onClick:c,label:`Activation for ${e.name}`})})}function OT({skill:e,deleting:t,error:n,onClose:r,onConfirm:a}){return i.jsxs(wt,{isOpen:e!==null,onClose:r,title:"Delete skill?",size:"sm",closeOnBackdropClick:!t,closeOnEscape:!t,footer:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ze,{variant:"secondary",onClick:r,disabled:t,children:"Cancel"}),i.jsx(Ze,{variant:"danger",onClick:a,disabled:t,children:t?"Deleting...":"Delete skill"})]}),children:[i.jsx("p",{className:"text-sm font-medium text-text-primary",children:"This skill files will be deleted."}),i.jsx("p",{className:"mt-2 text-sm text-text-secondary",children:"The full skill folder and all its contents will be removed."}),e&&i.jsx("p",{className:"mt-3 break-all font-mono text-xs text-text-muted",children:e.path}),n&&i.jsx("p",{className:"mt-3 text-sm text-error",children:n})]})}function IT({isOpen:e}){const t=An(te=>te.defaults),n=An(te=>te.userItems),r=An(te=>te.projectItems),a=An(te=>te.items),l=An(te=>te.selectedDirectory),u=An(te=>te.diagnostics),c=An(te=>te.loading),d=An(te=>te.fetchSkills),h=An(te=>te.fetchSkill),p=An(te=>te.fetchDefaultContent),m=An(te=>te.createSkill),x=An(te=>te.updateSkill),y=An(te=>te.deleteSkill),w=An(te=>te.selectDirectory),C=An(te=>te.removeDirectory),_=An(te=>te.installSkill),S=An(te=>te.toggleSkill),[v,b]=N.useState(null),[E,j]=N.useState(!1),[T,D]=N.useState(""),{view:L,editingId:I,formError:P,saving:W,formData:H,setView:R,setEditingId:U,setFormError:V,setFormData:G,setSaving:Z}=M1(),{clearConfirm:X}=Wl();N.useEffect(()=>{e&&(d(),R("list"),U(null),X())},[e,d,X]);const $=(te,se,xe,oe)=>{G({name:oe??te.metadata.name,id:xe??te.metadata.id,description:te.metadata.description??"",version:te.metadata.version??"1.0.0",prompt:te.prompt,isReadOnly:se,destination:"user"})},O=async te=>{if(t.some(xe=>xe.id===te)){const xe=await p(te);if(!xe)return;$(xe,!0),U(te),V(""),R("edit")}else{const xe=await h(te);if(!xe)return;$(xe,!0),U(te),V(""),R("edit")}},M=async te=>{const xe=t.some(Oe=>Oe.id===te)?await p(te):await h(te);if(!xe)return;const oe=`${te}-copy-${Date.now()}`;$(xe,!1,oe,`${xe.metadata.name} (copy)`),U(null),V(""),R("edit")},q=()=>{G({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1,destination:"user"}),R("edit")},z=async te=>{const se=await h(te);se&&($(se,!1),U(te),V(""),R("edit"))},ee=async()=>{if(!v)return;j(!0),D("");const te=await y(v.id);if(j(!1),!te.success){D(te.error??"Failed to delete skill.");return}await d(),b(null),X()},Q=async()=>{const te=I??H.id;if(!te||!H.name||!H.prompt){V("Name, ID, and prompt are required.");return}Z(!0),V("");const se={metadata:{id:te,name:H.name,description:H.description,version:H.version},prompt:H.prompt},xe=I?await x(I,se):await m(se,H.destination);if(Z(!1),!xe.success){V(xe.error??"Failed to save skill.");return}R("list")},ne=te=>{G(se=>({...se,name:te})),I||G(se=>({...se,id:te.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},K=H.isReadOnly;if(L==="edit")return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"flex justify-between items-center mb-3",children:[i.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:K?H.name:I?"Edit Skill":"New Skill"}),i.jsx("button",{onClick:()=>R("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),P&&i.jsx(Qa,{message:P}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(I1,{name:H.name,id:H.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:ne,onIdChange:()=>{}}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(kr,{label:"Description",value:H.description,onChange:te=>G(se=>({...se,description:te})),placeholder:"What this skill does...",readOnly:K}),i.jsx(kr,{label:"Version",value:H.version,onChange:te=>G(se=>({...se,version:te})),placeholder:"1.0.0",readOnly:K})]})]}),i.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),i.jsx("textarea",{value:H.prompt,onChange:te=>G(se=>({...se,prompt:te.target.value})),readOnly:K,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),!I&&i.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Save to:"}),i.jsxs("select",{value:H.destination,onChange:te=>G(se=>({...se,destination:te.target.value})),className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[i.jsx("option",{value:"user",children:"Global config"}),i.jsx("option",{value:"project",children:"Project (.openfox/)"})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[i.jsx(Ze,{variant:"secondary",onClick:()=>R("list"),children:"Cancel"}),K?i.jsx(Ze,{variant:"primary",onClick:()=>{G(te=>({...te,name:te.name+" (copy)",id:`${I}-copy-${Date.now()}`,isReadOnly:!1})),U(null)},children:"Duplicate & Customize"}):i.jsx(Ze,{variant:"primary",onClick:Q,disabled:W||!H.name||!H.id||!H.prompt,children:W?"Saving...":"Save"})]})]});function B({items:te}){return te.map(se=>i.jsx(O_,{skill:se,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>O(se.id),onEdit:()=>z(se.id),onDuplicate:()=>M(se.id),onDelete:()=>{D(""),b(se)},onToggle:()=>S(se.id),readOnly:se.readOnly},se.id))}return i.jsxs("div",{children:[i.jsx(OT,{skill:v,deleting:E,error:T,onClose:()=>{E||b(null)},onConfirm:ee}),i.jsx(DT,{selectedDirectory:l,onSelect:w,onRemove:C,onRefresh:d,onInstall:_}),u.length>0&&i.jsx("div",{className:"mb-3 rounded border border-accent-warning/40 bg-accent-warning/10 p-2 text-xs text-text-secondary",children:u.map((te,se)=>i.jsx("p",{children:te},`${te}-${se}`))}),i.jsx(O1,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:q}),i.jsxs(og,{loading:c,hasItems:t.length>0||n.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[t.length>0&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),i.jsx("div",{className:"space-y-2",children:t.map(te=>i.jsx(O_,{skill:te,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>O(te.id),onDuplicate:()=>M(te.id),onToggle:()=>S(te.id)},te.id))})]}),n.length>0&&i.jsx(R1,{children:i.jsx(B,{items:n})}),a.some(te=>["global-shared","selected","project-shared"].includes(te.source))&&i.jsxs("div",{className:"mt-4",children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Shared"}),i.jsx("div",{className:"space-y-2",children:i.jsx(B,{items:a.filter(te=>["global-shared","selected","project-shared"].includes(te.source))})})]}),r.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),i.jsx("div",{className:"space-y-2",children:i.jsx(B,{items:r})})]})]})]})}function Qi(){const e=Ht(a=>a.settings),t=Ht(a=>a.loading),n=Ht(a=>a.getSetting),r=Ht(a=>a.setSetting);return{settings:e,loading:t,getSetting:n,setSetting:r}}function MT({isOpen:e}){const{settings:t,loading:n,getSetting:r,setSetting:a}=Qi(),l=t[Te.GLOBAL_INSTRUCTIONS]??"",u=n[Te.GLOBAL_INSTRUCTIONS]??!1,[c,d]=N.useState(l),[h,p]=N.useState(!1),[m,x]=N.useState(!1);N.useEffect(()=>{e&&r(Te.GLOBAL_INSTRUCTIONS)},[e,r]),N.useEffect(()=>{d(l),p(!1)},[l]);const y=async()=>{x(!0),await a(Te.GLOBAL_INSTRUCTIONS,c),x(!1),p(!1)},w=()=>{d(l),p(!1)},C=u||m;return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),i.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),i.jsx("textarea",{value:c,onChange:_=>{d(_.target.value),p(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ze,{variant:"secondary",onClick:w,disabled:!h,children:"Discard"}),i.jsx(Ze,{variant:"primary",onClick:y,disabled:!h||C,children:m?"Saving...":"Save"})]})]})}function PT(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(t){const n=parseInt(t[1]??"0",16),r=parseInt(t[2]??"0",16),a=parseInt(t[3]??"0",16);return`${n} ${r} ${a}`}return e}function Hu(e){const t=e.split(" ").map(n=>parseInt(n,10));return t.length===3&&t.every(n=>!isNaN(n))?`#${t.map(n=>(n??0).toString(16).padStart(2,"0")).join("")}`:e}function BT({isOpen:e,isNew:t,basePresetId:n,presetName:r,mode:a,initialTokens:l,onClose:u,onSave:c}){const[d,h]=N.useState(l),[p,m]=N.useState(r),[x,y]=N.useState(a);N.useEffect(()=>{h(l),m(r)},[l,r]);const w=(b,E)=>{const j=E.startsWith("#")?PT(E):E;h(T=>({...T,[b]:j}))},C=()=>{c(p.trim()||"Untitled",{...d},x)},_=v1.reduce((b,E)=>{const j=E.category;return b[j]||(b[j]=[]),b[j].push(E),b},{}),S={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},v=zn.find(b=>b.id===n);return i.jsx(wt,{isOpen:e,onClose:u,size:"lg",title:t?"New Theme":"Edit Theme",closeOnBackdropClick:!0,closeOnEscape:!0,footer:i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx("button",{type:"button",onClick:u,className:"px-4 py-2 border border-border rounded text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:"Cancel"}),i.jsx("button",{type:"button",onClick:C,className:"px-4 py-2 bg-accent-primary text-white rounded hover:bg-accent-primary/80 transition-colors text-sm",children:"Save"})]}),children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),i.jsx("input",{type:"text",value:p,onChange:b=>m(b.target.value),className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Mode"}),i.jsxs("div",{className:"flex rounded overflow-hidden border border-border",children:[i.jsx("button",{type:"button",onClick:()=>y("dark"),className:`px-3 py-2 text-xs font-medium transition-colors ${x==="dark"?"bg-accent-primary text-white":"bg-bg-tertiary text-text-muted hover:text-text-primary"}`,children:"Dark"}),i.jsx("button",{type:"button",onClick:()=>y("light"),className:`px-3 py-2 text-xs font-medium transition-colors ${x==="light"?"bg-accent-primary text-white":"bg-bg-tertiary text-text-muted hover:text-text-primary"}`,children:"Light"})]})]})]}),!t&&i.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",i.jsx("span",{className:"text-text-primary",children:v==null?void 0:v.name})]}),Object.entries(_).map(([b,E])=>i.jsxs("div",{className:"space-y-3",children:[i.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:S[b]??b}),i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:E.map(j=>i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("label",{htmlFor:j.key,className:"text-xs text-text-muted",children:j.label}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"color",id:j.key,value:Hu(d[j.key]??j.defaultValue),onChange:T=>w(j.key,T.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent flex-shrink-0"}),i.jsx("input",{type:"text",value:d[j.key]??j.defaultValue,onChange:T=>w(j.key,T.target.value),className:"flex-1 min-w-0 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]},j.key))})]},b))]})})}function I_({preset:e,isActive:t,isUnderlying:n,onClick:r,onNewFrom:a,onEdit:l,onDelete:u}){return i.jsxs("div",{className:"relative group",children:[i.jsxs("button",{type:"button",onClick:r,className:`flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors min-w-[80px] ${t?"border-accent-primary bg-bg-tertiary text-text-primary":n?"border-dashed border-accent-primary/50 bg-bg-tertiary/50 text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[i.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:e.id==="system"?"transparent":Hu(e.tokens["color-bg-primary"]??"#000"),borderColor:Hu(e.tokens["color-border"]??"#000")},children:e.id==="system"?i.jsx("div",{className:"w-4 h-4 rounded-full",style:{background:"linear-gradient(135deg, #000 50%, #fff 50%)"}}):i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hu(e.tokens["color-text-primary"]??"#fff")}})}),i.jsx("span",{className:"text-xs",children:e.name})]}),a&&i.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),a()},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Create custom theme based on this",children:i.jsx("span",{className:"text-xs",children:"✎"})}),l&&i.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),l()},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Edit",children:i.jsx("span",{className:"text-xs",children:"✎"})}),u&&i.jsx("button",{type:"button",onClick:c=>u(c),className:"absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent-error text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20",children:i.jsx(js,{className:"w-3 h-3"})})]})}function $T(){const[e,t]=N.useState(null),n=Rt(H=>H.currentPreset),r=Rt(H=>H.isCustom),a=Rt(H=>H.basePreset),l=Rt(H=>H.isSystem),u=Rt(H=>H.systemDarkPreset),c=Rt(H=>H.systemLightPreset),d=Rt(H=>H.applyPreset),h=Rt(H=>H.applyUserPreset),p=Rt(H=>H.deleteUserPreset),m=Rt(H=>H.saveTheme),x=Rt(H=>H.setSystemDarkPreset),y=Rt(H=>H.setSystemLightPreset),w=Rt(H=>H.activeUserPresetId),C=Rt(H=>H.userPresets),_=zn.filter(H=>H.mode==="dark"),S=zn.filter(H=>H.mode==="light"),v=H=>{var R;if(l){const U=C[H];if(!U)return;const V=U.mode??((R=zn.find(G=>G.id===U.basePreset))==null?void 0:R.mode);V==="dark"?x(U.id):V==="light"&&y(U.id)}else h(H)},b=H=>{const R=zn.find(U=>U.id===H);R&&t({type:"new",presetIndex:C.length,basePresetId:H,presetName:R.name+" Copy",mode:R.mode??"dark",tokens:{...R.tokens}})},E=H=>{const R=C[H];if(!R)return;const U=zn.find(G=>G.id===R.basePreset),V=U?{...U.tokens,...R.tokens}:R.tokens;t({type:"edit",presetIndex:H,basePresetId:R.basePreset,presetName:R.name,mode:R.mode??"dark",tokens:V})},j=(H,R,U)=>{if(!e)return;const V=[...C];if(e.type==="new"){const G={id:"custom-"+Date.now(),name:H,basePreset:e.basePresetId,mode:U,tokens:R};V.push(G);const Z=V.length-1;Rt.setState({userPresets:V}),Rt.getState().saveUserPresets(),Rt.getState().applyUserPreset(Z)}else{const G=V[e.presetIndex];G&&(V[e.presetIndex]={...G,name:H,mode:U,tokens:R}),Rt.setState({userPresets:V}),Rt.getState().saveUserPresets(),Rt.getState().applyUserPreset(e.presetIndex)}t(null)},T=()=>{t(null)},D=(H,R)=>{H.stopPropagation(),p(R)},L=l?"system":r?a:n,I=()=>{l?(d(n),m(JSON.stringify({preset:n})).catch(()=>{})):(d("system"),m(JSON.stringify({preset:"system"})).catch(()=>{}))},P=H=>{if(l){const R=zn.find(U=>U.id===H);(R==null?void 0:R.mode)==="dark"?x(H):(R==null?void 0:R.mode)==="light"&&y(H)}else d(H),m(JSON.stringify({preset:H})).catch(()=>{})},W=H=>{const R=zn.find(U=>U.id===H.basePreset);return R?{...R.tokens,...H.tokens}:H.tokens};return i.jsxs("div",{className:"space-y-4",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Theme"}),i.jsxs("label",{className:"flex items-center justify-between gap-3 cursor-pointer",children:[i.jsx("span",{className:"text-sm text-text-primary font-medium",children:"Follow system theme"}),i.jsx("button",{type:"button",onClick:I,className:`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${l?"bg-accent-primary":"bg-bg-tertiary"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l?"translate-x-6":"translate-x-1"}`})})]}),[{title:"Dark Themes",mode:"dark"},{title:"Light Themes",mode:"light"}].map(({title:H,mode:R})=>{const U=R==="dark"?_:S,V=C.filter(G=>{var X;return(G.mode??((X=zn.find($=>$.id===G.basePreset))==null?void 0:X.mode))===R});return i.jsxs("div",{children:[i.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase mb-2",children:H}),i.jsxs("div",{className:"flex flex-wrap gap-2",children:[U.map(G=>i.jsx(I_,{preset:G,isActive:G.id===L&&!r,isUnderlying:l&&(G.id===u||G.id===c),onClick:()=>P(G.id),onNewFrom:()=>b(G.id)},G.id)),V.map(G=>{const Z=C.indexOf(G),X=W(G);return i.jsx(I_,{preset:{id:G.id,name:G.name,tokens:X},isActive:w===G.id,isUnderlying:l&&(G.id===u||G.id===c),onClick:()=>v(Z),onEdit:()=>E(Z),onDelete:$=>D($,Z)},G.id)})]})]},H)}),e&&i.jsx(BT,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,mode:e.mode,initialTokens:e.tokens,onClose:T,onSave:j})]})}function zT(){return i.jsx($T,{})}function HT(){const{settings:e,loading:t,getSetting:n,setSetting:r}=Qi(),a=t[Te.DISPLAY_SHOW_THINKING]??!1,l=e[Te.DISPLAY_MAX_VISIBLE_ITEMS]??"300",[u,c]=N.useState(l);N.useEffect(()=>{n(Te.DISPLAY_MAX_VISIBLE_ITEMS)},[n]),N.useEffect(()=>{c(l)},[l]);const d=()=>{const w=parseInt(u,10),C=isNaN(w)||w<0?0:Math.min(w,9999);c(String(C)),r(Te.DISPLAY_MAX_VISIBLE_ITEMS,String(C))},h=[{key:Te.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:Te.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:Te.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:Te.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:Te.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"},{key:Te.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING,label:"Show syntax highlighting",description:"Nicer formatting, but costly - applies to code blocks, diffs, and file previews"}],p=Object.fromEntries(h.map(w=>[w.key,e[w.key]??"true"])),[m,x]=N.useState(()=>Object.fromEntries(h.map(w=>[w.key,p[w.key]==="true"])));N.useEffect(()=>{h.forEach(w=>n(w.key))},[n]),N.useEffect(()=>{x(Object.fromEntries(h.map(w=>[w.key,p[w.key]==="true"])))},[JSON.stringify(p)]);const y=async w=>{const C=String(!m[w]);x(_=>({..._,[w]:!_[w]})),await r(w,C)};return a?i.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):i.jsxs("div",{className:"space-y-6",children:[i.jsx(zT,{}),i.jsxs("div",{className:"border-t border-border pt-4",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-2",children:"Scrollbar / Custom CSS"}),i.jsx("p",{className:"text-xs text-text-muted mb-3",children:"Scrollbars are quite finicky, so there is no CSS for them in OpenFox. You can add your own below or select one of the options and see if they match your browser needs."}),i.jsx(UT,{})]}),i.jsxs("div",{className:"border-t border-border pt-4",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),i.jsx("div",{className:"space-y-4",children:h.map(({key:w,label:C,description:_})=>i.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm text-text-primary font-medium",children:C}),i.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:_})]}),i.jsx("button",{type:"button",onClick:()=>y(w),className:`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${m[w]?"bg-accent-primary":"bg-bg-tertiary"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${m[w]?"translate-x-6":"translate-x-1"}`})})]},w))})]}),i.jsx("div",{className:"border-t border-border pt-4",children:i.jsxs("label",{className:"flex items-center justify-between gap-3",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm text-text-primary font-medium",children:"Max visible items"}),i.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:"Keep only the last N items in the feed. Set to 0 to show all."})]}),i.jsx("input",{type:"number",min:0,max:9999,value:u,onChange:w=>{const C=w.target.value.replace(/[^0-9]/g,"");c(C)},onBlur:d,onKeyDown:w=>{w.key==="Enter"&&d()},className:"w-20 px-2 py-1 text-sm text-text-primary bg-bg-tertiary border border-border rounded text-right"})]})})]})}const M_=[{label:"None (browser default)",css:""},{label:"Thin scrollbars",css:["/* Thin scrollbars for Chrome/Safari/Edge */","::-webkit-scrollbar { width: 6px; height: 6px; }","::-webkit-scrollbar-thumb { background: rgba(128,128,128,0.4); border-radius: 3px; }","","/* Thin scrollbars for Firefox */","@-moz-document url-prefix() {"," * { scrollbar-width: thin; }","}"].join(`
60
60
  `)},{label:"Stable gutter (prevent layout shift)",css:["/* Reserve scrollbar space so content does not jump when scrollbar appears */",".scrollbar-stable { scrollbar-gutter: stable; }"].join(`
61
61
  `)},{label:"Balanced gutter (stable + symmetrical)",css:["/* Reserve space on both sides — keeps content centered */","/* Note: Chrome has a bug where both-edges reserves space but the scrollbar"," may not occupy it properly. Test in your browser. */",".scrollbar-stable { scrollbar-gutter: stable both-edges; }"].join(`
@@ -68,7 +68,7 @@ Error generating stack: `+g.message+`
68
68
  }`,className:"w-full h-32 px-3 py-2 text-xs font-mono text-text-primary bg-bg-tertiary border border-border rounded resize-y focus:outline-none focus:ring-2 focus:ring-accent-primary/50 focus:border-accent-primary",spellCheck:!1})]})}function gp(){const[e,t]=N.useState("Test"),[n,r]=N.useState(""),[a,l]=N.useState(!1),u=N.useCallback(async c=>{t("Testing..."),r(""),l(!1);try{const d=await c();d.success?(t("Success"),l(!0),setTimeout(()=>{t("Test"),l(!1)},3e3)):(r(d.error??"Test failed"),t("Test"))}catch{r("Connection error"),t("Test")}},[]);return[e,n,a,u]}function FT(e){try{return new RegExp(e),!0}catch{return!1}}function VT({value:e,onChange:t}){const[n,r]=N.useState({}),a=(d,h)=>{const p=e.patterns.map((m,x)=>x===d?{...m,...h}:m);t({...e,patterns:p})},l=d=>{const h=e.patterns.filter((p,m)=>m!==d);t({...e,patterns:h})},u=()=>{const d={field:"content",pattern:"",action:"retry",active:!0};t({...e,patterns:[...e.patterns,d]})},c=(d,h)=>{r(p=>({...p,[d]:h.length>0&&!FT(h)})),a(d,{pattern:h})};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-sm font-medium text-text-primary",children:"Max Retries Per Turn"}),i.jsx("input",{type:"number",min:1,max:100,value:e.maxRetriesPerTurn,onChange:d=>{const h=parseInt(d.target.value,10),p=isNaN(h)?10:Math.max(1,Math.min(100,h));t({...e,maxRetriesPerTurn:p})},className:"mt-1 block w-24 px-2 py-1 text-sm bg-bg-secondary border border-border rounded"})]}),e.patterns.length===0?i.jsx("p",{className:"text-sm text-text-muted",children:"No retry patterns configured."}):i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"text-left text-text-muted border-b border-border",children:[i.jsx("th",{className:"pb-2 pr-2 w-12",children:"Active"}),i.jsx("th",{className:"pb-2 pr-2",children:"Field"}),i.jsx("th",{className:"pb-2 pr-2",children:"Pattern"}),i.jsx("th",{className:"pb-2 pr-2",children:"Action"}),i.jsx("th",{className:"pb-2 w-8"})]})}),i.jsx("tbody",{children:e.patterns.map((d,h)=>i.jsxs("tr",{className:"border-b border-border",children:[i.jsx("td",{className:"py-2 pr-2",children:i.jsx("input",{type:"checkbox",checked:d.active,onChange:()=>a(h,{active:!d.active}),className:"accent-accent-primary","aria-label":`Toggle pattern ${h+1}`})}),i.jsx("td",{className:"py-2 pr-2",children:i.jsxs("select",{value:d.field,onChange:p=>a(h,{field:p.target.value}),className:"px-2 py-1 bg-bg-secondary border border-border rounded text-sm",children:[i.jsx("option",{value:"content",children:"content"}),i.jsx("option",{value:"thinking",children:"thinking"}),i.jsx("option",{value:"both",children:"both"})]})}),i.jsx("td",{className:"py-2 pr-2",children:i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"text",value:d.pattern,onChange:p=>c(h,p.target.value),placeholder:"regex pattern",className:"flex-1 px-2 py-1 bg-bg-secondary border border-border rounded text-sm font-mono"}),d.pattern.length>0&&i.jsx("span",{className:`text-sm ${n[h]?"text-red-500":"text-green-500"}`,children:n[h]?"✗":"✓"})]})}),i.jsx("td",{className:"py-2 pr-2 text-text-muted",children:"retry"}),i.jsx("td",{className:"py-2",children:i.jsx("button",{onClick:()=>l(h),title:"Remove pattern",className:"text-text-muted hover:text-red-500 transition-colors",children:"×"})})]},h))})]}),i.jsx(Ze,{variant:"secondary",onClick:u,children:"Add Pattern"})]})}function U1({isOpen:e,onClose:t,versionInfo:n}){const[r,a]=N.useState("ready"),[l,u]=N.useState(""),[c,d]=N.useState(n),[h,p]=N.useState(null),[m,x]=N.useState(null);N.useEffect(()=>{!e||n||fetch(ks("/api/auto-update/check")).then(S=>S.json()).then(S=>{d({current:S.current,latest:S.latest})}).catch(()=>{})},[e]),N.useEffect(()=>{if(!e||r!=="updating"&&r!=="restarting")return;const S=setInterval(()=>{u(v=>v.length>=3?"":v+".")},400);return()=>clearInterval(S)},[e,r]);const y=N.useCallback(async()=>{a("updating"),x(null);try{const v=await(await Se("/api/auto-update",{method:"POST"})).json();if(v.success){const b=v.version??"unknown";p(b),localStorage.setItem("openfox_updated_to",b),localStorage.setItem("update_pending","true"),v.isService?(a("restarting"),await Se("/api/auto-update/restart",{method:"POST"}).catch(()=>{}),setTimeout(()=>window.location.reload(),5e3)):a("complete")}else x(v.error??"Update failed"),a("failed")}catch(S){x(S instanceof Error?S.message:"Update request failed"),a("failed")}},[]);N.useEffect(()=>{e&&(a("ready"),u(""),p(null),x(null))},[e]);const w=r!=="updating"&&r!=="restarting",C=S=>S,_=r==="failed"?"Update Failed":r==="complete"||r==="restarting"?"Update Complete":"New OpenFox version available";return i.jsxs(wt,{isOpen:e,onClose:w?t:void 0,title:_,size:"md",closeOnBackdropClick:w,showCloseButton:w,children:[i.jsxs("div",{className:"flex flex-col gap-4",children:[c&&i.jsxs("div",{className:"flex justify-between text-sm",children:[i.jsx("span",{className:"text-text-muted",children:"Current version"}),i.jsx("span",{className:"text-text-primary font-mono",children:C(c.current)})]}),c&&i.jsxs("div",{className:"flex justify-between text-sm pb-2",children:[i.jsx("span",{className:"text-text-muted",children:"Latest version"}),i.jsx("span",{className:"text-accent-primary font-mono font-semibold",children:c.latest})]}),(r==="updating"||r==="restarting")&&i.jsxs("div",{className:"flex flex-col gap-2 mt-2",children:[i.jsx("div",{className:"h-1.5 bg-bg-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full bg-accent-primary animate-pulse w-full"})}),i.jsxs("p",{className:"text-xs text-text-muted text-center",children:[r==="restarting"?"Restarting":"Updating",l]})]}),r==="complete"&&i.jsx("div",{className:"flex flex-col gap-3 mt-2",children:i.jsxs("div",{className:"bg-bg-tertiary rounded px-3 py-2 text-xs text-text-secondary",children:["OpenFox has been updated to v",h??(c==null?void 0:c.latest),"."," Please restart OpenFox to use the new version."]})}),r==="failed"&&i.jsxs("div",{className:"flex flex-col gap-3 mt-2",children:[i.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-accent-danger/10 border border-accent-danger/30 rounded text-xs",children:[i.jsx("span",{children:"⚠️"}),i.jsx("p",{className:"text-text-secondary",children:m})]}),i.jsx("div",{className:"bg-bg-tertiary rounded px-3 py-2 text-xs font-mono text-text-secondary",children:"openfox update"}),i.jsx("p",{className:"text-xs text-text-muted",children:"Run this command in your terminal to complete the update."})]})]}),r==="ready"&&i.jsx("button",{onClick:y,className:"w-full px-3 py-2 text-sm rounded bg-accent-primary hover:brightness-110 transition-all text-white font-medium",children:"Update OpenFox"}),(r==="complete"||r==="failed")&&i.jsx("button",{onClick:t,className:"w-full px-3 py-2 text-sm rounded bg-bg-tertiary hover:bg-bg-secondary transition-colors text-text-primary font-medium mt-2",children:"Close"})]})}function GT(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const WT=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,qT=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,KT={};function P_(e,t){return(KT.jsx?qT:WT).test(e)}const YT=/[ \t\n\f\r]/g;function XT(e){return typeof e=="object"?e.type==="text"?B_(e.value):!1:B_(e)}function B_(e){return e.replace(YT,"")===""}let ql=class{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}};ql.prototype.normal={};ql.prototype.property={};ql.prototype.space=void 0;function F1(e,t){const n={},r={};for(const a of e)Object.assign(n,a.property),Object.assign(r,a.normal);return new ql(n,r,t)}function xp(e){return e.toLowerCase()}let Zn=class{constructor(t,n){this.attribute=n,this.property=t}};Zn.prototype.attribute="";Zn.prototype.booleanish=!1;Zn.prototype.boolean=!1;Zn.prototype.commaOrSpaceSeparated=!1;Zn.prototype.commaSeparated=!1;Zn.prototype.defined=!1;Zn.prototype.mustUseProperty=!1;Zn.prototype.number=!1;Zn.prototype.overloadedBoolean=!1;Zn.prototype.property="";Zn.prototype.spaceSeparated=!1;Zn.prototype.space=void 0;let QT=0;const ct=Ji(),hn=Ji(),yp=Ji(),Pe=Ji(),$t=Ji(),Ja=Ji(),lr=Ji();function Ji(){return 2**++QT}const bp=Object.freeze(Object.defineProperty({__proto__:null,boolean:ct,booleanish:hn,commaOrSpaceSeparated:lr,commaSeparated:Ja,number:Pe,overloadedBoolean:yp,spaceSeparated:$t},Symbol.toStringTag,{value:"Module"})),vm=Object.keys(bp);let lg=class extends Zn{constructor(t,n,r,a){let l=-1;if(super(t,n),$_(this,"space",a),typeof r=="number")for(;++l<vm.length;){const u=vm[l];$_(this,vm[l],(r&bp[u])===bp[u])}}};lg.prototype.defined=!0;function $_(e,t,n){n&&(e[t]=n)}function co(e){const t={},n={};for(const[r,a]of Object.entries(e.properties)){const l=new lg(r,e.transform(e.attributes||{},r),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(l.mustUseProperty=!0),t[r]=l,n[xp(r)]=r,n[xp(l.attribute)]=r}return new ql(t,n,e.space)}const V1=co({properties:{ariaActiveDescendant:null,ariaAtomic:hn,ariaAutoComplete:null,ariaBusy:hn,ariaChecked:hn,ariaColCount:Pe,ariaColIndex:Pe,ariaColSpan:Pe,ariaControls:$t,ariaCurrent:null,ariaDescribedBy:$t,ariaDetails:null,ariaDisabled:hn,ariaDropEffect:$t,ariaErrorMessage:null,ariaExpanded:hn,ariaFlowTo:$t,ariaGrabbed:hn,ariaHasPopup:null,ariaHidden:hn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:$t,ariaLevel:Pe,ariaLive:null,ariaModal:hn,ariaMultiLine:hn,ariaMultiSelectable:hn,ariaOrientation:null,ariaOwns:$t,ariaPlaceholder:null,ariaPosInSet:Pe,ariaPressed:hn,ariaReadOnly:hn,ariaRelevant:null,ariaRequired:hn,ariaRoleDescription:$t,ariaRowCount:Pe,ariaRowIndex:Pe,ariaRowSpan:Pe,ariaSelected:hn,ariaSetSize:Pe,ariaSort:null,ariaValueMax:Pe,ariaValueMin:Pe,ariaValueNow:Pe,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function G1(e,t){return t in e?e[t]:t}function W1(e,t){return G1(e,t.toLowerCase())}const JT=co({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ja,acceptCharset:$t,accessKey:$t,action:null,allow:null,allowFullScreen:ct,allowPaymentRequest:ct,allowUserMedia:ct,alt:null,as:null,async:ct,autoCapitalize:null,autoComplete:$t,autoFocus:ct,autoPlay:ct,blocking:$t,capture:null,charSet:null,checked:ct,cite:null,className:$t,cols:Pe,colSpan:null,content:null,contentEditable:hn,controls:ct,controlsList:$t,coords:Pe|Ja,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ct,defer:ct,dir:null,dirName:null,disabled:ct,download:yp,draggable:hn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ct,formTarget:null,headers:$t,height:Pe,hidden:yp,high:Pe,href:null,hrefLang:null,htmlFor:$t,httpEquiv:$t,id:null,imageSizes:null,imageSrcSet:null,inert:ct,inputMode:null,integrity:null,is:null,isMap:ct,itemId:null,itemProp:$t,itemRef:$t,itemScope:ct,itemType:$t,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ct,low:Pe,manifest:null,max:null,maxLength:Pe,media:null,method:null,min:null,minLength:Pe,multiple:ct,muted:ct,name:null,nonce:null,noModule:ct,noValidate:ct,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ct,optimum:Pe,pattern:null,ping:$t,placeholder:null,playsInline:ct,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ct,referrerPolicy:null,rel:$t,required:ct,reversed:ct,rows:Pe,rowSpan:Pe,sandbox:$t,scope:null,scoped:ct,seamless:ct,selected:ct,shadowRootClonable:ct,shadowRootDelegatesFocus:ct,shadowRootMode:null,shape:null,size:Pe,sizes:null,slot:null,span:Pe,spellCheck:hn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Pe,step:null,style:null,tabIndex:Pe,target:null,title:null,translate:null,type:null,typeMustMatch:ct,useMap:null,value:hn,width:Pe,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:$t,axis:null,background:null,bgColor:null,border:Pe,borderColor:null,bottomMargin:Pe,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ct,declare:ct,event:null,face:null,frame:null,frameBorder:null,hSpace:Pe,leftMargin:Pe,link:null,longDesc:null,lowSrc:null,marginHeight:Pe,marginWidth:Pe,noResize:ct,noHref:ct,noShade:ct,noWrap:ct,object:null,profile:null,prompt:null,rev:null,rightMargin:Pe,rules:null,scheme:null,scrolling:hn,standby:null,summary:null,text:null,topMargin:Pe,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Pe,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ct,disableRemotePlayback:ct,prefix:null,property:null,results:Pe,security:null,unselectable:null},space:"html",transform:W1}),ZT=co({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:lr,accentHeight:Pe,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Pe,amplitude:Pe,arabicForm:null,ascent:Pe,attributeName:null,attributeType:null,azimuth:Pe,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Pe,by:null,calcMode:null,capHeight:Pe,className:$t,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Pe,diffuseConstant:Pe,direction:null,display:null,dur:null,divisor:Pe,dominantBaseline:null,download:ct,dx:null,dy:null,edgeMode:null,editable:null,elevation:Pe,enableBackground:null,end:null,event:null,exponent:Pe,externalResourcesRequired:null,fill:null,fillOpacity:Pe,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Ja,g2:Ja,glyphName:Ja,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Pe,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Pe,horizOriginX:Pe,horizOriginY:Pe,id:null,ideographic:Pe,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Pe,k:Pe,k1:Pe,k2:Pe,k3:Pe,k4:Pe,kernelMatrix:lr,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Pe,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Pe,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Pe,overlineThickness:Pe,paintOrder:null,panose1:null,path:null,pathLength:Pe,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:$t,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Pe,pointsAtY:Pe,pointsAtZ:Pe,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:lr,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:lr,rev:lr,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:lr,requiredFeatures:lr,requiredFonts:lr,requiredFormats:lr,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Pe,specularExponent:Pe,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Pe,strikethroughThickness:Pe,string:null,stroke:null,strokeDashArray:lr,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Pe,strokeOpacity:Pe,strokeWidth:null,style:null,surfaceScale:Pe,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:lr,tabIndex:Pe,tableValues:null,target:null,targetX:Pe,targetY:Pe,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:lr,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Pe,underlineThickness:Pe,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Pe,values:null,vAlphabetic:Pe,vMathematical:Pe,vectorEffect:null,vHanging:Pe,vIdeographic:Pe,version:null,vertAdvY:Pe,vertOriginX:Pe,vertOriginY:Pe,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Pe,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:G1}),q1=co({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),K1=co({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:W1}),Y1=co({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),eA={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},tA=/[A-Z]/g,z_=/-[a-z]/g,nA=/^data[-\w.:]+$/i;function rA(e,t){const n=xp(t);let r=t,a=Zn;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&nA.test(t)){if(t.charAt(4)==="-"){const l=t.slice(5).replace(z_,iA);r="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=t.slice(4);if(!z_.test(l)){let u=l.replace(tA,sA);u.charAt(0)!=="-"&&(u="-"+u),t="data"+u}}a=lg}return new a(r,t)}function sA(e){return"-"+e.toLowerCase()}function iA(e){return e.charAt(1).toUpperCase()}const aA=F1([V1,JT,q1,K1,Y1],"html"),cg=F1([V1,ZT,q1,K1,Y1],"svg");function oA(e){return e.join(" ").trim()}var Ba={},_m,H_;function lA(){if(H_)return _m;H_=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,u=/^[;\s]*/,c=/^\s+|\s+$/g,d=`
69
69
  `,h="/",p="*",m="",x="comment",y="declaration";function w(_,S){if(typeof _!="string")throw new TypeError("First argument must be a string");if(!_)return[];S=S||{};var v=1,b=1;function E(U){var V=U.match(t);V&&(v+=V.length);var G=U.lastIndexOf(d);b=~G?U.length-G:b+U.length}function j(){var U={line:v,column:b};return function(V){return V.position=new T(U),I(),V}}function T(U){this.start=U,this.end={line:v,column:b},this.source=S.source}T.prototype.content=_;function D(U){var V=new Error(S.source+":"+v+":"+b+": "+U);if(V.reason=U,V.filename=S.source,V.line=v,V.column=b,V.source=_,!S.silent)throw V}function L(U){var V=U.exec(_);if(V){var G=V[0];return E(G),_=_.slice(G.length),V}}function I(){L(n)}function P(U){var V;for(U=U||[];V=W();)V!==!1&&U.push(V);return U}function W(){var U=j();if(!(h!=_.charAt(0)||p!=_.charAt(1))){for(var V=2;m!=_.charAt(V)&&(p!=_.charAt(V)||h!=_.charAt(V+1));)++V;if(V+=2,m===_.charAt(V-1))return D("End of comment missing");var G=_.slice(2,V-2);return b+=2,E(G),_=_.slice(V),b+=2,U({type:x,comment:G})}}function H(){var U=j(),V=L(r);if(V){if(W(),!L(a))return D("property missing ':'");var G=L(l),Z=U({type:y,property:C(V[0].replace(e,m)),value:G?C(G[0].replace(e,m)):m});return L(u),Z}}function R(){var U=[];P(U);for(var V;V=H();)V!==!1&&(U.push(V),P(U));return U}return I(),R()}function C(_){return _?_.replace(c,m):m}return _m=w,_m}var U_;function cA(){if(U_)return Ba;U_=1;var e=Ba&&Ba.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ba,"__esModule",{value:!0}),Ba.default=n;const t=e(lA());function n(r,a){let l=null;if(!r||typeof r!="string")return l;const u=(0,t.default)(r),c=typeof a=="function";return u.forEach(d=>{if(d.type!=="declaration")return;const{property:h,value:p}=d;c?a(h,p,d):p&&(l=l||{},l[h]=p)}),l}return Ba}var ul={},F_;function uA(){if(F_)return ul;F_=1,Object.defineProperty(ul,"__esModule",{value:!0}),ul.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,l=function(h){return!h||n.test(h)||e.test(h)},u=function(h,p){return p.toUpperCase()},c=function(h,p){return"".concat(p,"-")},d=function(h,p){return p===void 0&&(p={}),l(h)?h:(h=h.toLowerCase(),p.reactCompat?h=h.replace(a,c):h=h.replace(r,c),h.replace(t,u))};return ul.camelCase=d,ul}var dl,V_;function dA(){if(V_)return dl;V_=1;var e=dl&&dl.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(cA()),n=uA();function r(a,l){var u={};return!a||typeof a!="string"||(0,t.default)(a,function(c,d){c&&d&&(u[(0,n.camelCase)(c,l)]=d)}),u}return r.default=r,dl=r,dl}var hA=dA();const fA=xd(hA),X1=Q1("end"),ug=Q1("start");function Q1(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function mA(e){const t=ug(e),n=X1(e);if(t&&n)return{start:t,end:n}}function Cl(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?G_(e.position):"start"in e||"end"in e?G_(e):"line"in e||"column"in e?vp(e):""}function vp(e){return W_(e&&e.line)+":"+W_(e&&e.column)}function G_(e){return vp(e&&e.start)+"-"+vp(e&&e.end)}function W_(e){return e&&typeof e=="number"?e:1}class Pn extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let a="",l={},u=!1;if(n&&("line"in n&&"column"in n?l={place:n}:"start"in n&&"end"in n?l={place:n}:"type"in n?l={ancestors:[n],place:n.position}:l={...n}),typeof t=="string"?a=t:!l.cause&&t&&(u=!0,a=t.message,l.cause=t),!l.ruleId&&!l.source&&typeof r=="string"){const d=r.indexOf(":");d===-1?l.ruleId=r:(l.source=r.slice(0,d),l.ruleId=r.slice(d+1))}if(!l.place&&l.ancestors&&l.ancestors){const d=l.ancestors[l.ancestors.length-1];d&&(l.place=d.position)}const c=l.place&&"start"in l.place?l.place.start:l.place;this.ancestors=l.ancestors||void 0,this.cause=l.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=c?c.line:void 0,this.name=Cl(l.place)||"1:1",this.place=l.place||void 0,this.reason=this.message,this.ruleId=l.ruleId||void 0,this.source=l.source||void 0,this.stack=u&&l.cause&&typeof l.cause.stack=="string"?l.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Pn.prototype.file="";Pn.prototype.name="";Pn.prototype.reason="";Pn.prototype.message="";Pn.prototype.stack="";Pn.prototype.column=void 0;Pn.prototype.line=void 0;Pn.prototype.ancestors=void 0;Pn.prototype.cause=void 0;Pn.prototype.fatal=void 0;Pn.prototype.place=void 0;Pn.prototype.ruleId=void 0;Pn.prototype.source=void 0;const dg={}.hasOwnProperty,pA=new Map,gA=/[A-Z]/g,xA=new Set(["table","tbody","thead","tfoot","tr"]),yA=new Set(["td","th"]),J1="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function bA(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=jA(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=EA(n,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?cg:aA,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},l=Z1(a,e,void 0);return l&&typeof l!="string"?l:a.create(e,a.Fragment,{children:l||void 0},void 0)}function Z1(e,t,n){if(t.type==="element")return vA(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return _A(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return wA(e,t,n);if(t.type==="mdxjsEsm")return SA(e,t);if(t.type==="root")return CA(e,t,n);if(t.type==="text")return kA(e,t)}function vA(e,t,n){const r=e.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=cg,e.schema=a),e.ancestors.push(t);const l=tw(e,t.tagName,!1),u=NA(e,t);let c=fg(e,t);return xA.has(t.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!XT(d):!0})),ew(e,u,l,t),hg(u,c),e.ancestors.pop(),e.schema=r,e.create(t,l,u,n)}function _A(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Ol(e,t.position)}function SA(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Ol(e,t.position)}function wA(e,t,n){const r=e.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=cg,e.schema=a),e.ancestors.push(t);const l=t.name===null?e.Fragment:tw(e,t.name,!0),u=TA(e,t),c=fg(e,t);return ew(e,u,l,t),hg(u,c),e.ancestors.pop(),e.schema=r,e.create(t,l,u,n)}function CA(e,t,n){const r={};return hg(r,fg(e,t)),e.create(t,e.Fragment,r,n)}function kA(e,t){return t.value}function ew(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function hg(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function EA(e,t,n){return r;function r(a,l,u,c){const h=Array.isArray(u.children)?n:t;return c?h(l,u,c):h(l,u)}}function jA(e,t){return n;function n(r,a,l,u){const c=Array.isArray(l.children),d=ug(r);return t(a,l,u,c,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function NA(e,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&dg.call(t.properties,a)){const l=AA(e,a,t.properties[a]);if(l){const[u,c]=l;e.tableCellAlignToStyle&&u==="align"&&typeof c=="string"&&yA.has(t.tagName)?r=c:n[u]=c}}if(r){const l=n.style||(n.style={});l[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function TA(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const l=r.data.estree.body[0];l.type;const u=l.expression;u.type;const c=u.properties[0];c.type,Object.assign(n,e.evaluater.evaluateExpression(c.argument))}else Ol(e,t.position);else{const a=r.name;let l;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const c=r.value.data.estree.body[0];c.type,l=e.evaluater.evaluateExpression(c.expression)}else Ol(e,t.position);else l=r.value===null?!0:r.value;n[a]=l}return n}function fg(e,t){const n=[];let r=-1;const a=e.passKeys?new Map:pA;for(;++r<t.children.length;){const l=t.children[r];let u;if(e.passKeys){const d=l.type==="element"?l.tagName:l.type==="mdxJsxFlowElement"||l.type==="mdxJsxTextElement"?l.name:void 0;if(d){const h=a.get(d)||0;u=d+"-"+h,a.set(d,h+1)}}const c=Z1(e,l,u);c!==void 0&&n.push(c)}return n}function AA(e,t,n){const r=rA(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?GT(n):oA(n)),r.property==="style"){let a=typeof n=="object"?n:LA(e,String(n));return e.stylePropertyNameCase==="css"&&(a=DA(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&r.space?eA[r.property]||r.property:r.attribute,n]}}function LA(e,t){try{return fA(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,a=new Pn("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=J1+"#cannot-parse-style-attribute",a}}function tw(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let l=-1,u;for(;++l<a.length;){const c=P_(a[l])?{type:"Identifier",name:a[l]}:{type:"Literal",value:a[l]};u=u?{type:"MemberExpression",object:u,property:c,computed:!!(l&&c.type==="Literal"),optional:!1}:c}r=u}else r=P_(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const a=r.value;return dg.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(r);Ol(e)}function Ol(e,t){const n=new Pn("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=J1+"#cannot-handle-mdx-estrees-without-createevaluater",n}function DA(e){const t={};let n;for(n in e)dg.call(e,n)&&(t[RA(n)]=e[n]);return t}function RA(e){let t=e.replace(gA,OA);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function OA(e){return"-"+e.toLowerCase()}const Sm={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},IA={};function mg(e,t){const n=IA,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,a=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return nw(e,r,a)}function nw(e,t,n){if(MA(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return q_(e.children,t,n)}return Array.isArray(e)?q_(e,t,n):""}function q_(e,t,n){const r=[];let a=-1;for(;++a<e.length;)r[a]=nw(e[a],t,n);return r.join("")}function MA(e){return!!(e&&typeof e=="object")}const K_=document.createElement("i");function pg(e){const t="&"+e+";";K_.innerHTML=t;const n=K_.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function ur(e,t,n,r){const a=e.length;let l=0,u;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,n=n>0?n:0,r.length<1e4)u=Array.from(r),u.unshift(t,n),e.splice(...u);else for(n&&e.splice(t,n);l<r.length;)u=r.slice(l,l+1e4),u.unshift(t,0),e.splice(...u),l+=1e4,t+=1e4}function Sr(e,t){return e.length>0?(ur(e,e.length,0,t),e):t}const Y_={}.hasOwnProperty;function rw(e){const t={};let n=-1;for(;++n<e.length;)PA(t,e[n]);return t}function PA(e,t){let n;for(n in t){const a=(Y_.call(e,n)?e[n]:void 0)||(e[n]={}),l=t[n];let u;if(l)for(u in l){Y_.call(a,u)||(a[u]=[]);const c=l[u];BA(a[u],Array.isArray(c)?c:c?[c]:[])}}}function BA(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);ur(e,0,0,r)}function sw(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ir(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Un=fi(/[A-Za-z]/),In=fi(/[\dA-Za-z]/),$A=fi(/[#-'*+\--9=?A-Z^-~]/);function Yu(e){return e!==null&&(e<32||e===127)}const _p=fi(/\d/),zA=fi(/[\dA-Fa-f]/),HA=fi(/[!-/:-@[-`{-~]/);function Je(e){return e!==null&&e<-2}function Bt(e){return e!==null&&(e<0||e===32)}function pt(e){return e===-2||e===-1||e===32}const kd=fi(new RegExp("\\p{P}|\\p{S}","u")),Ki=fi(/\s/);function fi(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function uo(e){const t=[];let n=-1,r=0,a=0;for(;++n<e.length;){const l=e.charCodeAt(n);let u="";if(l===37&&In(e.charCodeAt(n+1))&&In(e.charCodeAt(n+2)))a=2;else if(l<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(l))||(u=String.fromCharCode(l));else if(l>55295&&l<57344){const c=e.charCodeAt(n+1);l<56320&&c>56319&&c<57344?(u=String.fromCharCode(l,c),a=1):u="�"}else u=String.fromCharCode(l);u&&(t.push(e.slice(r,n),encodeURIComponent(u)),r=n+a+1,u=""),a&&(n+=a,a=0)}return t.join("")+e.slice(r)}function St(e,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let l=0;return u;function u(d){return pt(d)?(e.enter(n),c(d)):t(d)}function c(d){return pt(d)&&l++<a?(e.consume(d),c):(e.exit(n),t(d))}}const UA={tokenize:FA};function FA(e){const t=e.attempt(this.parser.constructs.contentInitial,r,a);let n;return t;function r(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),St(e,t,"linePrefix")}function a(c){return e.enter("paragraph"),l(c)}function l(c){const d=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=d),n=d,u(c)}function u(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return Je(c)?(e.consume(c),e.exit("chunkText"),l):(e.consume(c),u)}}const VA={tokenize:GA},X_={tokenize:WA};function GA(e){const t=this,n=[];let r=0,a,l,u;return c;function c(b){if(r<n.length){const E=n[r];return t.containerState=E[1],e.attempt(E[0].continuation,d,h)(b)}return h(b)}function d(b){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&v();const E=t.events.length;let j=E,T;for(;j--;)if(t.events[j][0]==="exit"&&t.events[j][1].type==="chunkFlow"){T=t.events[j][1].end;break}S(r);let D=E;for(;D<t.events.length;)t.events[D][1].end={...T},D++;return ur(t.events,j+1,0,t.events.slice(E)),t.events.length=D,h(b)}return c(b)}function h(b){if(r===n.length){if(!a)return x(b);if(a.currentConstruct&&a.currentConstruct.concrete)return w(b);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(X_,p,m)(b)}function p(b){return a&&v(),S(r),x(b)}function m(b){return t.parser.lazy[t.now().line]=r!==n.length,u=t.now().offset,w(b)}function x(b){return t.containerState={},e.attempt(X_,y,w)(b)}function y(b){return r++,n.push([t.currentConstruct,t.containerState]),x(b)}function w(b){if(b===null){a&&v(),S(0),e.consume(b);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:l}),C(b)}function C(b){if(b===null){_(e.exit("chunkFlow"),!0),S(0),e.consume(b);return}return Je(b)?(e.consume(b),_(e.exit("chunkFlow")),r=0,t.interrupt=void 0,c):(e.consume(b),C)}function _(b,E){const j=t.sliceStream(b);if(E&&j.push(null),b.previous=l,l&&(l.next=b),l=b,a.defineSkip(b.start),a.write(j),t.parser.lazy[b.start.line]){let T=a.events.length;for(;T--;)if(a.events[T][1].start.offset<u&&(!a.events[T][1].end||a.events[T][1].end.offset>u))return;const D=t.events.length;let L=D,I,P;for(;L--;)if(t.events[L][0]==="exit"&&t.events[L][1].type==="chunkFlow"){if(I){P=t.events[L][1].end;break}I=!0}for(S(r),T=D;T<t.events.length;)t.events[T][1].end={...P},T++;ur(t.events,L+1,0,t.events.slice(D)),t.events.length=T}}function S(b){let E=n.length;for(;E-- >b;){const j=n[E];t.containerState=j[1],j[0].exit.call(t,e)}n.length=b}function v(){a.write([null]),l=void 0,a=void 0,t.containerState._closeFlow=void 0}}function WA(e,t,n){return St(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function no(e){if(e===null||Bt(e)||Ki(e))return 1;if(kd(e))return 2}function Ed(e,t,n){const r=[];let a=-1;for(;++a<e.length;){const l=e[a].resolveAll;l&&!r.includes(l)&&(t=l(t,n),r.push(l))}return t}const Sp={name:"attention",resolveAll:qA,tokenize:KA};function qA(e,t){let n=-1,r,a,l,u,c,d,h,p;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;d=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const m={...e[r][1].end},x={...e[n][1].start};Q_(m,-d),Q_(x,d),u={type:d>1?"strongSequence":"emphasisSequence",start:m,end:{...e[r][1].end}},c={type:d>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:x},l={type:d>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},a={type:d>1?"strong":"emphasis",start:{...u.start},end:{...c.end}},e[r][1].end={...u.start},e[n][1].start={...c.end},h=[],e[r][1].end.offset-e[r][1].start.offset&&(h=Sr(h,[["enter",e[r][1],t],["exit",e[r][1],t]])),h=Sr(h,[["enter",a,t],["enter",u,t],["exit",u,t],["enter",l,t]]),h=Sr(h,Ed(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),h=Sr(h,[["exit",l,t],["enter",c,t],["exit",c,t],["exit",a,t]]),e[n][1].end.offset-e[n][1].start.offset?(p=2,h=Sr(h,[["enter",e[n][1],t],["exit",e[n][1],t]])):p=0,ur(e,r-1,n-r+3,h),n=r+h.length-p-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function KA(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,a=no(r);let l;return u;function u(d){return l=d,e.enter("attentionSequence"),c(d)}function c(d){if(d===l)return e.consume(d),c;const h=e.exit("attentionSequence"),p=no(d),m=!p||p===2&&a||n.includes(d),x=!a||a===2&&p||n.includes(r);return h._open=!!(l===42?m:m&&(a||!x)),h._close=!!(l===42?x:x&&(p||!m)),t(d)}}function Q_(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const YA={name:"autolink",tokenize:XA};function XA(e,t,n){let r=0;return a;function a(y){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(y),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),l}function l(y){return Un(y)?(e.consume(y),u):y===64?n(y):h(y)}function u(y){return y===43||y===45||y===46||In(y)?(r=1,c(y)):h(y)}function c(y){return y===58?(e.consume(y),r=0,d):(y===43||y===45||y===46||In(y))&&r++<32?(e.consume(y),c):(r=0,h(y))}function d(y){return y===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(y),e.exit("autolinkMarker"),e.exit("autolink"),t):y===null||y===32||y===60||Yu(y)?n(y):(e.consume(y),d)}function h(y){return y===64?(e.consume(y),p):$A(y)?(e.consume(y),h):n(y)}function p(y){return In(y)?m(y):n(y)}function m(y){return y===46?(e.consume(y),r=0,p):y===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(y),e.exit("autolinkMarker"),e.exit("autolink"),t):x(y)}function x(y){if((y===45||In(y))&&r++<63){const w=y===45?x:m;return e.consume(y),w}return n(y)}}const Kl={partial:!0,tokenize:QA};function QA(e,t,n){return r;function r(l){return pt(l)?St(e,a,"linePrefix")(l):a(l)}function a(l){return l===null||Je(l)?t(l):n(l)}}const iw={continuation:{tokenize:ZA},exit:eL,name:"blockQuote",tokenize:JA};function JA(e,t,n){const r=this;return a;function a(u){if(u===62){const c=r.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(u),e.exit("blockQuoteMarker"),l}return n(u)}function l(u){return pt(u)?(e.enter("blockQuotePrefixWhitespace"),e.consume(u),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(u))}}function ZA(e,t,n){const r=this;return a;function a(u){return pt(u)?St(e,l,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(u):l(u)}function l(u){return e.attempt(iw,t,n)(u)}}function eL(e){e.exit("blockQuote")}const aw={name:"characterEscape",tokenize:tL};function tL(e,t,n){return r;function r(l){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(l),e.exit("escapeMarker"),a}function a(l){return HA(l)?(e.enter("characterEscapeValue"),e.consume(l),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(l)}}const ow={name:"characterReference",tokenize:nL};function nL(e,t,n){const r=this;let a=0,l,u;return c;function c(m){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),d}function d(m){return m===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(m),e.exit("characterReferenceMarkerNumeric"),h):(e.enter("characterReferenceValue"),l=31,u=In,p(m))}function h(m){return m===88||m===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(m),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),l=6,u=zA,p):(e.enter("characterReferenceValue"),l=7,u=_p,p(m))}function p(m){if(m===59&&a){const x=e.exit("characterReferenceValue");return u===In&&!pg(r.sliceSerialize(x))?n(m):(e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return u(m)&&a++<l?(e.consume(m),p):n(m)}}const J_={partial:!0,tokenize:sL},Z_={concrete:!0,name:"codeFenced",tokenize:rL};function rL(e,t,n){const r=this,a={partial:!0,tokenize:j};let l=0,u=0,c;return d;function d(T){return h(T)}function h(T){const D=r.events[r.events.length-1];return l=D&&D[1].type==="linePrefix"?D[2].sliceSerialize(D[1],!0).length:0,c=T,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),p(T)}function p(T){return T===c?(u++,e.consume(T),p):u<3?n(T):(e.exit("codeFencedFenceSequence"),pt(T)?St(e,m,"whitespace")(T):m(T))}function m(T){return T===null||Je(T)?(e.exit("codeFencedFence"),r.interrupt?t(T):e.check(J_,C,E)(T)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),x(T))}function x(T){return T===null||Je(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),m(T)):pt(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),St(e,y,"whitespace")(T)):T===96&&T===c?n(T):(e.consume(T),x)}function y(T){return T===null||Je(T)?m(T):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),w(T))}function w(T){return T===null||Je(T)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),m(T)):T===96&&T===c?n(T):(e.consume(T),w)}function C(T){return e.attempt(a,E,_)(T)}function _(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),S}function S(T){return l>0&&pt(T)?St(e,v,"linePrefix",l+1)(T):v(T)}function v(T){return T===null||Je(T)?e.check(J_,C,E)(T):(e.enter("codeFlowValue"),b(T))}function b(T){return T===null||Je(T)?(e.exit("codeFlowValue"),v(T)):(e.consume(T),b)}function E(T){return e.exit("codeFenced"),t(T)}function j(T,D,L){let I=0;return P;function P(V){return T.enter("lineEnding"),T.consume(V),T.exit("lineEnding"),W}function W(V){return T.enter("codeFencedFence"),pt(V)?St(T,H,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(V):H(V)}function H(V){return V===c?(T.enter("codeFencedFenceSequence"),R(V)):L(V)}function R(V){return V===c?(I++,T.consume(V),R):I>=u?(T.exit("codeFencedFenceSequence"),pt(V)?St(T,U,"whitespace")(V):U(V)):L(V)}function U(V){return V===null||Je(V)?(T.exit("codeFencedFence"),D(V)):L(V)}}}function sL(e,t,n){const r=this;return a;function a(u){return u===null?n(u):(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),l)}function l(u){return r.parser.lazy[r.now().line]?n(u):t(u)}}const wm={name:"codeIndented",tokenize:aL},iL={partial:!0,tokenize:oL};function aL(e,t,n){const r=this;return a;function a(h){return e.enter("codeIndented"),St(e,l,"linePrefix",5)(h)}function l(h){const p=r.events[r.events.length-1];return p&&p[1].type==="linePrefix"&&p[2].sliceSerialize(p[1],!0).length>=4?u(h):n(h)}function u(h){return h===null?d(h):Je(h)?e.attempt(iL,u,d)(h):(e.enter("codeFlowValue"),c(h))}function c(h){return h===null||Je(h)?(e.exit("codeFlowValue"),u(h)):(e.consume(h),c)}function d(h){return e.exit("codeIndented"),t(h)}}function oL(e,t,n){const r=this;return a;function a(u){return r.parser.lazy[r.now().line]?n(u):Je(u)?(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),a):St(e,l,"linePrefix",5)(u)}function l(u){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?t(u):Je(u)?a(u):n(u)}}const lL={name:"codeText",previous:uL,resolve:cL,tokenize:dL};function cL(e){let t=e.length-4,n=3,r,a;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)a===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(a=r):(r===t||e[r][1].type==="lineEnding")&&(e[a][1].type="codeTextData",r!==a+2&&(e[a][1].end=e[r-1][1].end,e.splice(a+2,r-a-2),t-=r-a-2,r=a+2),a=void 0);return e}function uL(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function dL(e,t,n){let r=0,a,l;return u;function u(m){return e.enter("codeText"),e.enter("codeTextSequence"),c(m)}function c(m){return m===96?(e.consume(m),r++,c):(e.exit("codeTextSequence"),d(m))}function d(m){return m===null?n(m):m===32?(e.enter("space"),e.consume(m),e.exit("space"),d):m===96?(l=e.enter("codeTextSequence"),a=0,p(m)):Je(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),d):(e.enter("codeTextData"),h(m))}function h(m){return m===null||m===32||m===96||Je(m)?(e.exit("codeTextData"),d(m)):(e.consume(m),h)}function p(m){return m===96?(e.consume(m),a++,p):a===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(m)):(l.type="codeTextData",h(m))}}class hL{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const a=n||0;this.setCursor(Math.trunc(t));const l=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return r&&hl(this.left,r),l.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),hl(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),hl(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);hl(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);hl(this.left,n.reverse())}}}function hl(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function lw(e){const t={};let n=-1,r,a,l,u,c,d,h;const p=new hL(e);for(;++n<p.length;){for(;n in t;)n=t[n];if(r=p.get(n),n&&r[1].type==="chunkFlow"&&p.get(n-1)[1].type==="listItemPrefix"&&(d=r[1]._tokenizer.events,l=0,l<d.length&&d[l][1].type==="lineEndingBlank"&&(l+=2),l<d.length&&d[l][1].type==="content"))for(;++l<d.length&&d[l][1].type!=="content";)d[l][1].type==="chunkText"&&(d[l][1]._isInFirstContentOfListItem=!0,l++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,fL(p,n)),n=t[n],h=!0);else if(r[1]._container){for(l=n,a=void 0;l--;)if(u=p.get(l),u[1].type==="lineEnding"||u[1].type==="lineEndingBlank")u[0]==="enter"&&(a&&(p.get(a)[1].type="lineEndingBlank"),u[1].type="lineEnding",a=l);else if(!(u[1].type==="linePrefix"||u[1].type==="listItemIndent"))break;a&&(r[1].end={...p.get(a)[1].start},c=p.slice(a,n),c.unshift(r),p.splice(a,n-a+1,c))}}return ur(e,0,Number.POSITIVE_INFINITY,p.slice(0)),!h}function fL(e,t){const n=e.get(t)[1],r=e.get(t)[2];let a=t-1;const l=[];let u=n._tokenizer;u||(u=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(u._contentTypeTextTrailing=!0));const c=u.events,d=[],h={};let p,m,x=-1,y=n,w=0,C=0;const _=[C];for(;y;){for(;e.get(++a)[1]!==y;);l.push(a),y._tokenizer||(p=r.sliceStream(y),y.next||p.push(null),m&&u.defineSkip(y.start),y._isInFirstContentOfListItem&&(u._gfmTasklistFirstContentOfListItem=!0),u.write(p),y._isInFirstContentOfListItem&&(u._gfmTasklistFirstContentOfListItem=void 0)),m=y,y=y.next}for(y=n;++x<c.length;)c[x][0]==="exit"&&c[x-1][0]==="enter"&&c[x][1].type===c[x-1][1].type&&c[x][1].start.line!==c[x][1].end.line&&(C=x+1,_.push(C),y._tokenizer=void 0,y.previous=void 0,y=y.next);for(u.events=[],y?(y._tokenizer=void 0,y.previous=void 0):_.pop(),x=_.length;x--;){const S=c.slice(_[x],_[x+1]),v=l.pop();d.push([v,v+S.length-1]),e.splice(v,2,S)}for(d.reverse(),x=-1;++x<d.length;)h[w+d[x][0]]=w+d[x][1],w+=d[x][1]-d[x][0]-1;return h}const mL={resolve:gL,tokenize:xL},pL={partial:!0,tokenize:yL};function gL(e){return lw(e),e}function xL(e,t){let n;return r;function r(c){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),a(c)}function a(c){return c===null?l(c):Je(c)?e.check(pL,u,l)(c):(e.consume(c),a)}function l(c){return e.exit("chunkContent"),e.exit("content"),t(c)}function u(c){return e.consume(c),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,a}}function yL(e,t,n){const r=this;return a;function a(u){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),St(e,l,"linePrefix")}function l(u){if(u===null||Je(u))return n(u);const c=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?t(u):e.interrupt(r.parser.constructs.flow,n,t)(u)}}function cw(e,t,n,r,a,l,u,c,d){const h=d||Number.POSITIVE_INFINITY;let p=0;return m;function m(S){return S===60?(e.enter(r),e.enter(a),e.enter(l),e.consume(S),e.exit(l),x):S===null||S===32||S===41||Yu(S)?n(S):(e.enter(r),e.enter(u),e.enter(c),e.enter("chunkString",{contentType:"string"}),C(S))}function x(S){return S===62?(e.enter(l),e.consume(S),e.exit(l),e.exit(a),e.exit(r),t):(e.enter(c),e.enter("chunkString",{contentType:"string"}),y(S))}function y(S){return S===62?(e.exit("chunkString"),e.exit(c),x(S)):S===null||S===60||Je(S)?n(S):(e.consume(S),S===92?w:y)}function w(S){return S===60||S===62||S===92?(e.consume(S),y):y(S)}function C(S){return!p&&(S===null||S===41||Bt(S))?(e.exit("chunkString"),e.exit(c),e.exit(u),e.exit(r),t(S)):p<h&&S===40?(e.consume(S),p++,C):S===41?(e.consume(S),p--,C):S===null||S===32||S===40||Yu(S)?n(S):(e.consume(S),S===92?_:C)}function _(S){return S===40||S===41||S===92?(e.consume(S),C):C(S)}}function uw(e,t,n,r,a,l){const u=this;let c=0,d;return h;function h(y){return e.enter(r),e.enter(a),e.consume(y),e.exit(a),e.enter(l),p}function p(y){return c>999||y===null||y===91||y===93&&!d||y===94&&!c&&"_hiddenFootnoteSupport"in u.parser.constructs?n(y):y===93?(e.exit(l),e.enter(a),e.consume(y),e.exit(a),e.exit(r),t):Je(y)?(e.enter("lineEnding"),e.consume(y),e.exit("lineEnding"),p):(e.enter("chunkString",{contentType:"string"}),m(y))}function m(y){return y===null||y===91||y===93||Je(y)||c++>999?(e.exit("chunkString"),p(y)):(e.consume(y),d||(d=!pt(y)),y===92?x:m)}function x(y){return y===91||y===92||y===93?(e.consume(y),c++,m):m(y)}}function dw(e,t,n,r,a,l){let u;return c;function c(x){return x===34||x===39||x===40?(e.enter(r),e.enter(a),e.consume(x),e.exit(a),u=x===40?41:x,d):n(x)}function d(x){return x===u?(e.enter(a),e.consume(x),e.exit(a),e.exit(r),t):(e.enter(l),h(x))}function h(x){return x===u?(e.exit(l),d(u)):x===null?n(x):Je(x)?(e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),St(e,h,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===u||x===null||Je(x)?(e.exit("chunkString"),h(x)):(e.consume(x),x===92?m:p)}function m(x){return x===u||x===92?(e.consume(x),p):p(x)}}function kl(e,t){let n;return r;function r(a){return Je(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),n=!0,r):pt(a)?St(e,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const bL={name:"definition",tokenize:_L},vL={partial:!0,tokenize:SL};function _L(e,t,n){const r=this;let a;return l;function l(y){return e.enter("definition"),u(y)}function u(y){return uw.call(r,e,c,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(y)}function c(y){return a=Ir(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),d):n(y)}function d(y){return Bt(y)?kl(e,h)(y):h(y)}function h(y){return cw(e,p,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(y)}function p(y){return e.attempt(vL,m,m)(y)}function m(y){return pt(y)?St(e,x,"whitespace")(y):x(y)}function x(y){return y===null||Je(y)?(e.exit("definition"),r.parser.defined.push(a),t(y)):n(y)}}function SL(e,t,n){return r;function r(c){return Bt(c)?kl(e,a)(c):n(c)}function a(c){return dw(e,l,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function l(c){return pt(c)?St(e,u,"whitespace")(c):u(c)}function u(c){return c===null||Je(c)?t(c):n(c)}}const wL={name:"hardBreakEscape",tokenize:CL};function CL(e,t,n){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),a}function a(l){return Je(l)?(e.exit("hardBreakEscape"),t(l)):n(l)}}const kL={name:"headingAtx",resolve:EL,tokenize:jL};function EL(e,t){let n=e.length-2,r=3,a,l;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(a={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},l={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},ur(e,r,n-r+1,[["enter",a,t],["enter",l,t],["exit",l,t],["exit",a,t]])),e}function jL(e,t,n){let r=0;return a;function a(p){return e.enter("atxHeading"),l(p)}function l(p){return e.enter("atxHeadingSequence"),u(p)}function u(p){return p===35&&r++<6?(e.consume(p),u):p===null||Bt(p)?(e.exit("atxHeadingSequence"),c(p)):n(p)}function c(p){return p===35?(e.enter("atxHeadingSequence"),d(p)):p===null||Je(p)?(e.exit("atxHeading"),t(p)):pt(p)?St(e,c,"whitespace")(p):(e.enter("atxHeadingText"),h(p))}function d(p){return p===35?(e.consume(p),d):(e.exit("atxHeadingSequence"),c(p))}function h(p){return p===null||p===35||Bt(p)?(e.exit("atxHeadingText"),c(p)):(e.consume(p),h)}}const NL=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],e0=["pre","script","style","textarea"],TL={concrete:!0,name:"htmlFlow",resolveTo:DL,tokenize:RL},AL={partial:!0,tokenize:IL},LL={partial:!0,tokenize:OL};function DL(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function RL(e,t,n){const r=this;let a,l,u,c,d;return h;function h(z){return p(z)}function p(z){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(z),m}function m(z){return z===33?(e.consume(z),x):z===47?(e.consume(z),l=!0,C):z===63?(e.consume(z),a=3,r.interrupt?t:O):Un(z)?(e.consume(z),u=String.fromCharCode(z),_):n(z)}function x(z){return z===45?(e.consume(z),a=2,y):z===91?(e.consume(z),a=5,c=0,w):Un(z)?(e.consume(z),a=4,r.interrupt?t:O):n(z)}function y(z){return z===45?(e.consume(z),r.interrupt?t:O):n(z)}function w(z){const ee="CDATA[";return z===ee.charCodeAt(c++)?(e.consume(z),c===ee.length?r.interrupt?t:H:w):n(z)}function C(z){return Un(z)?(e.consume(z),u=String.fromCharCode(z),_):n(z)}function _(z){if(z===null||z===47||z===62||Bt(z)){const ee=z===47,Q=u.toLowerCase();return!ee&&!l&&e0.includes(Q)?(a=1,r.interrupt?t(z):H(z)):NL.includes(u.toLowerCase())?(a=6,ee?(e.consume(z),S):r.interrupt?t(z):H(z)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(z):l?v(z):b(z))}return z===45||In(z)?(e.consume(z),u+=String.fromCharCode(z),_):n(z)}function S(z){return z===62?(e.consume(z),r.interrupt?t:H):n(z)}function v(z){return pt(z)?(e.consume(z),v):P(z)}function b(z){return z===47?(e.consume(z),P):z===58||z===95||Un(z)?(e.consume(z),E):pt(z)?(e.consume(z),b):P(z)}function E(z){return z===45||z===46||z===58||z===95||In(z)?(e.consume(z),E):j(z)}function j(z){return z===61?(e.consume(z),T):pt(z)?(e.consume(z),j):b(z)}function T(z){return z===null||z===60||z===61||z===62||z===96?n(z):z===34||z===39?(e.consume(z),d=z,D):pt(z)?(e.consume(z),T):L(z)}function D(z){return z===d?(e.consume(z),d=null,I):z===null||Je(z)?n(z):(e.consume(z),D)}function L(z){return z===null||z===34||z===39||z===47||z===60||z===61||z===62||z===96||Bt(z)?j(z):(e.consume(z),L)}function I(z){return z===47||z===62||pt(z)?b(z):n(z)}function P(z){return z===62?(e.consume(z),W):n(z)}function W(z){return z===null||Je(z)?H(z):pt(z)?(e.consume(z),W):n(z)}function H(z){return z===45&&a===2?(e.consume(z),G):z===60&&a===1?(e.consume(z),Z):z===62&&a===4?(e.consume(z),M):z===63&&a===3?(e.consume(z),O):z===93&&a===5?(e.consume(z),$):Je(z)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(AL,q,R)(z)):z===null||Je(z)?(e.exit("htmlFlowData"),R(z)):(e.consume(z),H)}function R(z){return e.check(LL,U,q)(z)}function U(z){return e.enter("lineEnding"),e.consume(z),e.exit("lineEnding"),V}function V(z){return z===null||Je(z)?R(z):(e.enter("htmlFlowData"),H(z))}function G(z){return z===45?(e.consume(z),O):H(z)}function Z(z){return z===47?(e.consume(z),u="",X):H(z)}function X(z){if(z===62){const ee=u.toLowerCase();return e0.includes(ee)?(e.consume(z),M):H(z)}return Un(z)&&u.length<8?(e.consume(z),u+=String.fromCharCode(z),X):H(z)}function $(z){return z===93?(e.consume(z),O):H(z)}function O(z){return z===62?(e.consume(z),M):z===45&&a===2?(e.consume(z),O):H(z)}function M(z){return z===null||Je(z)?(e.exit("htmlFlowData"),q(z)):(e.consume(z),M)}function q(z){return e.exit("htmlFlow"),t(z)}}function OL(e,t,n){const r=this;return a;function a(u){return Je(u)?(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),l):n(u)}function l(u){return r.parser.lazy[r.now().line]?n(u):t(u)}}function IL(e,t,n){return r;function r(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Kl,t,n)}}const ML={name:"htmlText",tokenize:PL};function PL(e,t,n){const r=this;let a,l,u;return c;function c(O){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(O),d}function d(O){return O===33?(e.consume(O),h):O===47?(e.consume(O),j):O===63?(e.consume(O),b):Un(O)?(e.consume(O),L):n(O)}function h(O){return O===45?(e.consume(O),p):O===91?(e.consume(O),l=0,w):Un(O)?(e.consume(O),v):n(O)}function p(O){return O===45?(e.consume(O),y):n(O)}function m(O){return O===null?n(O):O===45?(e.consume(O),x):Je(O)?(u=m,Z(O)):(e.consume(O),m)}function x(O){return O===45?(e.consume(O),y):m(O)}function y(O){return O===62?G(O):O===45?x(O):m(O)}function w(O){const M="CDATA[";return O===M.charCodeAt(l++)?(e.consume(O),l===M.length?C:w):n(O)}function C(O){return O===null?n(O):O===93?(e.consume(O),_):Je(O)?(u=C,Z(O)):(e.consume(O),C)}function _(O){return O===93?(e.consume(O),S):C(O)}function S(O){return O===62?G(O):O===93?(e.consume(O),S):C(O)}function v(O){return O===null||O===62?G(O):Je(O)?(u=v,Z(O)):(e.consume(O),v)}function b(O){return O===null?n(O):O===63?(e.consume(O),E):Je(O)?(u=b,Z(O)):(e.consume(O),b)}function E(O){return O===62?G(O):b(O)}function j(O){return Un(O)?(e.consume(O),T):n(O)}function T(O){return O===45||In(O)?(e.consume(O),T):D(O)}function D(O){return Je(O)?(u=D,Z(O)):pt(O)?(e.consume(O),D):G(O)}function L(O){return O===45||In(O)?(e.consume(O),L):O===47||O===62||Bt(O)?I(O):n(O)}function I(O){return O===47?(e.consume(O),G):O===58||O===95||Un(O)?(e.consume(O),P):Je(O)?(u=I,Z(O)):pt(O)?(e.consume(O),I):G(O)}function P(O){return O===45||O===46||O===58||O===95||In(O)?(e.consume(O),P):W(O)}function W(O){return O===61?(e.consume(O),H):Je(O)?(u=W,Z(O)):pt(O)?(e.consume(O),W):I(O)}function H(O){return O===null||O===60||O===61||O===62||O===96?n(O):O===34||O===39?(e.consume(O),a=O,R):Je(O)?(u=H,Z(O)):pt(O)?(e.consume(O),H):(e.consume(O),U)}function R(O){return O===a?(e.consume(O),a=void 0,V):O===null?n(O):Je(O)?(u=R,Z(O)):(e.consume(O),R)}function U(O){return O===null||O===34||O===39||O===60||O===61||O===96?n(O):O===47||O===62||Bt(O)?I(O):(e.consume(O),U)}function V(O){return O===47||O===62||Bt(O)?I(O):n(O)}function G(O){return O===62?(e.consume(O),e.exit("htmlTextData"),e.exit("htmlText"),t):n(O)}function Z(O){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(O),e.exit("lineEnding"),X}function X(O){return pt(O)?St(e,$,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):$(O)}function $(O){return e.enter("htmlTextData"),u(O)}}const gg={name:"labelEnd",resolveAll:HL,resolveTo:UL,tokenize:FL},BL={tokenize:VL},$L={tokenize:GL},zL={tokenize:WL};function HL(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const a=r.type==="labelImage"?4:2;r.type="data",t+=a}}return e.length!==n.length&&ur(e,0,e.length,n),e}function UL(e,t){let n=e.length,r=0,a,l,u,c;for(;n--;)if(a=e[n][1],l){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[n][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(u){if(e[n][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(l=n,a.type!=="labelLink")){r=2;break}}else a.type==="labelEnd"&&(u=n);const d={type:e[l][1].type==="labelLink"?"link":"image",start:{...e[l][1].start},end:{...e[e.length-1][1].end}},h={type:"label",start:{...e[l][1].start},end:{...e[u][1].end}},p={type:"labelText",start:{...e[l+r+2][1].end},end:{...e[u-2][1].start}};return c=[["enter",d,t],["enter",h,t]],c=Sr(c,e.slice(l+1,l+r+3)),c=Sr(c,[["enter",p,t]]),c=Sr(c,Ed(t.parser.constructs.insideSpan.null,e.slice(l+r+4,u-3),t)),c=Sr(c,[["exit",p,t],e[u-2],e[u-1],["exit",h,t]]),c=Sr(c,e.slice(u+1)),c=Sr(c,[["exit",d,t]]),ur(e,l,e.length,c),e}function FL(e,t,n){const r=this;let a=r.events.length,l,u;for(;a--;)if((r.events[a][1].type==="labelImage"||r.events[a][1].type==="labelLink")&&!r.events[a][1]._balanced){l=r.events[a][1];break}return c;function c(x){return l?l._inactive?m(x):(u=r.parser.defined.includes(Ir(r.sliceSerialize({start:l.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(x),e.exit("labelMarker"),e.exit("labelEnd"),d):n(x)}function d(x){return x===40?e.attempt(BL,p,u?p:m)(x):x===91?e.attempt($L,p,u?h:m)(x):u?p(x):m(x)}function h(x){return e.attempt(zL,p,m)(x)}function p(x){return t(x)}function m(x){return l._balanced=!0,n(x)}}function VL(e,t,n){return r;function r(m){return e.enter("resource"),e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),a}function a(m){return Bt(m)?kl(e,l)(m):l(m)}function l(m){return m===41?p(m):cw(e,u,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(m)}function u(m){return Bt(m)?kl(e,d)(m):p(m)}function c(m){return n(m)}function d(m){return m===34||m===39||m===40?dw(e,h,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(m):p(m)}function h(m){return Bt(m)?kl(e,p)(m):p(m)}function p(m){return m===41?(e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),e.exit("resource"),t):n(m)}}function GL(e,t,n){const r=this;return a;function a(c){return uw.call(r,e,l,u,"reference","referenceMarker","referenceString")(c)}function l(c){return r.parser.defined.includes(Ir(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(c):n(c)}function u(c){return n(c)}}function WL(e,t,n){return r;function r(l){return e.enter("reference"),e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),a}function a(l){return l===93?(e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),e.exit("reference"),t):n(l)}}const qL={name:"labelStartImage",resolveAll:gg.resolveAll,tokenize:KL};function KL(e,t,n){const r=this;return a;function a(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),l}function l(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),u):n(c)}function u(c){return c===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(c):t(c)}}const YL={name:"labelStartLink",resolveAll:gg.resolveAll,tokenize:XL};function XL(e,t,n){const r=this;return a;function a(u){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(u),e.exit("labelMarker"),e.exit("labelLink"),l}function l(u){return u===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(u):t(u)}}const Cm={name:"lineEnding",tokenize:QL};function QL(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),St(e,t,"linePrefix")}}const Uu={name:"thematicBreak",tokenize:JL};function JL(e,t,n){let r=0,a;return l;function l(h){return e.enter("thematicBreak"),u(h)}function u(h){return a=h,c(h)}function c(h){return h===a?(e.enter("thematicBreakSequence"),d(h)):r>=3&&(h===null||Je(h))?(e.exit("thematicBreak"),t(h)):n(h)}function d(h){return h===a?(e.consume(h),r++,d):(e.exit("thematicBreakSequence"),pt(h)?St(e,c,"whitespace")(h):c(h))}}const Xn={continuation:{tokenize:nD},exit:sD,name:"list",tokenize:tD},ZL={partial:!0,tokenize:iD},eD={partial:!0,tokenize:rD};function tD(e,t,n){const r=this,a=r.events[r.events.length-1];let l=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,u=0;return c;function c(y){const w=r.containerState.type||(y===42||y===43||y===45?"listUnordered":"listOrdered");if(w==="listUnordered"?!r.containerState.marker||y===r.containerState.marker:_p(y)){if(r.containerState.type||(r.containerState.type=w,e.enter(w,{_container:!0})),w==="listUnordered")return e.enter("listItemPrefix"),y===42||y===45?e.check(Uu,n,h)(y):h(y);if(!r.interrupt||y===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(y)}return n(y)}function d(y){return _p(y)&&++u<10?(e.consume(y),d):(!r.interrupt||u<2)&&(r.containerState.marker?y===r.containerState.marker:y===41||y===46)?(e.exit("listItemValue"),h(y)):n(y)}function h(y){return e.enter("listItemMarker"),e.consume(y),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||y,e.check(Kl,r.interrupt?n:p,e.attempt(ZL,x,m))}function p(y){return r.containerState.initialBlankLine=!0,l++,x(y)}function m(y){return pt(y)?(e.enter("listItemPrefixWhitespace"),e.consume(y),e.exit("listItemPrefixWhitespace"),x):n(y)}function x(y){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(y)}}function nD(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Kl,a,l);function a(c){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,St(e,t,"listItemIndent",r.containerState.size+1)(c)}function l(c){return r.containerState.furtherBlankLines||!pt(c)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,u(c)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(eD,t,u)(c))}function u(c){return r.containerState._closeFlow=!0,r.interrupt=void 0,St(e,e.attempt(Xn,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function rD(e,t,n){const r=this;return St(e,a,"listItemIndent",r.containerState.size+1);function a(l){const u=r.events[r.events.length-1];return u&&u[1].type==="listItemIndent"&&u[2].sliceSerialize(u[1],!0).length===r.containerState.size?t(l):n(l)}}function sD(e){e.exit(this.containerState.type)}function iD(e,t,n){const r=this;return St(e,a,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(l){const u=r.events[r.events.length-1];return!pt(l)&&u&&u[1].type==="listItemPrefixWhitespace"?t(l):n(l)}}const t0={name:"setextUnderline",resolveTo:aD,tokenize:oD};function aD(e,t){let n=e.length,r,a,l;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(a=n)}else e[n][1].type==="content"&&e.splice(n,1),!l&&e[n][1].type==="definition"&&(l=n);const u={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",l?(e.splice(a,0,["enter",u,t]),e.splice(l+1,0,["exit",e[r][1],t]),e[r][1].end={...e[l][1].end}):e[r][1]=u,e.push(["exit",u,t]),e}function oD(e,t,n){const r=this;let a;return l;function l(h){let p=r.events.length,m;for(;p--;)if(r.events[p][1].type!=="lineEnding"&&r.events[p][1].type!=="linePrefix"&&r.events[p][1].type!=="content"){m=r.events[p][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||m)?(e.enter("setextHeadingLine"),a=h,u(h)):n(h)}function u(h){return e.enter("setextHeadingLineSequence"),c(h)}function c(h){return h===a?(e.consume(h),c):(e.exit("setextHeadingLineSequence"),pt(h)?St(e,d,"lineSuffix")(h):d(h))}function d(h){return h===null||Je(h)?(e.exit("setextHeadingLine"),t(h)):n(h)}}const lD={tokenize:cD};function cD(e){const t=this,n=e.attempt(Kl,r,e.attempt(this.parser.constructs.flowInitial,a,St(e,e.attempt(this.parser.constructs.flow,a,e.attempt(mL,a)),"linePrefix")));return n;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function a(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const uD={resolveAll:fw()},dD=hw("string"),hD=hw("text");function hw(e){return{resolveAll:fw(e==="text"?fD:void 0),tokenize:t};function t(n){const r=this,a=this.parser.constructs[e],l=n.attempt(a,u,c);return u;function u(p){return h(p)?l(p):c(p)}function c(p){if(p===null){n.consume(p);return}return n.enter("data"),n.consume(p),d}function d(p){return h(p)?(n.exit("data"),l(p)):(n.consume(p),d)}function h(p){if(p===null)return!0;const m=a[p];let x=-1;if(m)for(;++x<m.length;){const y=m[x];if(!y.previous||y.previous.call(r,r.previous))return!0}return!1}}}function fw(e){return t;function t(n,r){let a=-1,l;for(;++a<=n.length;)l===void 0?n[a]&&n[a][1].type==="data"&&(l=a,a++):(!n[a]||n[a][1].type!=="data")&&(a!==l+2&&(n[l][1].end=n[a-1][1].end,n.splice(l+2,a-l-2),a=l+2),l=void 0);return e?e(n,r):n}}function fD(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],a=t.sliceStream(r);let l=a.length,u=-1,c=0,d;for(;l--;){const h=a[l];if(typeof h=="string"){for(u=h.length;h.charCodeAt(u-1)===32;)c++,u--;if(u)break;u=-1}else if(h===-2)d=!0,c++;else if(h!==-1){l++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(c=0),c){const h={type:n===e.length||d||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:l?u:r.start._bufferIndex+u,_index:r.start._index+l,line:r.end.line,column:r.end.column-c,offset:r.end.offset-c},end:{...r.end}};r.end={...h.start},r.start.offset===r.end.offset?Object.assign(r,h):(e.splice(n,0,["enter",h,t],["exit",h,t]),n+=2)}n++}return e}const mD={42:Xn,43:Xn,45:Xn,48:Xn,49:Xn,50:Xn,51:Xn,52:Xn,53:Xn,54:Xn,55:Xn,56:Xn,57:Xn,62:iw},pD={91:bL},gD={[-2]:wm,[-1]:wm,32:wm},xD={35:kL,42:Uu,45:[t0,Uu],60:TL,61:t0,95:Uu,96:Z_,126:Z_},yD={38:ow,92:aw},bD={[-5]:Cm,[-4]:Cm,[-3]:Cm,33:qL,38:ow,42:Sp,60:[YA,ML],91:YL,92:[wL,aw],93:gg,95:Sp,96:lL},vD={null:[Sp,uD]},_D={null:[42,95]},SD={null:[]},wD=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:_D,contentInitial:pD,disable:SD,document:mD,flow:xD,flowInitial:gD,insideSpan:vD,string:yD,text:bD},Symbol.toStringTag,{value:"Module"}));function CD(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const a={},l=[];let u=[],c=[];const d={attempt:D(j),check:D(T),consume:v,enter:b,exit:E,interrupt:D(T,{interrupt:!0})},h={code:null,containerState:{},defineSkip:C,events:[],now:w,parser:e,previous:null,sliceSerialize:x,sliceStream:y,write:m};let p=t.tokenize.call(h,d);return t.resolveAll&&l.push(t),h;function m(W){return u=Sr(u,W),_(),u[u.length-1]!==null?[]:(L(t,0),h.events=Ed(l,h.events,h),h.events)}function x(W,H){return ED(y(W),H)}function y(W){return kD(u,W)}function w(){const{_bufferIndex:W,_index:H,line:R,column:U,offset:V}=r;return{_bufferIndex:W,_index:H,line:R,column:U,offset:V}}function C(W){a[W.line]=W.column,P()}function _(){let W;for(;r._index<u.length;){const H=u[r._index];if(typeof H=="string")for(W=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===W&&r._bufferIndex<H.length;)S(H.charCodeAt(r._bufferIndex));else S(H)}}function S(W){p=p(W)}function v(W){Je(W)?(r.line++,r.column=1,r.offset+=W===-3?2:1,P()):W!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===u[r._index].length&&(r._bufferIndex=-1,r._index++)),h.previous=W}function b(W,H){const R=H||{};return R.type=W,R.start=w(),h.events.push(["enter",R,h]),c.push(R),R}function E(W){const H=c.pop();return H.end=w(),h.events.push(["exit",H,h]),H}function j(W,H){L(W,H.from)}function T(W,H){H.restore()}function D(W,H){return R;function R(U,V,G){let Z,X,$,O;return Array.isArray(U)?q(U):"tokenize"in U?q([U]):M(U);function M(ne){return K;function K(B){const te=B!==null&&ne[B],se=B!==null&&ne.null,xe=[...Array.isArray(te)?te:te?[te]:[],...Array.isArray(se)?se:se?[se]:[]];return q(xe)(B)}}function q(ne){return Z=ne,X=0,ne.length===0?G:z(ne[X])}function z(ne){return K;function K(B){return O=I(),$=ne,ne.partial||(h.currentConstruct=ne),ne.name&&h.parser.constructs.disable.null.includes(ne.name)?Q():ne.tokenize.call(H?Object.assign(Object.create(h),H):h,d,ee,Q)(B)}}function ee(ne){return W($,O),V}function Q(ne){return O.restore(),++X<Z.length?z(Z[X]):G}}}function L(W,H){W.resolveAll&&!l.includes(W)&&l.push(W),W.resolve&&ur(h.events,H,h.events.length-H,W.resolve(h.events.slice(H),h)),W.resolveTo&&(h.events=W.resolveTo(h.events,h))}function I(){const W=w(),H=h.previous,R=h.currentConstruct,U=h.events.length,V=Array.from(c);return{from:U,restore:G};function G(){r=W,h.previous=H,h.currentConstruct=R,h.events.length=U,c=V,P()}}function P(){r.line in a&&r.column<2&&(r.column=a[r.line],r.offset+=a[r.line]-1)}}function kD(e,t){const n=t.start._index,r=t.start._bufferIndex,a=t.end._index,l=t.end._bufferIndex;let u;if(n===a)u=[e[n].slice(r,l)];else{if(u=e.slice(n,a),r>-1){const c=u[0];typeof c=="string"?u[0]=c.slice(r):u.shift()}l>0&&u.push(e[a].slice(0,l))}return u}function ED(e,t){let n=-1;const r=[];let a;for(;++n<e.length;){const l=e[n];let u;if(typeof l=="string")u=l;else switch(l){case-5:{u="\r";break}case-4:{u=`
70
70
  `;break}case-3:{u=`\r
71
- `;break}case-2:{u=t?" ":" ";break}case-1:{if(!t&&a)continue;u=" ";break}default:u=String.fromCharCode(l)}a=l===-2,r.push(u)}return r.join("")}function jD(e){const r={constructs:rw([wD,...(e||{}).extensions||[]]),content:a(UA),defined:[],document:a(VA),flow:a(lD),lazy:{},string:a(dD),text:a(hD)};return r;function a(l){return u;function u(c){return CD(r,l,c)}}}function ND(e){for(;!lw(e););return e}const n0=/[\0\t\n\r]/g;function TD(){let e=1,t="",n=!0,r;return a;function a(l,u,c){const d=[];let h,p,m,x,y;for(l=t+(typeof l=="string"?l.toString():new TextDecoder(u||void 0).decode(l)),m=0,t="",n&&(l.charCodeAt(0)===65279&&m++,n=void 0);m<l.length;){if(n0.lastIndex=m,h=n0.exec(l),x=h&&h.index!==void 0?h.index:l.length,y=l.charCodeAt(x),!h){t=l.slice(m);break}if(y===10&&m===x&&r)d.push(-3),r=void 0;else switch(r&&(d.push(-5),r=void 0),m<x&&(d.push(l.slice(m,x)),e+=x-m),y){case 0:{d.push(65533),e++;break}case 9:{for(p=Math.ceil(e/4)*4,d.push(-2);e++<p;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:r=!0,e=1}m=x+1}return c&&(r&&d.push(-5),t&&d.push(t),d.push(null)),d}}const AD=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function LD(e){return e.replace(AD,DD)}function DD(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const a=n.charCodeAt(1),l=a===120||a===88;return sw(n.slice(l?2:1),l?16:10)}return pg(n)||e}const mw={}.hasOwnProperty;function RD(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),OD(n)(ND(jD(n).document().write(TD()(e,t,!0))))}function OD(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(Qe),autolinkProtocol:I,autolinkEmail:I,atxHeading:l(ze),blockQuote:l(se),characterEscape:I,characterReference:I,codeFenced:l(xe),codeFencedFenceInfo:u,codeFencedFenceMeta:u,codeIndented:l(xe,u),codeText:l(oe,u),codeTextData:I,data:I,codeFlowValue:I,definition:l(Oe),definitionDestinationString:u,definitionLabelString:u,definitionTitleString:u,emphasis:l(Me),hardBreakEscape:l($e),hardBreakTrailing:l($e),htmlFlow:l(je,u),htmlFlowData:I,htmlText:l(je,u),htmlTextData:I,image:l(rt),label:u,link:l(Qe),listItem:l(ce),listItemValue:x,listOrdered:l(fe,m),listUnordered:l(fe),paragraph:l(de),reference:z,referenceString:u,resourceDestinationString:u,resourceTitleString:u,setextHeading:l(ze),strong:l(he),thematicBreak:l(Ue)},exit:{atxHeading:d(),atxHeadingSequence:j,autolink:d(),autolinkEmail:te,autolinkProtocol:B,blockQuote:d(),characterEscapeValue:P,characterReferenceMarkerHexadecimal:Q,characterReferenceMarkerNumeric:Q,characterReferenceValue:ne,characterReference:K,codeFenced:d(_),codeFencedFence:C,codeFencedFenceInfo:y,codeFencedFenceMeta:w,codeFlowValue:P,codeIndented:d(S),codeText:d(V),codeTextData:P,data:P,definition:d(),definitionDestinationString:E,definitionLabelString:v,definitionTitleString:b,emphasis:d(),hardBreakEscape:d(H),hardBreakTrailing:d(H),htmlFlow:d(R),htmlFlowData:P,htmlText:d(U),htmlTextData:P,image:d(Z),label:$,labelText:X,lineEnding:W,link:d(G),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:ee,resourceDestinationString:O,resourceTitleString:M,resource:q,setextHeading:d(L),setextHeadingLineSequence:D,setextHeadingText:T,strong:d(),thematicBreak:d()}};pw(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(re){let _e={type:"root",children:[]};const Le={stack:[_e],tokenStack:[],config:t,enter:c,exit:h,buffer:u,resume:p,data:n},He=[];let qe=-1;for(;++qe<re.length;)if(re[qe][1].type==="listOrdered"||re[qe][1].type==="listUnordered")if(re[qe][0]==="enter")He.push(qe);else{const Ke=He.pop();qe=a(re,Ke,qe)}for(qe=-1;++qe<re.length;){const Ke=t[re[qe][0]];mw.call(Ke,re[qe][1].type)&&Ke[re[qe][1].type].call(Object.assign({sliceSerialize:re[qe][2].sliceSerialize},Le),re[qe][1])}if(Le.tokenStack.length>0){const Ke=Le.tokenStack[Le.tokenStack.length-1];(Ke[1]||r0).call(Le,void 0,Ke[0])}for(_e.position={start:Js(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:Js(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},qe=-1;++qe<t.transforms.length;)_e=t.transforms[qe](_e)||_e;return _e}function a(re,_e,Le){let He=_e-1,qe=-1,Ke=!1,tt,_t,It,Kt;for(;++He<=Le;){const dt=re[He];switch(dt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{dt[0]==="enter"?qe++:qe--,Kt=void 0;break}case"lineEndingBlank":{dt[0]==="enter"&&(tt&&!Kt&&!qe&&!It&&(It=He),Kt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Kt=void 0}if(!qe&&dt[0]==="enter"&&dt[1].type==="listItemPrefix"||qe===-1&&dt[0]==="exit"&&(dt[1].type==="listUnordered"||dt[1].type==="listOrdered")){if(tt){let kn=He;for(_t=void 0;kn--;){const jt=re[kn];if(jt[1].type==="lineEnding"||jt[1].type==="lineEndingBlank"){if(jt[0]==="exit")continue;_t&&(re[_t][1].type="lineEndingBlank",Ke=!0),jt[1].type="lineEnding",_t=kn}else if(!(jt[1].type==="linePrefix"||jt[1].type==="blockQuotePrefix"||jt[1].type==="blockQuotePrefixWhitespace"||jt[1].type==="blockQuoteMarker"||jt[1].type==="listItemIndent"))break}It&&(!_t||It<_t)&&(tt._spread=!0),tt.end=Object.assign({},_t?re[_t][1].start:dt[1].end),re.splice(_t||He,0,["exit",tt,dt[2]]),He++,Le++}if(dt[1].type==="listItemPrefix"){const kn={type:"listItem",_spread:!1,start:Object.assign({},dt[1].start),end:void 0};tt=kn,re.splice(He,0,["enter",kn,dt[2]]),He++,Le++,It=void 0,Kt=!0}}}return re[_e][1]._spread=Ke,Le}function l(re,_e){return Le;function Le(He){c.call(this,re(He),He),_e&&_e.call(this,He)}}function u(){this.stack.push({type:"fragment",children:[]})}function c(re,_e,Le){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([_e,Le||void 0]),re.position={start:Js(_e.start),end:void 0}}function d(re){return _e;function _e(Le){re&&re.call(this,Le),h.call(this,Le)}}function h(re,_e){const Le=this.stack.pop(),He=this.tokenStack.pop();if(He)He[0].type!==re.type&&(_e?_e.call(this,re,He[0]):(He[1]||r0).call(this,re,He[0]));else throw new Error("Cannot close `"+re.type+"` ("+Cl({start:re.start,end:re.end})+"): it’s not open");Le.position.end=Js(re.end)}function p(){return mg(this.stack.pop())}function m(){this.data.expectingFirstListItemValue=!0}function x(re){if(this.data.expectingFirstListItemValue){const _e=this.stack[this.stack.length-2];_e.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function y(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.lang=re}function w(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.meta=re}function C(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function _(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function S(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re.replace(/(\r?\n|\r)$/g,"")}function v(re){const _e=this.resume(),Le=this.stack[this.stack.length-1];Le.label=_e,Le.identifier=Ir(this.sliceSerialize(re)).toLowerCase()}function b(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.title=re}function E(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.url=re}function j(re){const _e=this.stack[this.stack.length-1];if(!_e.depth){const Le=this.sliceSerialize(re).length;_e.depth=Le}}function T(){this.data.setextHeadingSlurpLineEnding=!0}function D(re){const _e=this.stack[this.stack.length-1];_e.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function L(){this.data.setextHeadingSlurpLineEnding=void 0}function I(re){const Le=this.stack[this.stack.length-1].children;let He=Le[Le.length-1];(!He||He.type!=="text")&&(He=De(),He.position={start:Js(re.start),end:void 0},Le.push(He)),this.stack.push(He)}function P(re){const _e=this.stack.pop();_e.value+=this.sliceSerialize(re),_e.position.end=Js(re.end)}function W(re){const _e=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Le=_e.children[_e.children.length-1];Le.position.end=Js(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(_e.type)&&(I.call(this,re),P.call(this,re))}function H(){this.data.atHardBreak=!0}function R(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re}function U(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re}function V(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re}function G(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const _e=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=_e,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function Z(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const _e=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=_e,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function X(re){const _e=this.sliceSerialize(re),Le=this.stack[this.stack.length-2];Le.label=LD(_e),Le.identifier=Ir(_e).toLowerCase()}function $(){const re=this.stack[this.stack.length-1],_e=this.resume(),Le=this.stack[this.stack.length-1];if(this.data.inReference=!0,Le.type==="link"){const He=re.children;Le.children=He}else Le.alt=_e}function O(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.url=re}function M(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.title=re}function q(){this.data.inReference=void 0}function z(){this.data.referenceType="collapsed"}function ee(re){const _e=this.resume(),Le=this.stack[this.stack.length-1];Le.label=_e,Le.identifier=Ir(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function Q(re){this.data.characterReferenceType=re.type}function ne(re){const _e=this.sliceSerialize(re),Le=this.data.characterReferenceType;let He;Le?(He=sw(_e,Le==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):He=pg(_e);const qe=this.stack[this.stack.length-1];qe.value+=He}function K(re){const _e=this.stack.pop();_e.position.end=Js(re.end)}function B(re){P.call(this,re);const _e=this.stack[this.stack.length-1];_e.url=this.sliceSerialize(re)}function te(re){P.call(this,re);const _e=this.stack[this.stack.length-1];_e.url="mailto:"+this.sliceSerialize(re)}function se(){return{type:"blockquote",children:[]}}function xe(){return{type:"code",lang:null,meta:null,value:""}}function oe(){return{type:"inlineCode",value:""}}function Oe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Me(){return{type:"emphasis",children:[]}}function ze(){return{type:"heading",depth:0,children:[]}}function $e(){return{type:"break"}}function je(){return{type:"html",value:""}}function rt(){return{type:"image",title:null,url:"",alt:null}}function Qe(){return{type:"link",title:null,url:"",children:[]}}function fe(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function ce(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function de(){return{type:"paragraph",children:[]}}function he(){return{type:"strong",children:[]}}function De(){return{type:"text",value:""}}function Ue(){return{type:"thematicBreak"}}}function Js(e){return{line:e.line,column:e.column,offset:e.offset}}function pw(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?pw(e,r):ID(e,r)}}function ID(e,t){let n;for(n in t)if(mw.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function r0(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Cl({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Cl({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Cl({start:t.start,end:t.end})+") is still open")}function MD(e){const t=this;t.parser=n;function n(r){return RD(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function PD(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function BD(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
71
+ `;break}case-2:{u=t?" ":" ";break}case-1:{if(!t&&a)continue;u=" ";break}default:u=String.fromCharCode(l)}a=l===-2,r.push(u)}return r.join("")}function jD(e){const r={constructs:rw([wD,...(e||{}).extensions||[]]),content:a(UA),defined:[],document:a(VA),flow:a(lD),lazy:{},string:a(dD),text:a(hD)};return r;function a(l){return u;function u(c){return CD(r,l,c)}}}function ND(e){for(;!lw(e););return e}const n0=/[\0\t\n\r]/g;function TD(){let e=1,t="",n=!0,r;return a;function a(l,u,c){const d=[];let h,p,m,x,y;for(l=t+(typeof l=="string"?l.toString():new TextDecoder(u||void 0).decode(l)),m=0,t="",n&&(l.charCodeAt(0)===65279&&m++,n=void 0);m<l.length;){if(n0.lastIndex=m,h=n0.exec(l),x=h&&h.index!==void 0?h.index:l.length,y=l.charCodeAt(x),!h){t=l.slice(m);break}if(y===10&&m===x&&r)d.push(-3),r=void 0;else switch(r&&(d.push(-5),r=void 0),m<x&&(d.push(l.slice(m,x)),e+=x-m),y){case 0:{d.push(65533),e++;break}case 9:{for(p=Math.ceil(e/4)*4,d.push(-2);e++<p;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:r=!0,e=1}m=x+1}return c&&(r&&d.push(-5),t&&d.push(t),d.push(null)),d}}const AD=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function LD(e){return e.replace(AD,DD)}function DD(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const a=n.charCodeAt(1),l=a===120||a===88;return sw(n.slice(l?2:1),l?16:10)}return pg(n)||e}const mw={}.hasOwnProperty;function RD(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),OD(n)(ND(jD(n).document().write(TD()(e,t,!0))))}function OD(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(Qe),autolinkProtocol:I,autolinkEmail:I,atxHeading:l(ze),blockQuote:l(se),characterEscape:I,characterReference:I,codeFenced:l(xe),codeFencedFenceInfo:u,codeFencedFenceMeta:u,codeIndented:l(xe,u),codeText:l(oe,u),codeTextData:I,data:I,codeFlowValue:I,definition:l(Oe),definitionDestinationString:u,definitionLabelString:u,definitionTitleString:u,emphasis:l(Me),hardBreakEscape:l($e),hardBreakTrailing:l($e),htmlFlow:l(je,u),htmlFlowData:I,htmlText:l(je,u),htmlTextData:I,image:l(rt),label:u,link:l(Qe),listItem:l(ce),listItemValue:x,listOrdered:l(fe,m),listUnordered:l(fe),paragraph:l(de),reference:z,referenceString:u,resourceDestinationString:u,resourceTitleString:u,setextHeading:l(ze),strong:l(he),thematicBreak:l(Ue)},exit:{atxHeading:d(),atxHeadingSequence:j,autolink:d(),autolinkEmail:te,autolinkProtocol:B,blockQuote:d(),characterEscapeValue:P,characterReferenceMarkerHexadecimal:Q,characterReferenceMarkerNumeric:Q,characterReferenceValue:ne,characterReference:K,codeFenced:d(_),codeFencedFence:C,codeFencedFenceInfo:y,codeFencedFenceMeta:w,codeFlowValue:P,codeIndented:d(S),codeText:d(V),codeTextData:P,data:P,definition:d(),definitionDestinationString:E,definitionLabelString:v,definitionTitleString:b,emphasis:d(),hardBreakEscape:d(H),hardBreakTrailing:d(H),htmlFlow:d(R),htmlFlowData:P,htmlText:d(U),htmlTextData:P,image:d(Z),label:$,labelText:X,lineEnding:W,link:d(G),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:ee,resourceDestinationString:O,resourceTitleString:M,resource:q,setextHeading:d(L),setextHeadingLineSequence:D,setextHeadingText:T,strong:d(),thematicBreak:d()}};pw(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(re){let _e={type:"root",children:[]};const Le={stack:[_e],tokenStack:[],config:t,enter:c,exit:h,buffer:u,resume:p,data:n},He=[];let qe=-1;for(;++qe<re.length;)if(re[qe][1].type==="listOrdered"||re[qe][1].type==="listUnordered")if(re[qe][0]==="enter")He.push(qe);else{const Ke=He.pop();qe=a(re,Ke,qe)}for(qe=-1;++qe<re.length;){const Ke=t[re[qe][0]];mw.call(Ke,re[qe][1].type)&&Ke[re[qe][1].type].call(Object.assign({sliceSerialize:re[qe][2].sliceSerialize},Le),re[qe][1])}if(Le.tokenStack.length>0){const Ke=Le.tokenStack[Le.tokenStack.length-1];(Ke[1]||r0).call(Le,void 0,Ke[0])}for(_e.position={start:Js(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:Js(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},qe=-1;++qe<t.transforms.length;)_e=t.transforms[qe](_e)||_e;return _e}function a(re,_e,Le){let He=_e-1,qe=-1,Ke=!1,tt,_t,It,Yt;for(;++He<=Le;){const dt=re[He];switch(dt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{dt[0]==="enter"?qe++:qe--,Yt=void 0;break}case"lineEndingBlank":{dt[0]==="enter"&&(tt&&!Yt&&!qe&&!It&&(It=He),Yt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Yt=void 0}if(!qe&&dt[0]==="enter"&&dt[1].type==="listItemPrefix"||qe===-1&&dt[0]==="exit"&&(dt[1].type==="listUnordered"||dt[1].type==="listOrdered")){if(tt){let kn=He;for(_t=void 0;kn--;){const jt=re[kn];if(jt[1].type==="lineEnding"||jt[1].type==="lineEndingBlank"){if(jt[0]==="exit")continue;_t&&(re[_t][1].type="lineEndingBlank",Ke=!0),jt[1].type="lineEnding",_t=kn}else if(!(jt[1].type==="linePrefix"||jt[1].type==="blockQuotePrefix"||jt[1].type==="blockQuotePrefixWhitespace"||jt[1].type==="blockQuoteMarker"||jt[1].type==="listItemIndent"))break}It&&(!_t||It<_t)&&(tt._spread=!0),tt.end=Object.assign({},_t?re[_t][1].start:dt[1].end),re.splice(_t||He,0,["exit",tt,dt[2]]),He++,Le++}if(dt[1].type==="listItemPrefix"){const kn={type:"listItem",_spread:!1,start:Object.assign({},dt[1].start),end:void 0};tt=kn,re.splice(He,0,["enter",kn,dt[2]]),He++,Le++,It=void 0,Yt=!0}}}return re[_e][1]._spread=Ke,Le}function l(re,_e){return Le;function Le(He){c.call(this,re(He),He),_e&&_e.call(this,He)}}function u(){this.stack.push({type:"fragment",children:[]})}function c(re,_e,Le){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([_e,Le||void 0]),re.position={start:Js(_e.start),end:void 0}}function d(re){return _e;function _e(Le){re&&re.call(this,Le),h.call(this,Le)}}function h(re,_e){const Le=this.stack.pop(),He=this.tokenStack.pop();if(He)He[0].type!==re.type&&(_e?_e.call(this,re,He[0]):(He[1]||r0).call(this,re,He[0]));else throw new Error("Cannot close `"+re.type+"` ("+Cl({start:re.start,end:re.end})+"): it’s not open");Le.position.end=Js(re.end)}function p(){return mg(this.stack.pop())}function m(){this.data.expectingFirstListItemValue=!0}function x(re){if(this.data.expectingFirstListItemValue){const _e=this.stack[this.stack.length-2];_e.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function y(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.lang=re}function w(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.meta=re}function C(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function _(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function S(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re.replace(/(\r?\n|\r)$/g,"")}function v(re){const _e=this.resume(),Le=this.stack[this.stack.length-1];Le.label=_e,Le.identifier=Ir(this.sliceSerialize(re)).toLowerCase()}function b(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.title=re}function E(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.url=re}function j(re){const _e=this.stack[this.stack.length-1];if(!_e.depth){const Le=this.sliceSerialize(re).length;_e.depth=Le}}function T(){this.data.setextHeadingSlurpLineEnding=!0}function D(re){const _e=this.stack[this.stack.length-1];_e.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function L(){this.data.setextHeadingSlurpLineEnding=void 0}function I(re){const Le=this.stack[this.stack.length-1].children;let He=Le[Le.length-1];(!He||He.type!=="text")&&(He=De(),He.position={start:Js(re.start),end:void 0},Le.push(He)),this.stack.push(He)}function P(re){const _e=this.stack.pop();_e.value+=this.sliceSerialize(re),_e.position.end=Js(re.end)}function W(re){const _e=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Le=_e.children[_e.children.length-1];Le.position.end=Js(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(_e.type)&&(I.call(this,re),P.call(this,re))}function H(){this.data.atHardBreak=!0}function R(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re}function U(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re}function V(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.value=re}function G(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const _e=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=_e,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function Z(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const _e=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=_e,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function X(re){const _e=this.sliceSerialize(re),Le=this.stack[this.stack.length-2];Le.label=LD(_e),Le.identifier=Ir(_e).toLowerCase()}function $(){const re=this.stack[this.stack.length-1],_e=this.resume(),Le=this.stack[this.stack.length-1];if(this.data.inReference=!0,Le.type==="link"){const He=re.children;Le.children=He}else Le.alt=_e}function O(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.url=re}function M(){const re=this.resume(),_e=this.stack[this.stack.length-1];_e.title=re}function q(){this.data.inReference=void 0}function z(){this.data.referenceType="collapsed"}function ee(re){const _e=this.resume(),Le=this.stack[this.stack.length-1];Le.label=_e,Le.identifier=Ir(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function Q(re){this.data.characterReferenceType=re.type}function ne(re){const _e=this.sliceSerialize(re),Le=this.data.characterReferenceType;let He;Le?(He=sw(_e,Le==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):He=pg(_e);const qe=this.stack[this.stack.length-1];qe.value+=He}function K(re){const _e=this.stack.pop();_e.position.end=Js(re.end)}function B(re){P.call(this,re);const _e=this.stack[this.stack.length-1];_e.url=this.sliceSerialize(re)}function te(re){P.call(this,re);const _e=this.stack[this.stack.length-1];_e.url="mailto:"+this.sliceSerialize(re)}function se(){return{type:"blockquote",children:[]}}function xe(){return{type:"code",lang:null,meta:null,value:""}}function oe(){return{type:"inlineCode",value:""}}function Oe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Me(){return{type:"emphasis",children:[]}}function ze(){return{type:"heading",depth:0,children:[]}}function $e(){return{type:"break"}}function je(){return{type:"html",value:""}}function rt(){return{type:"image",title:null,url:"",alt:null}}function Qe(){return{type:"link",title:null,url:"",children:[]}}function fe(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function ce(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function de(){return{type:"paragraph",children:[]}}function he(){return{type:"strong",children:[]}}function De(){return{type:"text",value:""}}function Ue(){return{type:"thematicBreak"}}}function Js(e){return{line:e.line,column:e.column,offset:e.offset}}function pw(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?pw(e,r):ID(e,r)}}function ID(e,t){let n;for(n in t)if(mw.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function r0(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Cl({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Cl({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Cl({start:t.start,end:t.end})+") is still open")}function MD(e){const t=this;t.parser=n;function n(r){return RD(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function PD(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function BD(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
72
72
  `}]}function $D(e,t){const n=t.value?t.value+`
73
73
  `:"",r={},a=t.lang?t.lang.split(/\s+/):[];a.length>0&&(r.className=["language-"+a[0]]);let l={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(l.data={meta:t.meta}),e.patch(t,l),l=e.applyData(t,l),l={type:"element",tagName:"pre",properties:{},children:[l]},e.patch(t,l),l}function zD(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function HD(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function UD(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=uo(r.toLowerCase()),l=e.footnoteOrder.indexOf(r);let u,c=e.footnoteCounts.get(r);c===void 0?(c=0,e.footnoteOrder.push(r),u=e.footnoteOrder.length):u=l+1,c+=1,e.footnoteCounts.set(r,c);const d={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+a,id:n+"fnref-"+a+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(u)}]};e.patch(t,d);const h={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(t,h),e.applyData(t,h)}function FD(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function VD(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function gw(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const a=e.all(t),l=a[0];l&&l.type==="text"?l.value="["+l.value:a.unshift({type:"text",value:"["});const u=a[a.length-1];return u&&u.type==="text"?u.value+=r:a.push({type:"text",value:r}),a}function GD(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return gw(e,t);const a={src:uo(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(a.title=r.title);const l={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,l),e.applyData(t,l)}function WD(e,t){const n={src:uo(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function qD(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function KD(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return gw(e,t);const a={href:uo(r.url||"")};r.title!==null&&r.title!==void 0&&(a.title=r.title);const l={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,l),e.applyData(t,l)}function YD(e,t){const n={href:uo(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function XD(e,t,n){const r=e.all(t),a=n?QD(n):xw(t),l={},u=[];if(typeof t.checked=="boolean"){const p=r[0];let m;p&&p.type==="element"&&p.tagName==="p"?m=p:(m={type:"element",tagName:"p",properties:{},children:[]},r.unshift(m)),m.children.length>0&&m.children.unshift({type:"text",value:" "}),m.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),l.className=["task-list-item"]}let c=-1;for(;++c<r.length;){const p=r[c];(a||c!==0||p.type!=="element"||p.tagName!=="p")&&u.push({type:"text",value:`
74
74
  `}),p.type==="element"&&p.tagName==="p"&&!a?u.push(...p.children):u.push(p)}const d=r[r.length-1];d&&(a||d.type!=="element"||d.tagName!=="p")&&u.push({type:"text",value:`
@@ -248,7 +248,7 @@ XID_Start XIDS`.split(/\s/).map(e=>[Hd(e),e])),FP=new Map([["s",xn(383)],[xn(383
248
248
  `)){const m=e?"text-text-muted":"text-text-code";return i.jsx("code",{className:`bg-bg-tertiary px-1 py-0.5 rounded ${m} font-mono text-xs`,...u,children:l})}const h=(c==null?void 0:c[1])||"text",p=String(l).replace(/\n$/,"");return i.jsx(A6,{language:h,codeString:p,showSyntaxHighlighting:t})},p({children:a}){const l=e?"text-text-muted":"text-text-primary";return i.jsx("p",{className:`${l} mb-1.5 last:mb-0 leading-tight break-words`,children:a})},ul({children:a}){return i.jsx("ul",{className:"list-disc list-inside mb-1.5 space-y-0.5",children:a})},ol({children:a}){return i.jsx("ol",{className:"list-decimal list-inside mb-1.5 space-y-0.5",children:a})},li({children:a}){const l=e?"text-text-muted":"text-text-primary";return i.jsx("li",{className:`${l} text-sm list-item`,children:a})},h1({children:a}){return i.jsx("h1",{className:`text-base font-bold mb-1.5 mt-2 first:mt-0 ${n}`,children:a})},h2({children:a}){return i.jsx("h2",{className:`text-sm font-bold mb-1.5 mt-2 first:mt-0 ${n}`,children:a})},h3({children:a}){return i.jsx("h3",{className:`text-sm font-bold mb-1.5 mt-1.5 first:mt-0 ${n}`,children:a})},h4({children:a}){return i.jsx("h4",{className:`text-sm font-bold mb-1.5 mt-1.5 first:mt-0 ${n}`,children:a})},strong({children:a}){return i.jsx("strong",{className:`font-bold ${r}`,children:a})},em({children:a}){return i.jsx("em",{className:e?"italic text-text-secondary":"italic",children:a})},a({href:a,children:l}){return i.jsx("a",{href:a,className:"text-text-link hover:underline text-sm",target:"_blank",rel:"noopener noreferrer",children:l})},blockquote({children:a}){const l=e?"text-text-muted":"text-text-secondary";return i.jsx("blockquote",{className:`border-l-2 border-accent-primary pl-2 my-1.5 ${l} italic text-sm`,children:a})},table({children:a}){return i.jsx("div",{className:"overflow-x-auto my-1.5",children:i.jsx("table",{className:"min-w-full border border-border",children:a})})},th({children:a}){return i.jsx("th",{className:"border border-border bg-bg-tertiary px-2 py-1 text-left font-semibold text-sm",children:a})},td({children:a}){return i.jsx("td",{className:"border border-border px-2 py-1 text-sm",children:a})},hr(){return i.jsx("hr",{className:"border-border my-2"})},input({checked:a,...l}){return i.jsx("input",{type:"checkbox",checked:a,disabled:!0,className:"mr-1.5 w-3.5 h-3.5",...l})}}}const Hn=N.memo(function({content:t,className:n="",muted:r=!1}){const{showSyntaxHighlighting:a}=Xi(),l=N.useMemo(()=>{let c=D6(t);return c=R6(c),c},[t]),u=N.useMemo(()=>L6(r,a),[r,a]);return i.jsx("div",{className:`markdown-content [&_li>p]:inline ${n}`,children:i.jsx(t5,{remarkPlugins:[mO],components:u,children:l})})});function D6(e){let t=e.replace(/^(\s*)•\s/gm,"$1- ");return t=t.replace(/^(\d+)\.\s*\n(?=\S)/gm,"$1. "),t=t.replace(/^\|\s*$/gm,""),t=t.replace(/^\d+\|/gm,""),t}function R6(e){const t=/```/g,n=e.match(t);if(((n==null?void 0:n.length)??0)%2===1){const a=e.lastIndexOf("```");return e.slice(a+3).includes(`
249
249
  `),e+"\n```"}return e}function _k({isOpen:e,onClose:t}){const[n,r]=N.useState(null),[a,l]=N.useState(!1),{settings:u,getSetting:c,setSetting:d}=Qi(),h=u[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]!=="false";N.useEffect(()=>{e&&c(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE)},[e,c]),N.useEffect(()=>{e&&(l(!0),Se("/api/changelog").then(m=>m.json()).then(m=>{r(m.content)}).catch(()=>{r(`# Changelog
250
250
 
251
- Failed to load changelog.`)}).finally(()=>l(!1)))},[e]);const p=N.useCallback(()=>{const m=h?"false":"true";d(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,m)},[h,d]);return i.jsx(wt,{isOpen:e,onClose:t,title:"What's New in OpenFox",size:"xl",closeOnBackdropClick:!0,showCloseButton:!0,footer:i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx(Yr,{enabled:h,onClick:p}),i.jsx("span",{className:"text-sm text-text-muted",children:"Show changelog on future updates"})]}),children:i.jsx("div",{className:"flex flex-col gap-4 min-h-0",children:a?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx("div",{className:"w-5 h-5 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"})}):i.jsx("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:i.jsx(Hn,{content:n??""})})})})}async function Sk(e,t,n){t({loading:!0});try{const a=await(await Se(e)).json();t({defaults:a.defaults??[],userItems:a.userItems??[],...n?{projectItems:a.projectItems??[]}:{},loading:!1})}catch{t({loading:!1})}}const O6="#6b7280";function Hl(e,t){var n;return((n=e.find(r=>r.id===t))==null?void 0:n.color)??O6}const mt=Mn(e=>{const t=async()=>{await Sk("/api/agents",e,!0)};return{defaults:[],userItems:[],projectItems:[],loading:!1,fetchAgents:t,fetchAgent:async n=>{try{const r=await Se(`/api/agents/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await Se(`/api/agents/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createAgent:async(n,r)=>{const a=await ui("POST","/api/agents",{...n,destination:r});return a.success&&await t(),a},updateAgent:async(n,r)=>{const a=await ui("PUT",`/api/agents/${n}`,r);return a.success&&await t(),a},deleteAgent:async n=>{try{const r=await Se(`/api/agents/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateAgent:async(n,r)=>vd(`/api/agents/${n}/duplicate`,t,r)}});function I6({onClose:e}){const[,t]=Ln(),{settings:n,getSetting:r,setSetting:a}=Qi(),l=n[Te.DISPLAY_SHOW_OPEN_IN_EDITOR]==="true",u=n[Te.LLM_DYNAMIC_SYSTEM_PROMPT]==="true",c=n[Te.CACHE_WARMING]==="true",[d,h]=N.useState({openInEditor:l,dynamicPrompt:u,cacheWarming:c}),[p,m]=N.useState({patterns:[],maxRetriesPerTurn:10}),[x,y]=N.useState(""),[w,C]=N.useState(""),[_,S]=N.useState(!1),[v,b,E,j]=gp(),[T,D]=N.useState(!1),[L,I]=N.useState(!1),P=Qt(B=>B.version),W=Cs(B=>B.status),H=Cs(B=>B.latest),R=Cs(B=>B.check),U=P&&H?{current:P,latest:H}:null,[V,G]=N.useState(!1),Z=mt(B=>B.defaults),X=mt(B=>B.userItems),$=mt(B=>B.fetchAgents),O=[...Z,...X].filter(B=>!B.subagent);N.useEffect(()=>{h({openInEditor:l,dynamicPrompt:u,cacheWarming:c})},[l,u,c]),N.useEffect(()=>{r(Te.DISPLAY_SHOW_OPEN_IN_EDITOR),r(Te.LLM_DYNAMIC_SYSTEM_PROMPT),r(Te.CACHE_WARMING),r(Te.RETRY_PATTERNS),r(Te.PROXY_URL)},[r]),N.useEffect(()=>{const B=n[Te.RETRY_PATTERNS];if(B)try{m(JSON.parse(B))}catch{}},[n]),N.useEffect(()=>{const B=n[Te.PROXY_URL];B!==void 0&&y(B)},[n]),N.useEffect(()=>{$().catch(()=>{})},[$]),N.useEffect(()=>{r(Te.DEFAULT_AGENT)},[r]),N.useEffect(()=>{const B=n[Te.DEFAULT_AGENT];B!==void 0&&(C(B),S(!0))},[n]);const M=N.useCallback(B=>{m(B),a(Te.RETRY_PATTERNS,JSON.stringify(B))},[a]),q=B=>{y(B),a(Te.PROXY_URL,B)};function z(){j(async()=>(await Se("/api/proxy/test",{method:"POST"})).json())}const ee=()=>{const B=!d.openInEditor;h(te=>({...te,openInEditor:B})),a(Te.DISPLAY_SHOW_OPEN_IN_EDITOR,String(B))},Q=()=>{const B=!d.dynamicPrompt;h(te=>({...te,dynamicPrompt:B})),a(Te.LLM_DYNAMIC_SYSTEM_PROMPT,String(B))},ne=()=>{const B=!d.cacheWarming;h(te=>({...te,cacheWarming:B})),a(Te.CACHE_WARMING,String(B))};function K(){e(),t("/onboarding")}return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"text-sm font-medium text-text-primary mb-1",children:[W==="available"&&i.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent-primary mr-1.5 align-middle"}),"Updates"]}),i.jsx("p",{className:"text-sm text-text-muted mb-4",children:P?i.jsxs(i.Fragment,{children:["Current version: ",i.jsxs("span",{className:"font-mono",children:["v",P]})]}):"Check for a new OpenFox version."}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Ze,{variant:"secondary",onClick:()=>{G(!0),R()},disabled:W==="checking",children:W==="checking"?"Checking…":"Check for Updates"}),V&&W==="upToDate"&&i.jsx("span",{className:"text-sm text-text-muted",children:"Up to date"}),W==="error"&&i.jsx("span",{className:"text-sm text-text-muted",children:"Update check failed"}),W==="available"&&i.jsxs("button",{onClick:()=>D(!0),className:"text-sm text-accent-primary hover:underline",children:["Update to v",H," →"]})]})]}),i.jsx(U1,{isOpen:T,onClose:()=>D(!1),versionInfo:U}),i.jsxs("div",{className:"flex items-center justify-between pt-2",children:[i.jsx("button",{onClick:()=>I(!0),className:"text-sm text-accent-primary hover:underline",children:"View Changelog →"}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("span",{className:"text-xs text-text-muted",children:"Show on update"}),i.jsx(Yr,{enabled:(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true",onClick:()=>{const te=(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true"?"false":"true";a(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,te)}})]})]}),i.jsx(_k,{isOpen:L,onClose:()=>I(!1)}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Default Agent"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Choose which agent is used by default for new sessions. The stock Planner is read-only; custom agents can have broader capabilities."}),i.jsxs("select",{value:_?w:"",onChange:B=>{const te=B.target.value;C(te),a(Te.DEFAULT_AGENT,te)},className:"w-full px-3 py-2 text-sm bg-bg-primary border border-border rounded-lg text-text-primary focus:outline-none focus:ring-2 focus:ring-accent-primary",children:[!_&&i.jsx("option",{value:"",children:"Loading…"}),_&&i.jsx("option",{value:"",children:"System default (planner)"}),O.map(B=>i.jsx("option",{value:B.id,children:B.name},B.id))]}),O.length===0&&_&&i.jsx("p",{className:"text-xs text-text-muted mt-1",children:"No agents available. Create one in the Agents modal."})]}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),i.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Manage providers, workdir and vision fallback."}),i.jsx(Ze,{variant:"secondary",onClick:K,children:"Launch Onboarding"})]}),i.jsx("hr",{className:"border-border"}),i.jsx("div",{children:i.jsx(ep,{title:'Show "Open in VSCode" links',description:"Display a link on file reads to open the file directly in VS Code.",enabled:d.openInEditor,onToggle:ee})}),i.jsx("hr",{className:"border-border"}),i.jsx(ep,{title:"Speculative Cache Warming",description:"On first keystroke in an empty session, prefill the LLM KV cache to reduce time-to-first-token.",enabled:d.cacheWarming,onToggle:ne,boldTitle:!0}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"HTTP Proxy"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Proxy server for LLM API requests. Leave empty for direct connection."}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx(oi,{type:"text",value:x,onChange:B=>q(B.target.value),placeholder:"http://proxy:8080",className:"flex-1"}),i.jsx(Ze,{variant:"secondary",onClick:z,style:E?{color:"rgb(63, 185, 80)"}:void 0,children:v})]}),b&&i.jsx("p",{className:"text-xs text-red-500 mt-1",children:b})]}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Auto-Retry Patterns"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:'Define regex patterns that, when matched against LLM responses mid-stream, trigger an automatic retry with a "continue" prompt. The content that triggered the match is preserved in the chat feed.'}),i.jsx(VT,{value:p,onChange:M})]}),i.jsx("hr",{className:"border-border"}),i.jsx(ep,{title:"Dynamic System Prompt",description:"Rebuild the system prompt on every turn. Recommended value: off.",enabled:d.dynamicPrompt,onToggle:Q,boldTitle:!0})]})}function ep({title:e,description:t,enabled:n,onToggle:r,boldTitle:a}){return i.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:`text-sm ${a?"font-medium":""} text-text-primary`,children:e}),i.jsx("div",{className:"text-sm text-text-muted mt-0.5",children:t})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(Yr,{enabled:n,onClick:r})})]})}function M6(e,t){return e===null&&t===null?!0:e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}function P6({label:e,binding:t,defaultBinding:n,isRecording:r,onStartRecording:a,onBindingRecorded:l,onClear:u,onReset:c,onCancelRecording:d}){const h=N.useRef(null),p=N.useRef(0),m=N.useRef("");return N.useEffect(()=>{if(!r)return;const x=new Set(["Control","Shift","Alt","Meta"]);let y=[];const w=_=>{if(_.preventDefault(),_.stopPropagation(),_.key==="Escape"){d();return}if(x.has(_.key)){const b=Date.now();if(_.key===m.current&&b-p.current<400){l({type:"double-press",key:_.key,threshold:300});return}p.current=b,m.current=_.key,_.ctrlKey&&!y.includes("ctrl")&&y.push("ctrl"),_.metaKey&&!y.includes("meta")&&y.push("meta"),_.altKey&&!y.includes("alt")&&y.push("alt"),_.shiftKey&&!y.includes("shift")&&y.push("shift");return}if(y.length>0||_.ctrlKey||_.metaKey||_.altKey||_.shiftKey){const b=[...y];_.ctrlKey&&!b.includes("ctrl")&&b.push("ctrl"),_.metaKey&&!b.includes("meta")&&b.push("meta"),_.altKey&&!b.includes("alt")&&b.push("alt"),_.shiftKey&&!b.includes("shift")&&b.push("shift"),l({type:"chord",key:A_(_),modifiers:b});return}const S=Date.now(),v=A_(_);if(v===m.current&&S-p.current<400){l({type:"double-press",key:v,threshold:300});return}p.current=S,m.current=v},C=_=>{_.key==="Control"&&(y=y.filter(S=>S!=="ctrl")),_.key==="Shift"&&(y=y.filter(S=>S!=="shift")),_.key==="Alt"&&(y=y.filter(S=>S!=="alt")),_.key==="Meta"&&(y=y.filter(S=>S!=="meta"))};return window.addEventListener("keydown",w,!0),window.addEventListener("keyup",C,!0),()=>{window.removeEventListener("keydown",w,!0),window.removeEventListener("keyup",C,!0)}},[r,l,d]),i.jsxs("div",{ref:h,className:`flex items-center justify-between px-3 py-2 rounded transition-colors ${r?"bg-accent-primary/10 ring-1 ring-accent-primary":"hover:bg-bg-tertiary"}`,children:[i.jsx("span",{className:"text-sm text-text-primary",children:e}),i.jsx("div",{className:"flex items-center gap-2",children:r?i.jsx("span",{className:"text-xs text-accent-primary font-medium animate-pulse",children:"Press shortcut..."}):i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:a,className:"px-2 py-0.5 text-xs font-mono bg-bg-tertiary text-text-secondary rounded border border-border hover:border-accent-primary hover:text-accent-primary transition-colors",children:t?qu(t):"None"}),t&&i.jsx("button",{type:"button",onClick:u,title:"Remove shortcut","aria-label":`Remove shortcut for ${e}`,className:"p-1 text-text-muted rounded hover:text-accent-error hover:bg-bg-tertiary transition-colors",children:i.jsx(rg,{className:"w-3.5 h-3.5"})}),!M6(t,n)&&i.jsx("button",{type:"button",onClick:c,title:"Reset to default","aria-label":`Reset ${e} to default`,className:"p-1 text-text-muted rounded hover:text-accent-primary hover:bg-bg-tertiary transition-colors",children:i.jsx(Sd,{className:"w-3.5 h-3.5"})})]})})]})}function B6(){const{settings:e,loading:t,setSetting:n}=Qi(),r=e[Te.KEYBINDINGS],a=t[Te.KEYBINDINGS]??!1,l=pp(r),[u,c]=N.useState(null),d=[{id:"terminalToggle",label:"Toggle Terminal",binding:l.terminalToggle,defaultBinding:qr.terminalToggle},{id:"quickAction",label:"Quick Action",binding:l.quickAction,defaultBinding:qr.quickAction},{id:"modelSelector",label:"Select Model",binding:l.modelSelector,defaultBinding:qr.modelSelector},{id:"sessionSearch",label:"Search Sessions",binding:l.sessionSearch,defaultBinding:qr.sessionSearch},{id:"criteriaSidebar",label:"Toggle Criteria Sidebar",binding:l.criteriaSidebar,defaultBinding:qr.criteriaSidebar},...l.agentSwitching.map((y,w)=>({id:`agentSwitching.${w}`,label:`Switch to Agent ${w+1}`,binding:y,defaultBinding:qr.agentSwitching[w]??null}))],h=y=>{c(y)},p=N.useCallback((y,w)=>{const C=pp(r);if(y.startsWith("agentSwitching.")){const _=parseInt(y.split(".")[1],10);C.agentSwitching[_]=w}else y==="terminalToggle"?C.terminalToggle=w:y==="quickAction"?C.quickAction=w:y==="modelSelector"?C.modelSelector=w:y==="sessionSearch"?C.sessionSearch=w:y==="criteriaSidebar"&&(C.criteriaSidebar=w);n(Te.KEYBINDINGS,JSON.stringify(C))},[r,n]),m=N.useCallback(y=>{u&&(c(null),p(u,y))},[u,p]),x=()=>{n(Te.KEYBINDINGS,JSON.stringify(qr))};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Keyboard Shortcuts"}),i.jsx("button",{type:"button",onClick:x,disabled:a,className:"text-xs text-text-muted hover:text-text-primary px-2 py-1 rounded hover:bg-bg-tertiary transition-colors disabled:opacity-30",children:"Reset to defaults"})]}),a?i.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):i.jsx("div",{className:"space-y-1",children:d.map(y=>i.jsx(P6,{label:y.label,binding:y.binding,defaultBinding:y.defaultBinding,isRecording:u===y.id,onStartRecording:()=>h(y.id),onBindingRecorded:m,onClear:()=>p(y.id,null),onReset:()=>p(y.id,y.defaultBinding),onCancelRecording:()=>c(null)},y.id))})]})}function Vg(e){switch(e){case"connected":return"text-accent-success";case"error":return"text-accent-error";case"disabled":return"text-text-muted";default:return"text-text-muted"}}function Gg(e){switch(e){case"connected":return"●";case"error":return"✕";default:return"○"}}function ud(e){return e>=1e3?`~${(e/1e3).toFixed(1)}K`:`~${e}`}function wk({server:e,expanded:t,onToggleExpand:n,serverToggleEnabled:r,onServerToggle:a,tools:l,onToolToggle:u,statusDot:c,statusColor:d,actions:h}){var y;const[p,m]=N.useState(new Set),x=e.name;return i.jsxs("div",{className:"rounded border border-border bg-bg-tertiary overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between p-3 hover:bg-bg-primary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1 cursor-pointer",onClick:()=>n(x),children:[i.jsx("span",{className:`text-sm ${d}`,children:c}),i.jsx("span",{className:"text-sm font-medium text-text-primary",children:x}),i.jsx("span",{className:"text-xs text-text-muted",children:e.config.transport}),i.jsxs("span",{className:"text-xs text-text-muted",children:["(",l.length," tools)"]}),i.jsxs("span",{className:"text-xs text-text-muted",children:[ud(e.estimatedTokens)," tokens"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Yr,{enabled:r,onClick:a}),h,i.jsx("span",{className:"text-xs text-text-muted",children:t?"▲":"▼"})]})]}),t&&i.jsxs("div",{className:"border-t border-border px-3 py-2 space-y-1.5",children:[e.config.command&&i.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[e.config.command," ",((y=e.config.args)==null?void 0:y.join(" "))??""]}),e.config.url&&i.jsx("div",{className:"text-xs text-text-muted font-mono",children:e.config.url}),l.length===0?i.jsx("div",{className:"text-xs text-text-muted",children:"No tools available"}):i.jsx("div",{className:"space-y-1",children:l.map(w=>i.jsxs("div",{className:"py-1",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"min-w-0 flex-1 mr-2",children:[i.jsx("span",{className:"text-xs text-text-primary font-mono",children:w.name}),w.description&&w.description.length>80?i.jsxs("button",{onClick:()=>{const C=w.name;m(_=>{const S=new Set(_);return S.has(C)?S.delete(C):S.add(C),S})},className:"inline-flex items-center gap-0.5 text-xs text-text-muted hover:text-text-primary transition-colors ml-2",children:[i.jsx("span",{className:"truncate max-w-[300px]",children:w.description}),i.jsx(yn,{rotate:p.has(w.name)?180:0,className:"w-3 h-3 flex-shrink-0"})]}):w.description?i.jsx("span",{className:"text-xs text-text-muted ml-2",children:w.description}):null]}),i.jsx("span",{className:"text-xs text-text-muted mr-2 flex-shrink-0",children:ud(w.estimatedTokens)}),i.jsx(Yr,{enabled:w.enabled,onClick:()=>u(w.name)})]}),w.description&&w.description.length>80&&p.has(w.name)&&i.jsx("div",{className:"text-xs text-text-muted mt-1 ml-1",children:w.description})]},w.name))})]})]},x)}function gS(e){const t={};return e.split(`
251
+ Failed to load changelog.`)}).finally(()=>l(!1)))},[e]);const p=N.useCallback(()=>{const m=h?"false":"true";d(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,m)},[h,d]);return i.jsx(wt,{isOpen:e,onClose:t,title:"What's New in OpenFox",size:"xl",closeOnBackdropClick:!0,showCloseButton:!0,footer:i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx(Yr,{enabled:h,onClick:p}),i.jsx("span",{className:"text-sm text-text-muted",children:"Show changelog on future updates"})]}),children:i.jsx("div",{className:"flex flex-col gap-4 min-h-0",children:a?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx("div",{className:"w-5 h-5 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"})}):i.jsx("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:i.jsx(Hn,{content:n??""})})})})}async function Sk(e,t,n){t({loading:!0});try{const a=await(await Se(e)).json();t({defaults:a.defaults??[],userItems:a.userItems??[],...n?{projectItems:a.projectItems??[]}:{},loading:!1})}catch{t({loading:!1})}}const O6="#6b7280";function Hl(e,t){var n;return((n=e.find(r=>r.id===t))==null?void 0:n.color)??O6}const mt=Mn(e=>{const t=async()=>{await Sk("/api/agents",e,!0)};return{defaults:[],userItems:[],projectItems:[],loading:!1,fetchAgents:t,fetchAgent:async n=>{try{const r=await Se(`/api/agents/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await Se(`/api/agents/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createAgent:async(n,r)=>{const a=await ui("POST","/api/agents",{...n,destination:r});return a.success&&await t(),a},updateAgent:async(n,r)=>{const a=await ui("PUT",`/api/agents/${n}`,r);return a.success&&await t(),a},deleteAgent:async n=>{try{const r=await Se(`/api/agents/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateAgent:async(n,r)=>vd(`/api/agents/${n}/duplicate`,t,r)}});function I6({onClose:e}){const[,t]=Ln(),{settings:n,getSetting:r,setSetting:a}=Qi(),l=n[Te.DISPLAY_SHOW_OPEN_IN_EDITOR]==="true",u=n[Te.LLM_DYNAMIC_SYSTEM_PROMPT]==="true",c=n[Te.CACHE_WARMING]==="true",[d,h]=N.useState({openInEditor:l,dynamicPrompt:u,cacheWarming:c}),[p,m]=N.useState({patterns:[],maxRetriesPerTurn:10}),[x,y]=N.useState(""),[w,C]=N.useState(""),[_,S]=N.useState(!1),[v,b,E,j]=gp(),[T,D]=N.useState(!1),[L,I]=N.useState(!1),P=Kt(B=>B.version),W=Cs(B=>B.status),H=Cs(B=>B.latest),R=Cs(B=>B.check),U=P&&H?{current:P,latest:H}:null,[V,G]=N.useState(!1),Z=mt(B=>B.defaults),X=mt(B=>B.userItems),$=mt(B=>B.fetchAgents),O=[...Z,...X].filter(B=>!B.subagent);N.useEffect(()=>{h({openInEditor:l,dynamicPrompt:u,cacheWarming:c})},[l,u,c]),N.useEffect(()=>{r(Te.DISPLAY_SHOW_OPEN_IN_EDITOR),r(Te.LLM_DYNAMIC_SYSTEM_PROMPT),r(Te.CACHE_WARMING),r(Te.RETRY_PATTERNS),r(Te.PROXY_URL)},[r]),N.useEffect(()=>{const B=n[Te.RETRY_PATTERNS];if(B)try{m(JSON.parse(B))}catch{}},[n]),N.useEffect(()=>{const B=n[Te.PROXY_URL];B!==void 0&&y(B)},[n]),N.useEffect(()=>{$().catch(()=>{})},[$]),N.useEffect(()=>{r(Te.DEFAULT_AGENT)},[r]),N.useEffect(()=>{const B=n[Te.DEFAULT_AGENT];B!==void 0&&(C(B),S(!0))},[n]);const M=N.useCallback(B=>{m(B),a(Te.RETRY_PATTERNS,JSON.stringify(B))},[a]),q=B=>{y(B),a(Te.PROXY_URL,B)};function z(){j(async()=>(await Se("/api/proxy/test",{method:"POST"})).json())}const ee=()=>{const B=!d.openInEditor;h(te=>({...te,openInEditor:B})),a(Te.DISPLAY_SHOW_OPEN_IN_EDITOR,String(B))},Q=()=>{const B=!d.dynamicPrompt;h(te=>({...te,dynamicPrompt:B})),a(Te.LLM_DYNAMIC_SYSTEM_PROMPT,String(B))},ne=()=>{const B=!d.cacheWarming;h(te=>({...te,cacheWarming:B})),a(Te.CACHE_WARMING,String(B))};function K(){e(),t("/onboarding")}return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"text-sm font-medium text-text-primary mb-1",children:[W==="available"&&i.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent-primary mr-1.5 align-middle"}),"Updates"]}),i.jsx("p",{className:"text-sm text-text-muted mb-4",children:P?i.jsxs(i.Fragment,{children:["Current version: ",i.jsxs("span",{className:"font-mono",children:["v",P]})]}):"Check for a new OpenFox version."}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Ze,{variant:"secondary",onClick:()=>{G(!0),R()},disabled:W==="checking",children:W==="checking"?"Checking…":"Check for Updates"}),V&&W==="upToDate"&&i.jsx("span",{className:"text-sm text-text-muted",children:"Up to date"}),W==="error"&&i.jsx("span",{className:"text-sm text-text-muted",children:"Update check failed"}),W==="available"&&i.jsxs("button",{onClick:()=>D(!0),className:"text-sm text-accent-primary hover:underline",children:["Update to v",H," →"]})]})]}),i.jsx(U1,{isOpen:T,onClose:()=>D(!1),versionInfo:U}),i.jsxs("div",{className:"flex items-center justify-between pt-2",children:[i.jsx("button",{onClick:()=>I(!0),className:"text-sm text-accent-primary hover:underline",children:"View Changelog →"}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("span",{className:"text-xs text-text-muted",children:"Show on update"}),i.jsx(Yr,{enabled:(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true",onClick:()=>{const te=(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true"?"false":"true";a(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,te)}})]})]}),i.jsx(_k,{isOpen:L,onClose:()=>I(!1)}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Default Agent"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Choose which agent is used by default for new sessions. The stock Planner is read-only; custom agents can have broader capabilities."}),i.jsxs("select",{value:_?w:"",onChange:B=>{const te=B.target.value;C(te),a(Te.DEFAULT_AGENT,te)},className:"w-full px-3 py-2 text-sm bg-bg-primary border border-border rounded-lg text-text-primary focus:outline-none focus:ring-2 focus:ring-accent-primary",children:[!_&&i.jsx("option",{value:"",children:"Loading…"}),_&&i.jsx("option",{value:"",children:"System default (planner)"}),O.map(B=>i.jsx("option",{value:B.id,children:B.name},B.id))]}),O.length===0&&_&&i.jsx("p",{className:"text-xs text-text-muted mt-1",children:"No agents available. Create one in the Agents modal."})]}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),i.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Manage providers, workdir and vision fallback."}),i.jsx(Ze,{variant:"secondary",onClick:K,children:"Launch Onboarding"})]}),i.jsx("hr",{className:"border-border"}),i.jsx("div",{children:i.jsx(ep,{title:'Show "Open in VSCode" links',description:"Display a link on file reads to open the file directly in VS Code.",enabled:d.openInEditor,onToggle:ee})}),i.jsx("hr",{className:"border-border"}),i.jsx(ep,{title:"Speculative Cache Warming",description:"On first keystroke in an empty session, prefill the LLM KV cache to reduce time-to-first-token.",enabled:d.cacheWarming,onToggle:ne,boldTitle:!0}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"HTTP Proxy"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Proxy server for LLM API requests. Leave empty for direct connection."}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx(oi,{type:"text",value:x,onChange:B=>q(B.target.value),placeholder:"http://proxy:8080",className:"flex-1"}),i.jsx(Ze,{variant:"secondary",onClick:z,style:E?{color:"rgb(63, 185, 80)"}:void 0,children:v})]}),b&&i.jsx("p",{className:"text-xs text-red-500 mt-1",children:b})]}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Auto-Retry Patterns"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:'Define regex patterns that, when matched against LLM responses mid-stream, trigger an automatic retry with a "continue" prompt. The content that triggered the match is preserved in the chat feed.'}),i.jsx(VT,{value:p,onChange:M})]}),i.jsx("hr",{className:"border-border"}),i.jsx(ep,{title:"Dynamic System Prompt",description:"Rebuild the system prompt on every turn. Recommended value: off.",enabled:d.dynamicPrompt,onToggle:Q,boldTitle:!0})]})}function ep({title:e,description:t,enabled:n,onToggle:r,boldTitle:a}){return i.jsxs("label",{className:"flex items-start justify-between gap-3 cursor-pointer",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:`text-sm ${a?"font-medium":""} text-text-primary`,children:e}),i.jsx("div",{className:"text-sm text-text-muted mt-0.5",children:t})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(Yr,{enabled:n,onClick:r})})]})}function M6(e,t){return e===null&&t===null?!0:e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}function P6({label:e,binding:t,defaultBinding:n,isRecording:r,onStartRecording:a,onBindingRecorded:l,onClear:u,onReset:c,onCancelRecording:d}){const h=N.useRef(null),p=N.useRef(0),m=N.useRef("");return N.useEffect(()=>{if(!r)return;const x=new Set(["Control","Shift","Alt","Meta"]);let y=[];const w=_=>{if(_.preventDefault(),_.stopPropagation(),_.key==="Escape"){d();return}if(x.has(_.key)){const b=Date.now();if(_.key===m.current&&b-p.current<400){l({type:"double-press",key:_.key,threshold:300});return}p.current=b,m.current=_.key,_.ctrlKey&&!y.includes("ctrl")&&y.push("ctrl"),_.metaKey&&!y.includes("meta")&&y.push("meta"),_.altKey&&!y.includes("alt")&&y.push("alt"),_.shiftKey&&!y.includes("shift")&&y.push("shift");return}if(y.length>0||_.ctrlKey||_.metaKey||_.altKey||_.shiftKey){const b=[...y];_.ctrlKey&&!b.includes("ctrl")&&b.push("ctrl"),_.metaKey&&!b.includes("meta")&&b.push("meta"),_.altKey&&!b.includes("alt")&&b.push("alt"),_.shiftKey&&!b.includes("shift")&&b.push("shift"),l({type:"chord",key:A_(_),modifiers:b});return}const S=Date.now(),v=A_(_);if(v===m.current&&S-p.current<400){l({type:"double-press",key:v,threshold:300});return}p.current=S,m.current=v},C=_=>{_.key==="Control"&&(y=y.filter(S=>S!=="ctrl")),_.key==="Shift"&&(y=y.filter(S=>S!=="shift")),_.key==="Alt"&&(y=y.filter(S=>S!=="alt")),_.key==="Meta"&&(y=y.filter(S=>S!=="meta"))};return window.addEventListener("keydown",w,!0),window.addEventListener("keyup",C,!0),()=>{window.removeEventListener("keydown",w,!0),window.removeEventListener("keyup",C,!0)}},[r,l,d]),i.jsxs("div",{ref:h,className:`flex items-center justify-between px-3 py-2 rounded transition-colors ${r?"bg-accent-primary/10 ring-1 ring-accent-primary":"hover:bg-bg-tertiary"}`,children:[i.jsx("span",{className:"text-sm text-text-primary",children:e}),i.jsx("div",{className:"flex items-center gap-2",children:r?i.jsx("span",{className:"text-xs text-accent-primary font-medium animate-pulse",children:"Press shortcut..."}):i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:a,className:"px-2 py-0.5 text-xs font-mono bg-bg-tertiary text-text-secondary rounded border border-border hover:border-accent-primary hover:text-accent-primary transition-colors",children:t?qu(t):"None"}),t&&i.jsx("button",{type:"button",onClick:u,title:"Remove shortcut","aria-label":`Remove shortcut for ${e}`,className:"p-1 text-text-muted rounded hover:text-accent-error hover:bg-bg-tertiary transition-colors",children:i.jsx(rg,{className:"w-3.5 h-3.5"})}),!M6(t,n)&&i.jsx("button",{type:"button",onClick:c,title:"Reset to default","aria-label":`Reset ${e} to default`,className:"p-1 text-text-muted rounded hover:text-accent-primary hover:bg-bg-tertiary transition-colors",children:i.jsx(Sd,{className:"w-3.5 h-3.5"})})]})})]})}function B6(){const{settings:e,loading:t,setSetting:n}=Qi(),r=e[Te.KEYBINDINGS],a=t[Te.KEYBINDINGS]??!1,l=pp(r),[u,c]=N.useState(null),d=[{id:"terminalToggle",label:"Toggle Terminal",binding:l.terminalToggle,defaultBinding:qr.terminalToggle},{id:"quickAction",label:"Quick Action",binding:l.quickAction,defaultBinding:qr.quickAction},{id:"modelSelector",label:"Select Model",binding:l.modelSelector,defaultBinding:qr.modelSelector},{id:"sessionSearch",label:"Search Sessions",binding:l.sessionSearch,defaultBinding:qr.sessionSearch},{id:"criteriaSidebar",label:"Toggle Criteria Sidebar",binding:l.criteriaSidebar,defaultBinding:qr.criteriaSidebar},...l.agentSwitching.map((y,w)=>({id:`agentSwitching.${w}`,label:`Switch to Agent ${w+1}`,binding:y,defaultBinding:qr.agentSwitching[w]??null}))],h=y=>{c(y)},p=N.useCallback((y,w)=>{const C=pp(r);if(y.startsWith("agentSwitching.")){const _=parseInt(y.split(".")[1],10);C.agentSwitching[_]=w}else y==="terminalToggle"?C.terminalToggle=w:y==="quickAction"?C.quickAction=w:y==="modelSelector"?C.modelSelector=w:y==="sessionSearch"?C.sessionSearch=w:y==="criteriaSidebar"&&(C.criteriaSidebar=w);n(Te.KEYBINDINGS,JSON.stringify(C))},[r,n]),m=N.useCallback(y=>{u&&(c(null),p(u,y))},[u,p]),x=()=>{n(Te.KEYBINDINGS,JSON.stringify(qr))};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Keyboard Shortcuts"}),i.jsx("button",{type:"button",onClick:x,disabled:a,className:"text-xs text-text-muted hover:text-text-primary px-2 py-1 rounded hover:bg-bg-tertiary transition-colors disabled:opacity-30",children:"Reset to defaults"})]}),a?i.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):i.jsx("div",{className:"space-y-1",children:d.map(y=>i.jsx(P6,{label:y.label,binding:y.binding,defaultBinding:y.defaultBinding,isRecording:u===y.id,onStartRecording:()=>h(y.id),onBindingRecorded:m,onClear:()=>p(y.id,null),onReset:()=>p(y.id,y.defaultBinding),onCancelRecording:()=>c(null)},y.id))})]})}function Vg(e){switch(e){case"connected":return"text-accent-success";case"error":return"text-accent-error";case"disabled":return"text-text-muted";default:return"text-text-muted"}}function Gg(e){switch(e){case"connected":return"●";case"error":return"✕";default:return"○"}}function ud(e){return e>=1e3?`~${(e/1e3).toFixed(1)}K`:`~${e}`}function wk({server:e,expanded:t,onToggleExpand:n,serverToggleEnabled:r,onServerToggle:a,tools:l,onToolToggle:u,statusDot:c,statusColor:d,actions:h}){var y;const[p,m]=N.useState(new Set),x=e.name;return i.jsxs("div",{className:"rounded border border-border bg-bg-tertiary overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between p-3 hover:bg-bg-primary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1 cursor-pointer",onClick:()=>n(x),children:[i.jsx("span",{className:`text-sm ${d}`,children:c}),i.jsx("span",{className:"text-sm font-medium text-text-primary",children:x}),i.jsx("span",{className:"text-xs text-text-muted",children:e.config.transport}),i.jsxs("span",{className:"text-xs text-text-muted",children:["(",l.length," tools)"]}),i.jsxs("span",{className:"text-xs text-text-muted",children:[ud(e.estimatedTokens)," tokens"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Yr,{enabled:r,onClick:a}),h,i.jsx("span",{className:"text-xs text-text-muted",children:t?"▲":"▼"})]})]}),t&&i.jsxs("div",{className:"border-t border-border px-3 py-2 space-y-1.5",children:[e.config.command&&i.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[e.config.command," ",((y=e.config.args)==null?void 0:y.join(" "))??""]}),e.config.url&&i.jsx("div",{className:"text-xs text-text-muted font-mono",children:e.config.url}),l.length===0?i.jsx("div",{className:"text-xs text-text-muted",children:"No tools available"}):i.jsx("div",{className:"space-y-1",children:l.map(w=>i.jsxs("div",{className:"py-1",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"min-w-0 flex-1 mr-2",children:[i.jsx("span",{className:"text-xs text-text-primary font-mono",children:w.name}),w.description&&w.description.length>80?i.jsxs("button",{onClick:()=>{const C=w.name;m(_=>{const S=new Set(_);return S.has(C)?S.delete(C):S.add(C),S})},className:"inline-flex items-center gap-0.5 text-xs text-text-muted hover:text-text-primary transition-colors ml-2",children:[i.jsx("span",{className:"truncate max-w-[300px]",children:w.description}),i.jsx(yn,{rotate:p.has(w.name)?180:0,className:"w-3 h-3 flex-shrink-0"})]}):w.description?i.jsx("span",{className:"text-xs text-text-muted ml-2",children:w.description}):null]}),i.jsx("span",{className:"text-xs text-text-muted mr-2 flex-shrink-0",children:ud(w.estimatedTokens)}),i.jsx(Yr,{enabled:w.enabled,onClick:()=>u(w.name)})]}),w.description&&w.description.length>80&&p.has(w.name)&&i.jsx("div",{className:"text-xs text-text-muted mt-1 ml-1",children:w.description})]},w.name))})]})]},x)}function gS(e){const t={};return e.split(`
252
252
  `).filter(Boolean).forEach(n=>{const r=n.indexOf("=");r>0&&(t[n.slice(0,r).trim()]=n.slice(r+1).trim())}),t}function xS({formData:e,onChange:t}){return i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Transport"}),i.jsxs("div",{className:"flex gap-1",children:[i.jsx("button",{onClick:()=>t({...e,transport:"stdio"}),className:`px-3 py-1.5 rounded text-xs font-medium transition-colors ${e.transport==="stdio"?"bg-accent-primary text-white":"bg-bg-tertiary text-text-secondary hover:bg-bg-primary"}`,children:"Stdio"}),i.jsx("button",{onClick:()=>t({...e,transport:"http"}),className:`px-3 py-1.5 rounded text-xs font-medium transition-colors ${e.transport==="http"?"bg-accent-primary text-white":"bg-bg-tertiary text-text-secondary hover:bg-bg-primary"}`,children:"HTTP"})]})]}),e.transport==="stdio"?i.jsxs(i.Fragment,{children:[i.jsx(kr,{label:"Command",value:e.command,onChange:n=>t({...e,command:n}),placeholder:"e.g. npx"}),i.jsx(kr,{label:"Arguments",value:e.args,onChange:n=>t({...e,args:n}),placeholder:"space-separated args"}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Environment variables ",i.jsx("span",{className:"text-text-muted",children:"(KEY=VALUE, one per line)"})]}),i.jsx("textarea",{value:e.env,onChange:n=>t({...e,env:n.target.value}),placeholder:"API_KEY=xxx",className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary",rows:3})]})]}):i.jsxs(i.Fragment,{children:[i.jsx(kr,{label:"URL",value:e.url,onChange:n=>t({...e,url:n}),placeholder:"e.g. https://mcp.example.com/mcp"}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Headers ",i.jsx("span",{className:"text-text-muted",children:"(KEY=VALUE, one per line)"})]}),i.jsx("textarea",{value:e.headers,onChange:n=>t({...e,headers:n.target.value}),placeholder:"X-API-Key=xxx",className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary",rows:3})]})]}),i.jsx(kr,{label:"Timeout (seconds)",value:e.timeout,onChange:n=>t({...e,timeout:n}),placeholder:"optional, e.g. 30"})]})}function tp(e,t,n,r=250){const a=N.useRef(!0);N.useEffect(()=>{if(a.current){a.current=!1;return}const l=setTimeout(()=>{n(t,e)},r);return()=>clearTimeout(l)},[e,t,r,n])}function yS({saving:e,saveLabel:t,savingLabel:n,onCancel:r,onSave:a}){return i.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[i.jsx(Ze,{variant:"secondary",onClick:r,disabled:e,children:"Cancel"}),i.jsx(Ze,{variant:"primary",onClick:a,disabled:e,children:e?n:t})]})}function $6(){const{settings:e,getSetting:t,setSetting:n}=Qi(),[r,a]=N.useState(""),[l,u]=N.useState(""),[c,d]=N.useState(""),[h,p]=N.useState("");tp(l,Te.SEARCH_TAVILY_API_KEY,n),tp(c,Te.SEARCH_SEARXNG_URL,n),tp(h,Te.SEARCH_SEARXNG_API_KEY,n);const[m,x,y,w]=gp(),[C,_,S,v]=gp();N.useEffect(()=>{t(Te.SEARCH_ENGINE),t(Te.SEARCH_TAVILY_API_KEY),t(Te.SEARCH_SEARXNG_URL),t(Te.SEARCH_SEARXNG_API_KEY),t(Te.TOOLS_USE_RTK),t(Te.CONFIRM_ON_WORKSPACE_ACTIONS)},[t]),N.useEffect(()=>{e[Te.SEARCH_ENGINE]!==void 0&&(a(e[Te.SEARCH_ENGINE]??""),u(e[Te.SEARCH_TAVILY_API_KEY]??""),d(e[Te.SEARCH_SEARXNG_URL]??""),p(e[Te.SEARCH_SEARXNG_API_KEY]??""))},[e]);function b(he){a(he),n(Te.SEARCH_ENGINE,he)}function E(){w(async()=>(await Se("/api/search/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({engine:"tavily",tavilyApiKey:l||void 0})})).json())}function j(){v(async()=>(await Se("/api/search/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({engine:"searxng",searxngUrl:c||void 0,searxngApiKey:h||void 0})})).json())}const[T,D]=N.useState("checking");N.useEffect(()=>{Se("/api/tools/rtk-check").then(he=>he.json()).then(he=>D(he.available?"available":"unavailable")).catch(()=>D("unavailable"))},[]);const[L,I]=N.useState([]);N.useEffect(()=>{t(Te.TOOLS_SHELL),Se("/api/tools/shells").then(he=>he.json()).then(he=>I(he.shells??[])).catch(()=>I([]))},[t]);const P=e[Te.TOOLS_SHELL]||"cmd",[W,H]=N.useState([]),[R,U]=N.useState(!0),[V,G]=N.useState(!1),[Z,X]=N.useState(null),[$,O]=N.useState(new Set),[M,q]=N.useState({name:"",transport:"stdio",command:"",args:"",env:"",url:"",headers:"",timeout:""}),[z,ee]=N.useState(""),[Q,ne]=N.useState(""),[K,B]=N.useState(!1),{requestDelete:te,clearConfirm:se,isConfirming:xe}=Wl(),oe=N.useCallback(async()=>{try{const Ue=((await(await Se("/api/mcp/servers")).json()).servers??[]).sort((re,_e)=>re.name.localeCompare(_e.name));H(Ue)}catch{}U(!1)},[]);N.useEffect(()=>{oe()},[oe]),N.useEffect(()=>{const he=()=>oe();return window.addEventListener("mcp-servers-changed",he),()=>window.removeEventListener("mcp-servers-changed",he)},[oe]);const Oe=he=>{O(De=>{const Ue=new Set(De);return Ue.has(he)?(Ue.delete(he),Ue):(Ue.add(he),Ue)})};function Me(){if(M.transport==="stdio"&&!M.command)return"Command is required for stdio transport";if(M.transport==="http"&&!M.url)return"URL is required for HTTP transport";if(M.timeout){const he=parseFloat(M.timeout);if(isNaN(he)||he<=0)return"Timeout must be a positive number"}return null}function ze(he){const De=he?{name:M.name,transport:M.transport}:{transport:M.transport};if(M.transport==="stdio"?(De.command=M.command,De.args=M.args?M.args.split(" ").filter(Boolean):[],De.env=gS(M.env)):(De.url=M.url,De.headers=gS(M.headers)),M.timeout){const Ue=parseFloat(M.timeout);!isNaN(Ue)&&Ue>0&&(De.timeout=Ue)}return De}const $e={name:"",transport:"stdio",command:"",args:"",env:"",url:"",headers:"",timeout:""},je=async()=>{if(ee(""),!M.name){ee("Name is required");return}const he=Me();if(he){ee(he);return}B(!0);try{const De=ze(!0),Ue=await Se("/api/mcp/servers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(De)});if(!Ue.ok){const re=await Ue.json();throw new Error(re.error??"Failed to add server")}G(!1),q($e),await oe()}catch(De){ee(De instanceof Error?De.message:String(De))}finally{B(!1)}},rt=he=>{var De;q({name:he.name,transport:he.config.transport,command:he.config.command??"",args:((De=he.config.args)==null?void 0:De.join(" "))??"",env:he.config.env?Object.entries(he.config.env).map(([Ue,re])=>`${Ue}=${re}`).join(`
253
253
  `):"",url:he.config.url??"",headers:he.config.headers?Object.entries(he.config.headers).map(([Ue,re])=>`${Ue}=${re}`).join(`
254
254
  `):"",timeout:he.config.timeout!==void 0?String(he.config.timeout):""}),ee(""),X(he.name)},Qe=async()=>{ee("");const he=Me();if(he){ee(he);return}B(!0);try{const De=ze(!1),Ue=await Se(`/api/mcp/servers/${encodeURIComponent(Z)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(De)});if(!Ue.ok){const re=await Ue.json();throw new Error(re.error??"Failed to update server")}X(null),q($e),await oe()}catch(De){ee(De instanceof Error?De.message:String(De))}finally{B(!1)}},fe=async he=>{try{const De=await Se(`/api/mcp/servers/${encodeURIComponent(he)}`,{method:"DELETE"});if(!De.ok){const Ue=await De.json().catch(()=>({}));throw new Error(Ue.error??"Failed to remove server")}se(),ne(""),await oe()}catch(De){ne(De instanceof Error?De.message:String(De))}},ce=async(he,De,Ue)=>{try{const re=await Se(`/api/mcp/servers/${encodeURIComponent(he)}/tools/${encodeURIComponent(De)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:Ue})});if(!re.ok){const _e=await re.json().catch(()=>({}));throw new Error(_e.error??"Failed to toggle tool")}ne(""),await oe()}catch(re){ne(re instanceof Error?re.message:String(re))}},de=async(he,De)=>{try{const Ue=await Se(`/api/mcp/servers/${encodeURIComponent(he)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabled:De})});if(!Ue.ok){const re=await Ue.json().catch(()=>({}));throw new Error(re.error??"Failed to toggle server")}ne(""),await oe()}catch(Ue){ne(Ue instanceof Error?Ue.message:String(Ue))}};return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Search Engine"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Configure a web search engine for the web_search tool."}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs font-medium text-text-primary mb-1",children:"Engine"}),i.jsx("div",{className:"flex gap-2",children:["","tavily","searxng"].map(he=>i.jsx("button",{onClick:()=>b(he),className:`px-3 py-1.5 rounded text-sm border transition-colors ${r===he?"bg-accent-primary/10 border-accent-primary text-accent-primary":"border-border text-text-muted hover:text-text-primary"}`,children:he||"Off"},he))})]}),r==="tavily"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs font-medium text-text-primary mb-1",children:"Tavily API Key"}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx(oi,{type:"password",value:l,onChange:he=>u(he.target.value),placeholder:"tvly-...",className:"flex-1"}),i.jsx(Ze,{variant:"secondary",onClick:E,style:y?{color:"rgb(63, 185, 80)"}:void 0,children:m})]}),x&&i.jsx("p",{className:"text-xs text-red-500 mt-1",children:x}),i.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["Get a free API key at"," ",i.jsx("a",{href:"https://app.tavily.com",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline",children:"tavily.com"})]})]}),r==="searxng"&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs font-medium text-text-primary mb-1",children:"SearXNG URL"}),i.jsx(oi,{type:"url",value:c,onChange:he=>d(he.target.value),placeholder:"http://localhost:4000",className:"w-full"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-xs font-medium text-text-primary mb-1",children:["API Key ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsx(oi,{type:"password",value:h,onChange:he=>p(he.target.value),placeholder:"Optional API key",className:"w-full"})]}),i.jsx(Ze,{variant:"secondary",onClick:j,style:S?{color:"rgb(63, 185, 80)"}:void 0,children:C}),_&&i.jsx("p",{className:"text-xs text-red-500",children:_})]})]})]}),L.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Shell"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Shell used to run agent commands and integrated terminals. Git Bash gives the agent a Unix-like toolset (grep, sed, ls…) and usually works better than cmd.exe."}),i.jsx("div",{className:"flex gap-2",children:L.map(he=>i.jsxs("button",{onClick:()=>n(Te.TOOLS_SHELL,he.id),disabled:!he.available,title:he.available?void 0:"Not found on this machine",className:`px-3 py-1.5 rounded text-sm border transition-colors ${P===he.id?"bg-accent-primary/10 border-accent-primary text-accent-primary":he.available?"border-border text-text-muted hover:text-text-primary":"border-border text-text-muted opacity-50 cursor-not-allowed"}`,children:[he.label,!he.available&&" (not found)"]},he.id))}),i.jsx("p",{className:"text-xs text-text-muted mt-2",children:"Applies to new commands and newly opened terminals. Running terminals keep their current shell."})]})]}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Token Optimization"}),i.jsxs("p",{className:"text-sm text-text-muted mb-3",children:["Reduce token consumption by filtering command output through RTK. See the"," ",i.jsx("a",{href:"https://github.com/rtk-ai/rtk",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline",children:"README"})," ","for installation."]}),i.jsxs("div",{className:"flex items-center justify-between py-2",children:[i.jsx("div",{className:"flex-1",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-text-primary",children:"Enable RTK auto-rewrite"}),T==="checking"&&i.jsx("span",{className:"text-xs text-text-muted animate-pulse",children:"checking…"}),T==="available"&&i.jsx("span",{className:"text-xs text-accent-success",children:"● installed"}),T==="unavailable"&&i.jsx("span",{className:"text-xs text-accent-error",children:"○ not found"})]})}),i.jsx(Yr,{enabled:e[Te.TOOLS_USE_RTK]==="true",onClick:()=>n(Te.TOOLS_USE_RTK,e[Te.TOOLS_USE_RTK]==="true"?"false":"true")})]})]}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Agent Confirmations"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Require confirmation for workspace changes and git mutations. When disabled, the agent proceeds without interruption."}),i.jsxs("div",{className:"flex items-center justify-between py-2",children:[i.jsx("div",{className:"flex-1",children:i.jsx("span",{className:"text-sm text-text-primary",children:"Confirm on workspace & git actions"})}),i.jsx(Yr,{enabled:e[Te.CONFIRM_ON_WORKSPACE_ACTIONS]==="true",onClick:()=>n(Te.CONFIRM_ON_WORKSPACE_ACTIONS,e[Te.CONFIRM_ON_WORKSPACE_ACTIONS]==="true"?"false":"true")})]})]}),i.jsx("hr",{className:"border-border"}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary","data-testid":"mcp-servers-heading",children:"MCP Servers"}),i.jsx(Ze,{variant:"primary",size:"sm",onClick:()=>G(!0),children:"+ Add Server"})]}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"MCP servers provide external tools that extend OpenFox's capabilities."}),i.jsxs("div",{className:"flex items-center justify-between py-2",children:[i.jsx("div",{className:"flex-1",children:i.jsx("span",{className:"text-sm text-text-primary",children:"Show per-conversation MCP toggle in chat bar"})}),i.jsx(Yr,{enabled:e[Te.FEATURES_PER_SESSION_MCP]==="true",onClick:()=>n(Te.FEATURES_PER_SESSION_MCP,e[Te.FEATURES_PER_SESSION_MCP]==="true"?"false":"true")})]}),Q&&i.jsx(Qa,{message:Q}),i.jsx(og,{loading:R,hasItems:W.length>0,loadingLabel:"Loading MCP servers...",emptyLabel:"No MCP servers configured.",children:W.map(he=>{const De=$.has(he.name)?xe(he.name,"delete")?i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:re=>{re.stopPropagation(),fe(he.name)},className:"px-2 py-1 rounded text-xs font-medium hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),i.jsx("button",{onClick:re=>{re.stopPropagation(),se()},className:"px-2 py-1 rounded text-xs text-text-muted hover:bg-bg-primary transition-colors",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:re=>{re.stopPropagation(),rt(he)},className:"px-2 py-1 rounded text-xs font-medium text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",children:"Edit"}),i.jsx("button",{onClick:re=>{re.stopPropagation(),te(he.name)},className:"px-2 py-1 rounded text-xs font-medium text-accent-error/80 hover:text-accent-error hover:bg-accent-error/10 transition-colors",children:"Remove"})]}):null,Ue=he.status==="error"&&he.error?i.jsx("span",{className:"text-xs text-accent-error truncate max-w-[200px]",title:he.error,children:he.error}):null;return i.jsx(wk,{server:he,expanded:$.has(he.name),onToggleExpand:Oe,serverToggleEnabled:!he.config.disabled,onServerToggle:()=>de(he.name,!he.config.disabled),tools:he.tools,onToolToggle:re=>{var _e;return ce(he.name,re,!((_e=he.tools.find(Le=>Le.name===re))!=null&&_e.enabled))},statusDot:Gg(he.status),statusColor:Vg(he.status),actions:i.jsxs(i.Fragment,{children:[Ue,De]})},he.name)})}),V&&i.jsx(wt,{isOpen:V,onClose:()=>{G(!1),ee("")},title:"Add MCP Server",size:"sm",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(kr,{label:"Name",value:M.name,onChange:he=>q({...M,name:he}),placeholder:"e.g. filesystem"}),i.jsx(xS,{formData:M,onChange:q}),z&&i.jsx(Qa,{message:z}),i.jsx(yS,{saving:K,saveLabel:"Add",savingLabel:"Adding...",onCancel:()=>{G(!1),ee(""),B(!1),q($e)},onSave:je})]})}),Z!==null&&i.jsx(wt,{isOpen:!0,onClose:()=>{X(null),ee("")},title:`Edit MCP Server: ${Z}`,size:"sm",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(xS,{formData:M,onChange:q}),z&&i.jsx(Qa,{message:z}),i.jsx(yS,{saving:K,saveLabel:"Save",savingLabel:"Saving...",onCancel:()=>{X(null),ee(""),B(!1),q($e)},onSave:Qe})]})})]})]})}const Ck="openfox_user_plugins";function z6(e){const t=e.match(/github\.com\/([^/]+)\/([^/]+?)(?:\/|$)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,"")}:null}async function np(e){const t=z6(e);if(!t)return null;try{const n=await fetch(`https://api.github.com/repos/${t.owner}/${t.repo}/releases/latest`,{signal:AbortSignal.timeout(5e3)});return n.ok?(await n.json()).tag_name??null:null}catch{return null}}function Tu(){try{return JSON.parse(localStorage.getItem(Ck)??"[]")}catch{return[]}}function bS(e){localStorage.setItem(Ck,JSON.stringify(e))}function H6({onAdd:e}){const[t,n]=N.useState(""),[r,a]=N.useState(""),[l,u]=N.useState(!1),c=d=>{d.preventDefault(),!(!t.trim()||!r.trim())&&(e({name:t.trim(),displayName:t.trim(),description:"User-added plugin",githubUrl:r.trim()}),n(""),a(""),u(!0),setTimeout(()=>u(!1),2e3))};return i.jsxs("form",{onSubmit:c,className:"flex gap-2 items-end",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),i.jsx("input",{type:"text",value:t,onChange:d=>n(d.target.value),placeholder:"my-plugin",className:"w-full px-2 py-1 text-sm text-text-primary bg-bg-tertiary border border-border rounded"})]}),i.jsxs("div",{className:"flex-[2]",children:[i.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"GitHub URL"}),i.jsx("input",{type:"text",value:r,onChange:d=>a(d.target.value),placeholder:"https://github.com/user/repo",className:"w-full px-2 py-1 text-sm text-text-primary bg-bg-tertiary border border-border rounded"})]}),i.jsx(Ze,{type:"submit",variant:"primary",size:"sm",children:l?"Added":"Add"})]})}function U6({plugin:e,initiallyInstalled:t,installedVersion:n,onRemove:r,onOpenFolder:a}){const[l,u]=N.useState(t?"installed":"idle"),[c,d]=N.useState(!1),[h,p]=N.useState(""),[m,x]=N.useState(n),[y,w]=N.useState(!1),[C,_]=N.useState(!1);N.useEffect(()=>{x(n)},[n]);const S=N.useCallback(async()=>{const P=await Se("/api/plugins/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({githubUrl:e.githubUrl})}),W=await P.json();if(P.ok)u("installed"),e.latestVersion&&x(e.latestVersion),W.loaded||p(W.loadError??"Plugin installed but failed to load");else throw new Error(W.error??"Install failed")},[e.githubUrl,e.name]),v=async()=>{u("installing"),p("");try{await S()}catch(P){u("error"),p(P instanceof Error?P.message:"Connection error")}},b=()=>{w(!0)},E=async()=>{_(!0);try{(await Se(`/api/plugins/${e.name}`,{method:"DELETE"})).ok&&(u("idle"),r(e.name))}catch{}_(!1),w(!1)},j=async()=>{d(!0),p("");try{await S()}catch(P){p(P instanceof Error?P.message:"Update failed")}d(!1)},T=m??n,D=e.latestVersion&&T&&T!=="unknown"&&e.latestVersion!==T,L=l==="installing"?"Installing…":c?"Updating…":l==="installed"?"Installed ✓":"Install",I=l==="installing"||l==="installed"||c;return i.jsxs("div",{className:"border border-border rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary",children:e.displayName}),i.jsxs("span",{className:"text-xs text-text-muted",children:["(",e.name,")"]})]}),i.jsx("p",{className:"text-xs text-text-muted mt-1",children:e.description}),i.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs",children:[e.githubUrl&&i.jsx("a",{href:e.githubUrl,target:"_blank",rel:"noreferrer",className:"text-accent-primary hover:underline",children:"GitHub"}),e.versionLoading?i.jsx("span",{className:"text-text-muted",children:"Loading version…"}):e.latestVersion?i.jsxs("span",{className:"text-text-muted",children:["v",e.latestVersion]}):null,T&&T!=="unknown"&&i.jsxs("span",{className:"text-text-muted",children:["installed: v",T]})]}),l==="error"&&h&&i.jsx("p",{className:"text-xs text-accent-error mt-1",children:h})]}),i.jsxs("div",{className:"flex flex-col items-end gap-1",children:[i.jsxs("div",{className:"flex gap-1",children:[e.githubUrl&&i.jsx(Ze,{variant:l==="installed"?"secondary":"primary",size:"sm",onClick:v,disabled:I,children:L}),D&&i.jsx(Ze,{variant:"primary",size:"sm",onClick:j,children:"Update"}),l==="installed"&&i.jsx(Ze,{variant:"danger",size:"sm",onClick:b,children:"Remove"})]}),l==="installed"&&i.jsx("button",{onClick:()=>a(e.name),className:"text-xs text-accent-primary hover:underline",children:"Open folder"})]})]}),i.jsx(Rl,{isOpen:y,onClose:()=>w(!1),onConfirm:E,title:`Remove "${e.displayName}"?`,message:`Remove the "${e.displayName}" plugin from your installation.`,confirmLabel:"Remove",confirmVariant:"danger",disabled:C})]})}function F6(){const[e,t]=N.useState([]),[n,r]=N.useState([]),[a,l]=N.useState({}),[u,c]=N.useState(!0),[d,h]=N.useState(""),[p,m]=N.useState("");N.useEffect(()=>{let S=!1;Promise.all([Se("/api/plugins/registry").then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}`);return b.json()}),Se("/api/plugins/installed").then(b=>b.ok?b.json():{installed:[]})]).then(([b,E])=>{if(S)return;const j={},T=E.installed;for(const W of T)j[W.name]=W.version;l(j);const D=b.plugins.map(W=>({...W,latestVersion:null,versionLoading:!0}));t(D),D.forEach(W=>{np(W.githubUrl).then(H=>{S||t(R=>R.map(U=>U.name===W.name?{...U,latestVersion:H,versionLoading:!1}:U))})});const L=new Set(D.map(W=>W.name)),I=Tu(),P=[];for(const W of T)!L.has(W.name)&&!I.some(H=>H.name===W.name)&&P.push({name:W.name,displayName:W.name,description:"Found on disk",githubUrl:"",latestVersion:null,versionLoading:!1});P.length>0&&r(W=>[...W,...P])}).catch(b=>{S||h(b instanceof Error?b.message:"Failed to load plugins")}).finally(()=>{S||c(!1)});const v=Tu();return v.length>0&&(r(v.map(b=>({...b,latestVersion:null,versionLoading:!0}))),v.forEach(b=>{np(b.githubUrl).then(E=>{S||r(j=>j.map(T=>T.name===b.name?{...T,latestVersion:E,versionLoading:!1}:T))})})),()=>{S=!0}},[]);const x=async S=>{try{S?await Se(`/api/plugins/${S}/open-folder`):await Se("/api/plugins/open-folder")}catch{}},y=N.useCallback(S=>{l(E=>{const j={...E};return delete j[S],j});const v=Tu(),b=v.filter(E=>E.name!==S);b.length!==v.length&&bS(b),r(E=>E.filter(j=>j.name!==S))},[]),w=N.useCallback(S=>{if(new Set(e.map(E=>E.name)).has(S.name)){m(`"${S.displayName}" is already listed in the registry and won't be added again.`);return}const b=Tu();bS([...b,S]),r(E=>[...E,{...S,latestVersion:null,versionLoading:!0}]),np(S.githubUrl).then(E=>{r(j=>j.map(T=>T.name===S.name?{...T,latestVersion:E,versionLoading:!1}:T))})},[e]),C=new Set,_=[...e,...n].filter(S=>C.has(S.name)?!1:(C.add(S.name),!0));return u?i.jsx("div",{className:"text-sm text-text-muted",children:"Loading plugins..."}):i.jsxs("div",{className:"space-y-4",children:[d&&i.jsxs("div",{className:"text-sm text-accent-error bg-accent-error/10 border border-accent-error/30 rounded-lg p-3",children:["Failed to load plugin registry: ",d]}),p&&i.jsxs("div",{className:"text-sm text-accent-warning bg-accent-warning/10 border border-accent-warning/30 rounded-lg p-3 flex justify-between items-center",children:[i.jsx("span",{children:p}),i.jsx("button",{onClick:()=>m(""),className:"text-text-muted hover:text-text-primary ml-2",children:"×"})]}),i.jsxs("div",{className:"border border-border rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-medium text-text-primary mb-3",children:"Add Plugin"}),i.jsx(H6,{onAdd:w})]}),_.length===0&&!d&&i.jsx("div",{className:"text-sm text-text-muted",children:"No plugins found."}),_.map(S=>i.jsx(U6,{plugin:S,initiallyInstalled:S.name in a,installedVersion:a[S.name]??null,onRemove:y,onOpenFolder:x},S.name))]})}function V6({isOpen:e,onClose:t}){const[n,r]=N.useState("instructions"),a=Cs(u=>u.status==="available"),l=()=>{try{Pt.send("context.checkDynamic",{})}catch{}t()};return i.jsx(wt,{isOpen:e,onClose:l,title:"Settings",size:"xl",minHeight:"500px",children:i.jsxs("div",{"data-global-settings":!0,className:"flex flex-col h-full",children:[i.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1 overflow-x-auto scrollbar-hide",children:[i.jsx(Zs,{label:"Instructions",active:n==="instructions",onClick:()=>r("instructions")}),i.jsx(Zs,{label:"Tools",active:n==="tools",onClick:()=>r("tools")}),i.jsx(Zs,{label:"Skills",active:n==="skills",onClick:()=>r("skills")}),i.jsx(Zs,{label:"Plugins",active:n==="plugins",onClick:()=>r("plugins")}),i.jsx(Zs,{label:"Notifications",active:n==="notifications",onClick:()=>r("notifications")}),i.jsx(Zs,{label:"Display",active:n==="display",onClick:()=>r("display")}),i.jsx(Zs,{label:"Keybindings",active:n==="keybindings",onClick:()=>r("keybindings")}),i.jsx(Zs,{label:"Advanced",active:n==="advanced",onClick:()=>r("advanced"),showDot:a})]}),n==="instructions"&&i.jsx(MT,{isOpen:e}),n==="skills"&&i.jsx(IT,{isOpen:e}),n==="plugins"&&i.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:i.jsx(F6,{})}),n==="notifications"&&i.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:i.jsx(CT,{})}),n==="display"&&i.jsx(HT,{}),n==="keybindings"&&i.jsx(B6,{}),n==="tools"&&i.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:i.jsx($6,{})}),n==="advanced"&&i.jsx(I6,{onClose:t})]})})}function Zs({label:e,active:t,onClick:n,showDot:r}){return i.jsxs("button",{onClick:n,className:`relative px-4 py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${t?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:[e,r&&i.jsx("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-accent-primary"})]})}var rp={exports:{}},vS;function G6(){return vS||(vS=1,(function(e,t){(function(n,r){e.exports=r()})(globalThis,(()=>(()=>{var n={4567:function(u,c,d){var h=this&&this.__decorate||function(v,b,E,j){var T,D=arguments.length,L=D<3?b:j===null?j=Object.getOwnPropertyDescriptor(b,E):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(v,b,E,j);else for(var I=v.length-1;I>=0;I--)(T=v[I])&&(L=(D<3?T(L):D>3?T(b,E,L):T(b,E))||L);return D>3&&L&&Object.defineProperty(b,E,L),L},p=this&&this.__param||function(v,b){return function(E,j){b(E,j,v)}};Object.defineProperty(c,"__esModule",{value:!0}),c.AccessibilityManager=void 0;const m=d(9042),x=d(9924),y=d(844),w=d(4725),C=d(2585),_=d(3656);let S=c.AccessibilityManager=class extends y.Disposable{constructor(v,b,E,j){super(),this._terminal=v,this._coreBrowserService=E,this._renderService=j,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let T=0;T<this._terminal.rows;T++)this._rowElements[T]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[T]);if(this._topBoundaryFocusListener=T=>this._handleBoundaryFocus(T,0),this._bottomBoundaryFocusListener=T=>this._handleBoundaryFocus(T,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new x.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((T=>this._handleResize(T.rows)))),this.register(this._terminal.onRender((T=>this._refreshRows(T.start,T.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((T=>this._handleChar(T)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
@@ -272,7 +272,7 @@ WARNING: This link could potentially be dangerous`)){const S=window.open();if(S)
272
272
  * Copyright (c) 2011 Fabrice Bellard
273
273
  */var q6=2,K6=1,Y6=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var m;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((m=this._terminal.options.overviewRuler)==null?void 0:m.width)||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),a=Math.max(0,parseInt(n.getPropertyValue("width"))),l=window.getComputedStyle(this._terminal.element),u={top:parseInt(l.getPropertyValue("padding-top")),bottom:parseInt(l.getPropertyValue("padding-bottom")),right:parseInt(l.getPropertyValue("padding-right")),left:parseInt(l.getPropertyValue("padding-left"))},c=u.top+u.bottom,d=u.right+u.left,h=r-c,p=a-d-t;return{cols:Math.max(q6,Math.floor(p/e.css.cell.width)),rows:Math.max(K6,Math.floor(h/e.css.cell.height))}}};function X6({sessionId:e,onClose:t,onEscape:n,autoFocus:r}){const a=N.useRef(null),l=N.useRef(e),u=N.useRef(null),c=N.useRef(null),d=Dr(p=>p.writeSession),h=Dr(p=>p.resizeSession);return N.useEffect(()=>{l.current=e},[e]),N.useEffect(()=>{if(!n)return;const p=m=>{m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),n())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n]),N.useEffect(()=>{if(!a.current)return;const p=new W6.Terminal({fontFamily:'"JetBrains Mono", monospace',fontSize:13,theme:{background:"#1a1a1a",foreground:"#e0e0e0",cursor:"#ffffff",cursorAccent:"#1a1a1a"},cursorBlink:!0,cursorStyle:"bar",convertEol:!0}),m=new Y6;p.loadAddon(m),u.current={term:p,fitAddon:m},a.current.addEventListener("keydown",C=>{C.key==="Escape"&&n&&(C.preventDefault(),C.stopPropagation(),n())}),p.open(a.current);const x=a.current.querySelector(".xterm");x&&(x.style.padding="8px"),m.fit(),r&&setTimeout(()=>{p.focus()},150);const y=new ResizeObserver(()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{requestAnimationFrame(()=>{var _;m.fit&&m.fit();const C=(_=u.current)==null?void 0:_.term;C&&C.cols>0&&C.rows>0&&h(l.current,C.cols,C.rows)})},100)});y.observe(a.current),p.onData(C=>{if(C==="\x1B"&&n){n();return}d(l.current,C)}),p.onKey(C=>{C.key==="\x1B"&&n&&(C.domEvent.stopPropagation(),n())});const w=Pt.subscribe(C=>{const _=C.payload;if(C.type==="terminal.output"&&(_==null?void 0:_.sessionId)===l.current){const S=_==null?void 0:_.data;S&&p.write(S)}});return()=>{w(),y.disconnect(),c.current&&clearTimeout(c.current),p.dispose(),u.current=null}},[e,d,h]),i.jsxs("div",{className:"flex flex-col h-full bg-[#1a1a1a]",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-2 py-1 bg-[#252525] border-b border-[#333]",children:[i.jsx("div",{}),i.jsx("button",{onClick:t,className:"p-1 rounded hover:bg-[#333] text-[#888] hover:text-[#ccc] transition-colors",title:"Close terminal",children:i.jsx(rg,{})})]}),i.jsx("div",{ref:a,className:"flex-1 relative overflow-hidden",tabIndex:0,onKeyDown:p=>{p.key==="Escape"&&n&&(p.preventDefault(),p.stopPropagation(),n())}})]})}const Ek="openfox-chat-textarea";function Ul(e){const t=document.getElementById(Ek);t&&(e===void 0?t.focus():t.focus({preventScroll:e}))}function Q6(e){return e===1?"grid-cols-1":e===2?"grid-cols-1 lg:grid-cols-2":"grid-cols-1 lg:grid-cols-2 xl:grid-cols-3"}function J6({isOpen:e,onClose:t}){const n=Dr(C=>C.createSession),r=Dr(C=>C.killSession),a=Dr(C=>C.sessions),l=Dr(C=>C.setWorkdir),u=Dr(C=>C.fetchSessions),c=Ft(C=>C.currentProject),d=Re(C=>C.currentSession),[h,p]=N.useState(!0),m=N.useRef(null),x=N.useRef(!1),y=N.useRef(!1),w=N.useCallback(()=>{t()},[t]);return N.useEffect(()=>{const C=(d==null?void 0:d.workspace)??(c==null?void 0:c.workdir);C&&l(C)},[d==null?void 0:d.workspace,c==null?void 0:c.workdir,l]),N.useEffect(()=>{e?(p(!0),u(c==null?void 0:c.id).finally(()=>p(!1))):Ul()},[e,u,c==null?void 0:c.id]),N.useEffect(()=>{e&&a.length===0&&!h&&!y.current&&(y.current=!0,n(void 0,(d==null?void 0:d.projectId)??(c==null?void 0:c.id)))},[e,a.length,h,n,d==null?void 0:d.projectId,c==null?void 0:c.id]),N.useEffect(()=>{e?(x.current=!0,setTimeout(()=>{var C;(C=m.current)==null||C.focus(),setTimeout(()=>{x.current=!1},200)},100)):y.current=!1},[e]),N.useEffect(()=>{if(!e)return;const C=_=>{x.current||_.key==="Escape"&&(_.preventDefault(),t())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e,t]),e?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-x-0 top-[50vh] bottom-0 z-[100] bg-black/40",style:{pointerEvents:"auto"},onClick:w}),i.jsxs("div",{ref:m,tabIndex:-1,className:"fixed inset-x-0 top-0 z-[100] h-[50vh] bg-bg-primary border-b border-border flex flex-col animate-slide-down outline-none",onClick:C=>C.stopPropagation(),onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),w())},children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border",children:[i.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Terminal"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>n(void 0,(d==null?void 0:d.projectId)??(c==null?void 0:c.id)),className:"p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"New terminal",children:i.jsx(oT,{})}),i.jsx("button",{onClick:t,className:"p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Close (Esc)",children:i.jsx(js,{})})]})]}),i.jsx("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:h?i.jsx("div",{className:"flex items-center justify-center h-full text-text-muted",children:"Loading..."}):a.length===0?i.jsx("div",{className:"flex items-center justify-center h-full text-text-muted",children:i.jsxs("div",{className:"text-center",children:[i.jsx("p",{className:"mb-4",children:"No terminal sessions"}),i.jsx("button",{onClick:()=>n(void 0,(d==null?void 0:d.projectId)??(c==null?void 0:c.id)),className:"px-4 py-2 bg-accent-primary/25 text-text-primary rounded hover:bg-accent-primary/40 transition-colors",children:"Create Terminal"})]})}):i.jsx("div",{className:`grid ${Q6(a.length)} gap-2 h-full auto-rows-fr`,children:a.map(C=>i.jsx(X6,{sessionId:C.id,onClose:()=>r(C.id),onEscape:w,autoFocus:a.length===1},C.id))})})]})]}):null}function Zl({items:e,footerItems:t=[],trigger:n,minWidth:r="120px",isOpen:a,onOpenChange:l}){const[u,c]=N.useState(!1),d=a!==void 0,h=d?a:u,p=R=>{if(d){const U=typeof R=="function"?R(u):R;l==null||l(U)}else c(R)},[m,x]=N.useState(null),y=N.useRef(null),w=N.useRef(null),[C,_]=N.useState(0),S=N.useRef(0),v=N.useMemo(()=>[...e,...t],[e,t]),b=N.useRef(v),E=N.useCallback(()=>{if(!y.current)return;const R=y.current.getBoundingClientRect(),U=200,G=window.innerHeight-R.bottom<U;x({top:G?R.top-U-4:R.bottom+4,left:R.left,alignToTop:G})},[]);N.useEffect(()=>{b.current=v},[v]),N.useEffect(()=>{function R(U){if(w.current){const V=U.target;w.current.contains(V)||p(!1)}}return h&&document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R)}},[h]),N.useEffect(()=>{h&&E()},[h,E]),N.useEffect(()=>{if(!h)return;setTimeout(()=>{var U;(U=w.current)==null||U.focus()},0);function R(U){const V=b.current,G=V.filter(X=>!j(X)),Z=T(S.current,V);switch(U.key){case"ArrowDown":if(U.preventDefault(),U.stopPropagation(),Z<G.length-1){const X=D(S.current+1,V);S.current=X,_(X)}break;case"ArrowUp":if(U.preventDefault(),U.stopPropagation(),Z>0){const X=L(S.current-1,V);S.current=X,_(X)}break;case"Enter":U.preventDefault(),U.stopPropagation(),I(S.current,V);break;case"Escape":U.preventDefault(),U.stopPropagation(),p(!1);break}}return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[h,v]);function j(R){var G;const U=R.label;return U?String(((G=U.props)==null?void 0:G.className)??"").includes("cursor-default"):!1}function T(R,U){let V=0;for(let G=0;G<R;G++){const Z=U[G];Z&&!j(Z)&&V++}return V}function D(R,U){for(let V=R;V<U.length;V++){const G=U[V];if(G&&!j(G))return V}return R}function L(R,U){for(let V=R;V>=0;V--){const G=U[V];if(G&&!j(G))return V}return R}function I(R,U){var G;const V=U[R];!V||j(V)||((G=V.onClick)==null||G.call(V),V.href&&(window.history.pushState(null,"",V.href),window.dispatchEvent(new PopStateEvent("popstate"))),p(!1))}N.useEffect(()=>{h&&(_(v.findIndex(R=>!j(R))),S.current=v.findIndex(R=>!j(R)))},[h,v]);const P=R=>{R.stopPropagation(),h||E(),p(!h)};function W(R,U,V,G){const X=!j(R)&&G===C,$=i.jsxs(i.Fragment,{children:[R.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0",children:R.icon}),R.label]}),O=U!==V-1;return R.href?i.jsx(Jn,{href:R.href,onClick:M=>{var q;(q=R.onClick)==null||q.call(R,M),p(!1)},onAuxClick:()=>p(!1),className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${R.danger?"text-accent-error hover:bg-accent-error/10":X?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"} ${O?"border-b border-border":""}`,children:$},G):i.jsx("button",{onClick:M=>{var q;(q=R.onClick)==null||q.call(R,M),R.closeOnClick!==!1&&p(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${R.danger?"text-accent-error hover:bg-accent-error/10":X?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"} ${O?"border-b border-border":""}`,children:$},G)}const H=m&&i.jsxs("div",{ref:w,"data-testid":"session-dropdown-menu",className:`fixed bg-bg-secondary border border-border rounded shadow-lg z-50 ${m.alignToTop?"mb-1":"mt-1"}`,style:{top:m.top,left:m.left,minWidth:r},tabIndex:-1,children:[i.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:e.map((R,U)=>W(R,U,e.length,U))}),t.length>0&&i.jsx("div",{className:"border-t border-border",children:t.map((R,U)=>W(R,U,t.length,e.length+U))})]});return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"relative",children:i.jsx("div",{ref:y,onClick:P,children:n})}),h&&di.createPortal(H,document.body)]})}function Z6(e){return!e||e.trim()===""?{valid:!1,error:"Project name cannot be empty"}:/^[a-zA-Z0-9._-]+$/.test(e)?{valid:!0}:{valid:!1,error:"Project name can only contain letters, numbers, hyphens, underscores, and dots"}}function jk({isOpen:e,onClose:t,path:n,onRetry:r}){const[a,l]=N.useState(!1),[u,c]=N.useState(null),[d,h]=N.useState(null);N.useEffect(()=>{e&&p()},[e]);const p=async()=>{try{const E=await(await Se("/api/projects/check-permissions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})})).json();h({sudoAvailable:E.sudoAvailable,userInGroup:E.userInGroup,groupHasWrite:E.groupHasWrite,groupName:E.groupName||null})}catch{h({sudoAvailable:!1,userInGroup:!1,groupHasWrite:!1,groupName:null})}},m=N.useCallback(async b=>{l(!0),c(null);try{const j=await(await Se("/api/projects/fix-permissions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n,action:b})})).json();j.success?(r(),t()):j.sudoAvailable?c("Failed to fix permissions: "+(j.error||"Unknown error")):c(`Passwordless sudo is not available. Please fix permissions manually:
274
274
 
275
- `+(b==="group"?`sudo chmod g+w "${n}"`:"sudo usermod -aG <group> $USER"))}catch(E){c("Failed to fix permissions: "+(E instanceof Error?E.message:"Unknown error"))}finally{l(!1)}},[n,r,t]),x=(d==null?void 0:d.userInGroup)??!1,y=(d==null?void 0:d.groupHasWrite)??!1,w=(d==null?void 0:d.sudoAvailable)??!1,C=(d==null?void 0:d.groupName)??"",_=x&&!y,S=!x&&y,v=!x&&!y;return i.jsx(wt,{isOpen:e,onClose:t,title:"Permission Denied",size:"sm",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"text-sm text-text-secondary",children:[i.jsx("p",{children:_?i.jsxs(i.Fragment,{children:["The group ",i.jsx("strong",{children:C})," doesn't have write access:"]}):S?i.jsxs(i.Fragment,{children:["You're not a member of group ",i.jsx("strong",{children:C}),":"]}):i.jsxs(i.Fragment,{children:["You're not a member of group ",i.jsx("strong",{children:C})," and it doesn't have write access:"]})}),i.jsx("p",{className:"mt-2 font-mono text-xs bg-bg-tertiary p-2 rounded break-all",children:n})]}),u?i.jsx("div",{className:"p-3 bg-accent-error/10 border border-accent-error/30 rounded text-sm text-accent-error whitespace-pre-wrap",children:u}):d?i.jsxs("div",{className:"flex flex-col gap-2",children:[_&&i.jsxs(i.Fragment,{children:[i.jsx(Ze,{type:"button",variant:"primary",onClick:()=>m("group"),disabled:a||!w,className:"w-full",children:a?"Granting access...":"Extend group permissions"}),i.jsx("div",{className:"text-xs text-text-secondary",children:"Or manually execute:"}),i.jsxs("code",{className:"text-xs text-text-muted p-2 bg-bg-tertiary rounded break-all",children:['sudo chmod g+w "',n,'"']})]}),S&&i.jsxs(i.Fragment,{children:[i.jsx(Ze,{type:"button",variant:"primary",onClick:()=>m("join_group"),disabled:a||!w,className:"w-full",children:a?"Joining group...":"Join group"}),i.jsx("div",{className:"text-xs text-text-secondary",children:"Or manually execute:"}),i.jsxs("code",{className:"text-xs text-text-muted p-2 bg-bg-tertiary rounded break-all",children:["sudo usermod -aG ",C," $USER"]})]}),v&&i.jsxs(i.Fragment,{children:[i.jsx(Ze,{type:"button",variant:"primary",onClick:()=>m("join_group_and_group"),disabled:a||!w,className:"w-full",children:a?"Joining group...":"Join group & grant write permissions"}),i.jsx("div",{className:"text-xs text-text-secondary",children:"Or manually execute:"}),i.jsxs("code",{className:"text-xs text-text-muted p-2 bg-bg-tertiary rounded break-all",children:["sudo usermod -aG ",C," $USER",i.jsx("br",{}),'sudo chmod g+w "',n,'"']})]}),!w&&!u&&i.jsxs("div",{className:"text-xs text-text-secondary",children:[i.jsx("p",{children:"Passwordless sudo is not available. Please fix permissions manually:"}),i.jsxs("code",{className:"block mt-1 p-2 bg-bg-tertiary rounded break-all",children:['sudo chmod g+w "',n,'"']})]}),i.jsx("div",{className:"flex justify-end",children:i.jsx(Ze,{type:"button",variant:"secondary",onClick:t,disabled:a,children:"Cancel"})})]}):null]})})}function Nk({isOpen:e,onClose:t}){const[,n]=Ln(),r=Ft(j=>j.listProjects),[a,l]=N.useState(""),[u,c]=N.useState(null),[d,h]=N.useState(!1),[p,m]=N.useState(""),[x,y]=N.useState(null),w=N.useRef(null);N.useEffect(()=>{e&&(Se("/api/config").then(j=>j.json()).then(j=>{j.workdir&&m(j.workdir)}),l(""),c(null),h(!1),y(null),setTimeout(()=>{var j;(j=w.current)==null||j.focus()},100))},[e]);const C=N.useCallback(async j=>{j.preventDefault();const T=Z6(a);if(!T.valid){c(T.error);return}const D=`${p}/${a}`;await v(D)},[a,n,t,p]),_=N.useCallback(()=>{y(null)},[]),S=N.useCallback(async()=>{const j=`${p}/${a}`;await v(j)},[p,a,n,t,y,c,h]);async function v(j){h(!0),c(null),y(null);try{const T=await Se("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,workdir:j})});if(!T.ok){const I=await T.json().catch(()=>({}));if(I.code==="EACCES"){y(j),h(!1);return}throw new Error(I.error||"Failed to create project")}const L=(await T.json()).project;t(),await r(),n(`/p/${L.id}`)}catch(T){c(T instanceof Error?T.message:"Failed to create project"),h(!1)}}const b=N.useCallback(()=>{l(""),c(null),t()},[t]),E=a?`${p}/${a}`:"";return i.jsxs(i.Fragment,{children:[i.jsx(wt,{isOpen:e,onClose:b,title:"Create New Project",size:"sm",children:i.jsxs("form",{onSubmit:C,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"project-name",className:"block text-sm font-medium text-text-secondary mb-2",children:"Project Name"}),i.jsx(oi,{ref:w,id:"project-name",value:a,onChange:j=>{l(j.target.value),c(null)},placeholder:"my-project",disabled:d,"data-testid":"create-project-name-input",className:"w-full"}),a&&i.jsxs("div",{className:"mt-2 text-xs text-text-muted",children:["Full path: ",i.jsx("span",{className:"font-mono",children:E})]}),u&&i.jsx("div",{className:"mt-3 p-3 bg-accent-error/10 border border-accent-error/30 rounded text-sm text-accent-error",children:u})]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ze,{type:"button",variant:"secondary",onClick:b,disabled:d,children:"Cancel"}),i.jsx(Ze,{type:"submit",variant:"primary",disabled:d||!a.trim(),"data-testid":"create-project-submit-button",className:"min-w-[100px]",children:d?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Es,{className:"h-4 w-4"}),"Creating..."]}):"Create"})]})]})}),x&&i.jsx(jk,{isOpen:!!x,onClose:_,path:x,onRetry:S})]})}function Tk(){const[e,t]=N.useState(null);return N.useEffect(()=>{Se("/api/config").then(n=>n.json()).then(n=>{n.workdir&&t(n.workdir)})},[]),e}function _S({projects:e,currentProject:t}){const[,n]=Ln(),r=Ft(_=>_.loadProject),a=Ft(_=>_.toggleStar),l=Ft(_=>_.createProject),u=Ft(_=>_.listProjects),[c,d]=N.useState(!1),[h,p]=N.useState(!1),m=Tk(),x=N.useCallback(async _=>{const S=P1(_),v=await l(S,_);return v&&"id"in v?(await u(),p(!1),n(`/p/${v.id}`),!0):!1},[l,u,n]),w=N.useMemo(()=>{const _=e.filter(v=>v.isStarred).sort((v,b)=>v.name.localeCompare(b.name)),S=e.filter(v=>!v.isStarred).sort((v,b)=>v.name.localeCompare(b.name));return[..._,...S]},[e]).map(_=>({label:i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[i.jsx("span",{className:"truncate flex-1",children:_.name}),i.jsx("button",{onClick:S=>{S.stopPropagation(),S.preventDefault(),S.nativeEvent.stopImmediatePropagation(),a(_.id,!_.isStarred)},className:"flex-shrink-0 p-1 hover:bg-bg-tertiary rounded transition-colors",title:_.isStarred?"Unstar project":"Star project",children:_.isStarred?i.jsx(N1,{className:"w-3.5 h-3.5 text-yellow-500"}):i.jsx(T1,{className:"w-3.5 h-3.5 text-text-muted hover:text-yellow-500"})})]}),icon:_.id===(t==null?void 0:t.id)?i.jsx(Pr,{}):void 0,href:`/p/${_.id}`,closeOnClick:!0,onClick:()=>{r(_.id)}})),C=[{label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Or,{className:"w-4 h-4"}),i.jsx("span",{children:"Open Project"})]}),onClick:()=>p(!0)},{label:i.jsxs("div",{className:"flex items-center gap-2 text-accent-primary",children:[i.jsx(Es,{className:"w-4 h-4"}),i.jsx("span",{children:"New Project"})]}),onClick:()=>d(!0)}];return i.jsxs(i.Fragment,{children:[i.jsx(Zl,{items:w,footerItems:C,trigger:i.jsxs("button",{className:`text-text-secondary hover:text-text-primary text-sm truncate flex items-center gap-1 ${t?"hover:underline":""}`,title:(t==null?void 0:t.name)??"Select project",children:[(t==null?void 0:t.name)??i.jsx("span",{className:"text-text-muted",children:"Select project..."}),i.jsx(yn,{})]}),minWidth:"250px"}),c&&i.jsx(Nk,{isOpen:c,onClose:()=>d(!1)}),h&&i.jsx(Cd,{initialPath:m??void 0,onSelect:x,onClose:()=>p(!1)})]})}function Ak(e){const t=new Date(e),r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),u=String(t.getDate()).padStart(2,"0");return`${r} ${a}/${l}/${u}`}function Gd(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}:${r}`}function eB(e){const t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),a=new Date(t.getFullYear(),t.getMonth(),t.getDate()),l=Math.floor((r.getTime()-a.getTime())/(1e3*60*60*24)),u=Gd(e);if(l===0)return`today ${u}`;if(l===1)return`yesterday ${u}`;if(l<7)return`${l} days ago ${u}`;{const c=t.getFullYear(),d=String(t.getMonth()+1).padStart(2,"0"),h=String(t.getDate()).padStart(2,"0");return`${c}/${d}/${h} ${u}`}}function Lk(e){const t=new Date(e);return{year:t.getFullYear(),month:String(t.getMonth()+1).padStart(2,"0"),day:String(t.getDate()).padStart(2,"0")}}function tB(e){const{year:t,month:n,day:r}=Lk(e);return`${t}-${n}-${r}`}function Dk(e){const t=new Map;for(const a of e){const l=tB(a.updatedAt);t.has(l)||t.set(l,[]),t.get(l).push(a)}for(const[a,l]of t)l.sort((u,c)=>{const d=new Date(u.updatedAt).getTime();return new Date(c.updatedAt).getTime()-d});const n=Array.from(t.keys()).sort((a,l)=>l.localeCompare(a)),r=new Map;for(const a of n)r.set(a,t.get(a));return r}function nB(e){const{year:t,month:n,day:r}=Lk(e);return`${t}/${n}/${r} ${Gd(e)}`}function dd(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function rB({sessions:e,currentProject:t,currentSession:n,isOpen:r,onOpenChange:a}){var x;const l=Re(y=>y.loadSession),u=50,c=e.filter(y=>y.projectId===t.id).slice(0,15),d=Dk(c),h=N.useMemo(()=>{const y=[];y.push({label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Es,{className:"w-4 h-4 text-accent-primary"}),i.jsx("span",{className:"text-sm",children:"New session"})]}),href:`/p/${t.id}/new`,onClick:()=>{}});for(const[w,C]of d){const _=C[0];if(_){y.push({label:i.jsx("div",{className:"px-3 py-2 text-text-muted text-xs font-medium cursor-default",children:Ak(_.updatedAt)}),onClick:()=>{}});for(const S of C)y.push({label:i.jsxs("div",{className:"min-w-[160px]",children:[i.jsx("div",{className:"truncate text-sm",children:dd(S.title??S.id.slice(0,8),u)}),i.jsx("div",{className:"text-text-muted text-xs",children:Gd(S.updatedAt)})]}),icon:S.id===(n==null?void 0:n.id)?i.jsx(Pr,{}):void 0,href:`/p/${t.id}/s/${S.id}`,onClick:()=>{l(S.id)}})}}return y},[t.id,d,n==null?void 0:n.id]),p=((x=n==null?void 0:n.metadata)==null?void 0:x.title)??(n?n.id.slice(0,8):null),m=p?dd(p,u):"No session selected";return i.jsx(Zl,{items:h,isOpen:r,onOpenChange:a,trigger:i.jsxs("button",{className:"text-text-secondary hover:text-text-primary hover:underline text-sm truncate flex items-center gap-1",title:p??"","data-testid":"header-session-dropdown",children:[m,i.jsx(yn,{})]}),minWidth:"280px"})}function sB({items:e,trigger:t,isActive:n=!1}){const[r,a]=N.useState(!1),l=N.useRef(null);return N.useEffect(()=>{function u(c){l.current&&!l.current.contains(c.target)&&a(!1)}if(r)return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),i.jsxs("div",{className:"relative",ref:l,children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),className:`flex items-center gap-1 px-1.5 py-0.5 rounded transition-colors ${n?"bg-bg-tertiary":"hover:bg-bg-tertiary"}`,children:[typeof t=="string"?i.jsx("span",{className:"text-sm text-text-secondary font-medium",children:t}):t,i.jsx(yn,{className:"w-3 h-3 text-text-muted flex-shrink-0 transition-transform",rotate:r?180:0})]}),r&&e.length>0&&i.jsx("div",{className:"absolute top-full left-0 mt-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:e.map((u,c)=>{const d=u.label&&typeof u.label=="object"&&u.label.type===Jn?u.label:null;if(d){const h=d.props.href||"";return i.jsxs(Jn,{href:h,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[u.icon,d.props.children]},c)}return u.href?i.jsxs("a",{href:u.href,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[u.icon,u.label]},c):i.jsxs("button",{type:"button",onClick:()=>{var h;(h=u.onClick)==null||h.call(u),a(!1)},className:"flex items-center gap-2 px-3 py-2 text-sm w-full text-left border-b border-border hover:bg-bg-tertiary transition-colors",children:[u.icon,u.label]},c)})})]})}function iB({currentProject:e,sessions:t,currentSession:n,projectIdFromUrl:r}){if(!(e!=null&&e.id)||e.id!==r)return null;const a=t.filter(u=>u.projectId===e.id).sort((u,c)=>new Date(c.updatedAt).getTime()-new Date(u.updatedAt).getTime()).slice(0,5),l=[{label:i.jsxs(Jn,{href:`/p/${e.id}/new`,className:"flex items-center gap-2",children:[i.jsx(Es,{className:"w-3 h-3 text-accent-primary"}),i.jsx("span",{className:"text-sm",children:"New Session"})]})},...a.map(u=>({label:i.jsx(Jn,{href:`/p/${e.id}/s/${u.id}`,className:"flex items-center gap-2 truncate text-sm",children:i.jsx("span",{children:dd(u.title??u.id.slice(0,8),50)})}),icon:u.id===(n==null?void 0:n.id)?i.jsx(Pr,{className:"w-3 h-3"}):void 0})),{label:i.jsxs(Jn,{href:"/",className:"flex items-center gap-2 text-text-muted hover:text-text-primary",children:[i.jsx(eT,{className:"w-3 h-3"}),i.jsx("span",{className:"text-sm",children:"Projects"})]})}];return i.jsx(sB,{items:l,trigger:i.jsx("span",{className:"text-sm text-text-secondary font-medium",children:e.name})})}function aB({onMenuClick:e,onCriteriaToggle:t}){const[n,r]=N.useState(!1),[a,l]=N.useState(!1),[u,c]=N.useState(!!document.fullscreenElement),[d,h]=Ln();N.useEffect(()=>{const D=()=>c(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",D),()=>document.removeEventListener("fullscreenchange",D)},[]);const p=d.startsWith("/p/"),m=/^\/p\/[^/]+\/s\/[^/]+$/.test(d),x=Re(D=>D.currentSession),y=Re(D=>D.sessions),w=Ft(D=>D.currentProject),C=Ft(D=>D.projects),_=Qt(D=>D.startAutoRefresh),S=Qt(D=>D.stopAutoRefresh),v=Dr(D=>D.setOpen),b=Dr(D=>D.isOpen),E=Cs(D=>D.status==="available"),j=Cs(D=>D.check);N.useEffect(()=>{Cs.getState().status==="idle"&&j()},[j]),N.useEffect(()=>{const D=()=>l(!0);return window.addEventListener("open-session-dropdown",D),()=>window.removeEventListener("open-session-dropdown",D)},[]);const T=Gl();return Dl(T.terminalToggle,()=>{Dr.getState().toggleOpen()},{capture:!0}),N.useEffect(()=>(_(),()=>S()),[_,S]),i.jsxs("header",{className:"h-8 bg-secondary border-b border-border flex items-center justify-between px-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e&&m&&i.jsx("button",{onClick:e,className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:T.sessionSearch?`Toggle session list (${qu(T.sessionSearch)})`:"Toggle session list",children:i.jsx(j_,{})}),i.jsx(Jn,{href:"/",className:"text-accent-primary font-semibold text-sm hover:underline flex-shrink-0 hidden md:inline",children:"OpenFox"}),w&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),i.jsx("span",{className:"hidden md:inline",children:i.jsx(_S,{projects:C,currentProject:w})}),i.jsx("span",{className:"md:hidden",children:i.jsx(iB,{currentProject:w,sessions:y,currentSession:x,projectIdFromUrl:p&&d.split("/")[2]||null},w==null?void 0:w.id)}),i.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),i.jsx("span",{className:"hidden md:inline",children:i.jsx(rB,{sessions:y,currentProject:w,currentSession:x,isOpen:a,onOpenChange:l})})]}),!w&&i.jsx("span",{className:"hidden md:inline",children:i.jsx(_S,{projects:C})})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[m&&i.jsx("button",{onClick:()=>{var D,L,I;document.fullscreenElement?(D=document.exitFullscreen)==null||D.call(document):(I=(L=document.documentElement).requestFullscreen)==null||I.call(L)},className:"max-sm:block hidden p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:u?"Exit fullscreen":"Enter fullscreen",children:u?i.jsx(rT,{}):i.jsx(sT,{})}),p&&i.jsx("button",{onClick:()=>v(!b),className:`p-2.5 rounded hover:bg-bg-tertiary transition-colors ${b?"text-accent-primary":"text-text-muted hover:text-text-primary"}`,title:"Toggle terminal (double Ctrl)",children:i.jsx(dT,{})}),i.jsxs("button",{onClick:()=>r(!0),className:"relative p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:E?"Settings — update available":"Settings",children:[i.jsx(lT,{}),E&&i.jsx("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-accent-primary"})]}),i.jsx("button",{onClick:()=>{localStorage.removeItem("openfox_token"),h("/")},className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Logout",children:i.jsx(aT,{})}),t&&m&&i.jsx("button",{onClick:t,className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:T.criteriaSidebar?`Toggle criteria sidebar (${qu(T.criteriaSidebar)})`:"Toggle criteria sidebar",children:i.jsx(j_,{})})]}),i.jsx(V6,{isOpen:n,onClose:()=>r(!1)}),i.jsx(J6,{isOpen:b,onClose:()=>v(!1)})]})}function Rk({onCancel:e,onSave:t,saving:n,saveDisabled:r,cancelLabel:a="Cancel",saveLabel:l=n?"Saving...":"Save"}){return i.jsxs("div",{className:"flex justify-end gap-2 flex-shrink-0",children:[i.jsx(Ze,{variant:"secondary",onClick:e,children:a}),i.jsx(Ze,{variant:"primary",onClick:t,disabled:r??n,children:l})]})}const Au=Mn()(e=>({config:null,loading:!1,fetchConfig:async t=>{e({loading:!0});try{const r=await(await Se(`/api/workspace/config?workdir=${encodeURIComponent(t)}`)).json();e({config:r.config??null,loading:!1})}catch{e({loading:!1})}},saveConfig:async(t,n)=>{const r=await Se(`/api/workspace/config?workdir=${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error("Failed to save workspace config");const a=await r.json();e({config:a.config??n})}})),oB=["/","/etc","/bin","/sbin","/lib","/lib64","/usr","/var","/opt","/root","/run","/tmp","/home","/mnt","/media"],lB=["/proc/","/sys/","/dev/","/boot/","/etc/","/lost+found/"];function cB(e,t=oB,n=lB){if(!e)return null;const r=e.replace(/\/+$/,"")||"/";if(t.includes(r))return"exact";for(const a of n)if(r.startsWith(a))return"virtual_fs";return null}function uB({isOpen:e,onClose:t,project:n}){const r=Ft(re=>re.updateProject),a=Au(re=>re.config),l=Au(re=>re.loading),u=Au(re=>re.fetchConfig),c=Au(re=>re.saveConfig),d=()=>{try{Pt.send("context.checkDynamic",{})}catch{}t()},[h,p]=N.useState(n.customInstructions??""),[m,x]=N.useState(n.dangerLevel??""),[y,w]=N.useState(!1),[C,_]=N.useState(!1),[S,v]=N.useState(!1),[b,E]=N.useState(null),[j,T]=N.useState(""),[D,L]=N.useState(!1),[I,P]=N.useState(""),[W,H]=N.useState(!1),[R,U]=N.useState(""),[V,G]=N.useState(!1),[Z,X]=N.useState(!1),[$,O]=N.useState([]),[M,q]=N.useState(""),[z,ee]=N.useState({}),[Q,ne]=N.useState(!1),[K,B]=N.useState(new Set),te=y||C||D||W||Q;N.useEffect(()=>{e&&(p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),H(!1),ne(!1),B(new Set),u(n.workdir))},[e,n,u]),N.useEffect(()=>{a!=null&&a.setup&&a.setup.length>0?T(a.setup.join(" && ")):T(""),P((a==null?void 0:a.rootDir)??""),ee((a==null?void 0:a.mcpOverrides)??{})},[a]);const se=Al(re=>re.servers),xe=re=>z[re]??{},oe=re=>{var He;const _e=xe(re);if(_e.disabled!==void 0)return _e.disabled;const Le=se.find(qe=>qe.name===re);return!!((He=Le==null?void 0:Le.config)!=null&&He.disabled)},Oe=(re,_e)=>{var He;return((He=xe(re).disabledTools)==null?void 0:He.includes(_e))??!1},Me=re=>{ee(_e=>({..._e,[re]:{..._e[re],disabled:!oe(re)}})),ne(!0)},ze=(re,_e)=>{ee(Le=>{const He=Le[re]??{},qe=He.disabledTools??[],Ke=qe.includes(_e)?qe.filter(tt=>tt!==_e):[...qe,_e];return{...Le,[re]:{...He,disabledTools:Ke.length>0?Ke:void 0}}}),ne(!0)},$e=re=>{B(_e=>{if(_e.has(re)){const He=new Set(_e);return He.delete(re),He}const Le=new Set(_e);return Le.add(re),Le})},je=re=>{p(re.target.value),w(!0)},rt=re=>{x(re),_(!0)},Qe=re=>{T(re.target.value),L(!0)},fe=re=>{P(re.target.value),H(!0)},ce=N.useCallback(async()=>{const re=m===""?null:m;await r(n.id,{customInstructions:h||null,dangerLevel:re});const _e=j.trim()?j.split("&&").map(Le=>Le.trim()).filter(Boolean):[];await c(n.workdir,{..._e.length>0?{setup:_e}:{},rootDir:I.trim(),...Object.keys(z).length>0?{mcpOverrides:z}:{mcpOverrides:void 0}}),w(!1),_(!1),L(!1),H(!1),ne(!1),d()},[n.id,m,h,j,I,z,r,c,n.workdir,d]),de=async()=>{const re=I.trim(),_e=(a==null?void 0:a.rootDir)??"";if(re){const Le=cB(re);if(Le==="exact"){const He=re.replace(/\/+$/,"")||"/";E(`Cannot use "${He}" directly as workspace root. Use a subdirectory like "${He}/${n.name}" instead.`);return}if(Le==="virtual_fs"){E(`Cannot use paths under "${re}" for workspaces.`);return}}if(!W||!re||re===_e){v(!0),E(null);try{await ce()}catch(Le){E(Le instanceof Error?Le.message:"Failed to save settings")}finally{v(!1)}return}U(re),v(!0),E(null);try{const Le=await Se(`/api/workspace/config/validate?workdir=${encodeURIComponent(n.workdir)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rootDir:re,workdir:n.workdir,projectName:n.name})});if(!Le.ok){const qe=await Le.json().catch(()=>({}));E((qe==null?void 0:qe.error)??"Failed to validate workspace root directory"),v(!1);return}const He=await Le.json();if(!He.exists){q(He.resolvedPath),v(!1),G(!0);return}if(He.workspaces&&He.workspaces.length>0){O(He.workspaces),v(!1),X(!0);return}E(null),await ce()}catch(Le){E(Le instanceof Error?Le.message:"Failed to validate settings"),v(!1)}},he=async()=>{G(!1),v(!0);try{const re=await Se(`/api/workspace/config/validate?workdir=${encodeURIComponent(n.workdir)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rootDir:R,workdir:n.workdir,projectName:n.name,createIfMissing:!0})});if(!re.ok){const Le=await re.json().catch(()=>({}));E((Le==null?void 0:Le.error)??"Failed to create directory"),v(!1);return}const _e=await re.json();if(_e.workspaces&&_e.workspaces.length>0){O(_e.workspaces),X(!0),v(!1);return}await ce()}catch(re){E(re instanceof Error?re.message:"Failed to create directory")}finally{v(!1)}},De=async()=>{X(!1),v(!0),E(null);try{await ce()}catch(re){E(re instanceof Error?re.message:"Failed to save settings")}finally{v(!1)}},Ue=()=>{G(!1),X(!1),p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),H(!1),d()};return i.jsxs(wt,{isOpen:e,onClose:Ue,title:`${n.name} Settings`,size:"lg",footer:i.jsx(Rk,{onCancel:Ue,onSave:de,saving:S,saveDisabled:!te||S}),children:[i.jsxs("div",{className:"flex flex-col gap-5 -mt-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Default Danger Level"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Default danger level for new sessions in this project. Existing sessions are not affected."}),i.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-1 rounded bg-bg-tertiary/50 w-fit",children:[i.jsx("button",{type:"button",onClick:()=>rt(""),className:`px-3 py-1 text-sm font-medium rounded transition-colors ${m===""?"bg-bg-tertiary text-text-primary border border-border":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Use global default (Normal)",children:"Default"}),i.jsx("button",{type:"button",onClick:()=>rt("normal"),className:`px-3 py-1 text-sm font-medium rounded transition-colors ${m==="normal"?"bg-accent-success/20 text-accent-success border border-accent-success/30":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),i.jsx("button",{type:"button",onClick:()=>rt("dangerous"),className:`px-3 py-1 text-sm font-medium rounded transition-colors ${m==="dangerous"?"bg-red-500/20 text-red-400 border border-red-500/30":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Project Path"}),i.jsx("p",{className:"text-sm text-text-muted font-mono",children:n.workdir})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Project Instructions"}),i.jsx("p",{className:"text-sm text-text-muted mb-3 flex-shrink-0",children:"These instructions are injected into prompts when working in this project. They are applied after global instructions but before AGENTS.md files."}),i.jsx("textarea",{value:h,onChange:je,placeholder:"Enter project-specific instructions...",className:"w-full h-32 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:S})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Workspace Setup Command"}),i.jsxs("p",{className:"text-sm text-text-muted mb-3",children:["Command(s) to run after creating a workspace (shared clone). Use"," ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:"&&"})," to chain multiple commands. Example:"," ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:"npm install --prefer-offline"})]}),l&&i.jsx("div",{className:"text-xs text-text-muted mb-2",children:"Loading config..."}),i.jsx("input",{type:"text",value:j,onChange:Qe,placeholder:"npm install --prefer-offline",className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:l||S})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Workspace Root Directory"}),i.jsxs("p",{className:"text-sm text-text-muted mb-3",children:["Override the default workspace location. Leave empty to use the global directory"," ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:"~/.local/share/openfox/workspaces/"}),". Supports absolute paths or paths relative to the project."]}),i.jsx("input",{type:"text",value:I,onChange:fe,placeholder:"/absolute/or/relative/path",className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:l||S})]}),se.length>0&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"MCP Servers"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Override MCP server availability for this project. These overrides apply to new conversations in this project and can be further overridden per conversation from the chat MCP selector."}),i.jsx("div",{className:"space-y-2",children:se.map(re=>{const _e=oe(re.name);return i.jsx(wk,{server:re,expanded:K.has(re.name),onToggleExpand:$e,serverToggleEnabled:!_e,onServerToggle:()=>Me(re.name),tools:re.tools.map(Le=>({...Le,enabled:!Oe(re.name,Le.name)})),onToolToggle:Le=>ze(re.name,Le),statusDot:Gg(_e?"disabled":re.status),statusColor:Vg(_e?"disabled":re.status)},re.name)})})]}),b&&i.jsx("div",{className:"text-sm text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:b})]}),V&&i.jsxs(wt,{isOpen:V,onClose:()=>G(!1),title:"Directory not found",size:"md",footer:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{type:"button",onClick:()=>G(!1),className:"px-4 py-2 text-sm font-medium rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:"Cancel"}),i.jsx("button",{type:"button",onClick:he,className:"px-4 py-2 text-sm font-medium rounded bg-accent-primary text-white hover:opacity-90 transition-colors",children:"Create"})]}),children:[i.jsxs("p",{className:"text-sm text-text-primary",children:["The directory ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:M})," does not exist."]}),i.jsx("p",{className:"text-sm text-text-muted mt-2",children:"Would you like to create it?"})]}),Z&&i.jsxs(wt,{isOpen:Z,onClose:()=>X(!1),title:"Orphaned workspaces",size:"md",footer:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{type:"button",onClick:()=>X(!1),className:"px-4 py-2 text-sm font-medium rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:"Cancel"}),i.jsx("button",{type:"button",onClick:De,className:"px-4 py-2 text-sm font-medium rounded bg-red-500 text-white hover:opacity-90 transition-colors",children:"Confirm change"})]}),children:[i.jsxs("p",{className:"text-sm text-text-primary",children:[$.length," existing workspace(s) will not be migrated and will become inaccessible:"]}),i.jsx("ul",{className:"mt-2 space-y-1",children:$.map(re=>i.jsx("li",{className:"text-sm font-mono text-text-muted",children:re.name},re.name))}),i.jsx("p",{className:"text-sm text-text-muted mt-3",children:"Existing workspaces will remain in the old location but will no longer be accessible from this project."})]})]})}const dB={sm:"w-3 h-3",md:"w-4 h-4",lg:"w-5 h-5",xl:"w-6 h-6"},hB="M6 18L18 6M6 6l12 12";function ec({onClick:e,className:t="",size:n="md",variant:r="default"}){const a=r==="overlay"?"bg-accent-error text-white rounded-full flex items-center justify-center hover:bg-accent-error/80 transition-colors":r==="sidebar"?"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors":r==="modal"?"text-text-muted hover:text-text-primary transition-colors":"hover:text-white transition-colors";return i.jsx(wd,{onClick:e,icon:hB,iconSize:dB[n],className:`${a} ${t}`,title:"Close"})}function Kr(e,t){const n=new Set(t.map(r=>r.id));return[...e.filter(r=>!n.has(r.id)),...t]}function qp(e,t){if(!t)return e;const n=e.toLowerCase(),r=t.toLowerCase(),a=new Array(e.length).fill(!1),l=n.indexOf(r);if(l>=0)for(let p=l;p<l+r.length;p++)a[p]=!0;else{let p=0;for(let m=0;m<e.length&&p<r.length;m++)n[m]===r[p]&&(a[m]=!0,p++)}const u=Array.from(e),c=[];let d="",h=a[0]??!1;for(let p=0;p<u.length;p++){const m=u[p]??"";a[p]===h?d+=m:(c.push(h?i.jsx("span",{className:"font-semibold text-accent-primary",children:d},c.length):d),d=m,h=a[p]??!1)}return c.push(h?i.jsx("span",{className:"font-semibold text-accent-primary",children:d},c.length):d),i.jsx(i.Fragment,{children:c})}function ai(e,t){if(!t)return!0;const n=t.toLowerCase().split(/\s+/),r=e.toLowerCase().split(/\s+/);return n.every(a=>{for(const l of r){let u=0;for(let c=0;c<l.length&&u<a.length;c++)l[c]===a[u]&&u++;if(u===a.length)return!0}return!1})}function Ok(e,t,n,r,a){switch(e.key){case"ArrowDown":e.preventDefault(),n(l=>Math.min(l+1,t));break;case"ArrowUp":e.preventDefault(),n(l=>Math.max(l-1,0));break;case"Enter":e.preventDefault(),r();break;case"Escape":e.preventDefault(),a();break}}function Ik({projectId:e,isOpen:t=!0,onClose:n}){const[,r]=Ln(),[a,l]=N.useState(!1),[u,c]=N.useState(null),[d,h]=N.useState(null),[p,m]=N.useState(""),[x,y]=N.useState(!1),w=Re(oe=>oe.sessions),C=Re(oe=>oe.currentSession),_=Re(oe=>oe.unreadSessionIds),S=Re(oe=>oe.deleteSession),v=Re(oe=>oe.deleteAllSessions),b=Re(oe=>oe.loadMoreSessions),E=Re(oe=>oe.sessionsHasMore),j=Re(oe=>oe.sessionsPaginationLoading),T=Re(oe=>oe.sessionsWithPendingConfirmations),D=Re(oe=>oe.pendingPathConfirmations),L=Ft(oe=>oe.currentProject),[I,P]=N.useState(""),[W,H]=N.useState(-1),R=N.useRef(null),U=N.useRef(null),V=N.useRef(!1),G=Gl();Dl(G.sessionSearch,()=>{var oe;if(t&&document.activeElement===R.current){n==null||n();return}t||(V.current=!0,n==null||n()),(oe=R.current)==null||oe.focus()});const Z=N.useRef(null),X=N.useCallback(()=>{E&&!j&&L&&b(L.id)},[E,j,L,b]);N.useEffect(()=>{if(!Z.current||!E)return;const oe=new IntersectionObserver(Oe=>{const Me=Oe[0];Me&&Me.isIntersecting&&X()},{threshold:.1});return oe.observe(Z.current),()=>oe.disconnect()},[E,X]);const $=w.filter(oe=>oe.projectId===(L==null?void 0:L.id)),O=N.useMemo(()=>I?$.filter(oe=>{var ze;const Oe=oe.title??"",Me=(((ze=oe.recentUserPrompts)==null?void 0:ze.map($e=>$e.content))??[]).join(" ");return ai(Oe,I)||ai(Me,I)}):$,[$,I]),M=I.length>0,q=M&&O.length===0;N.useEffect(()=>{H(O.length>0?0:-1)},[O.length]),N.useEffect(()=>{var Oe;if(W<0)return;const oe=(Oe=U.current)==null?void 0:Oe.querySelector(`[data-sidx="${W}"]`);oe==null||oe.scrollIntoView({block:"nearest"})},[W]);const z=(oe,Oe)=>{Oe==null||Oe.stopPropagation(),c(oe)},ee=()=>{u&&(S(u),(C==null?void 0:C.id)===u&&r(`/p/${e}`),c(null))},Q=(oe,Oe)=>{Oe==null||Oe.stopPropagation();const Me=w.find($e=>$e.id===oe),ze=(Me==null?void 0:Me.title)??oe.slice(0,6);m(ze),h(oe)},ne=()=>{if(!d||p.trim()==="")return;const oe=Re.getState().renameSession;oe(d,p.trim()),h(null),m("")},K=()=>{y(!0)},B=()=>{v(e),r(`/p/${e}`),y(!1)},te=oe=>{if(!V.current)return;oe.target.closest('a[href*="/s/"]')&&(V.current=!1,n==null||n())},se=()=>{var oe;P(""),(oe=R.current)==null||oe.focus()},xe=oe=>{var Oe;switch(oe.key){case"Escape":P(""),(Oe=R.current)==null||Oe.blur();break;case"ArrowDown":oe.preventDefault(),H(Me=>Me<O.length-1?Me+1:Me);break;case"ArrowUp":oe.preventDefault(),H(Me=>Me>0?Me-1:0);break;case"Enter":{oe.preventDefault();const Me=O[W];Me&&(r(`/p/${e}/s/${Me.id}`),V.current&&(V.current=!1,n==null||n()));break}}};return i.jsxs(i.Fragment,{children:[t&&n&&i.jsx("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:n}),(()=>{const oe=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-4 border-b border-border flex gap-2",children:[i.jsx(Jn,{href:`/p/${e}/new`,className:"flex-1 block text-center rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-1.5 text-sm","data-testid":"sidebar-new-session-button",children:"+ New Session"}),i.jsx(Zl,{items:[{label:"Edit project settings",onClick:()=>l(!0)},{label:"Delete all sessions",onClick:K,danger:!0}],trigger:i.jsx("button",{className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Options",children:i.jsx(C1,{})})}),n&&i.jsx(ec,{onClick:n,className:"md:hidden",variant:"sidebar",size:"md"})]}),i.jsxs("div",{className:"px-4 py-2 border-b border-border",children:[i.jsxs("div",{className:"relative flex items-center",children:[i.jsx(Wi,{className:"absolute left-2.5 w-3.5 h-3.5 text-text-muted pointer-events-none"}),i.jsx("input",{ref:R,type:"text",value:I,onChange:Oe=>P(Oe.target.value),onKeyDown:xe,placeholder:"Search sessions...",className:"w-full bg-bg-tertiary border border-border rounded pl-8 pr-8 py-1.5 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:ring-1 focus:ring-accent-primary/50 focus:border-accent-primary transition-colors"}),I&&i.jsx("button",{type:"button",onClick:se,className:"absolute right-1.5 p-0.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors","aria-label":"Clear search",children:i.jsx(js,{className:"w-3.5 h-3.5"})})]}),M&&!q&&i.jsxs("div",{className:"mt-1 text-xs text-text-muted px-1",children:[O.length," ",O.length===1?"match":"matches"]})]}),L&&i.jsx(uB,{isOpen:a,onClose:()=>l(!1),project:L}),i.jsx(Rl,{isOpen:u!==null,onClose:()=>c(null),onConfirm:ee,title:"Delete session?",message:"This session will be permanently deleted.",confirmLabel:"Delete session",confirmVariant:"danger"}),i.jsx(Rl,{isOpen:x,onClose:()=>y(!1),onConfirm:B,title:"Delete all sessions?",message:"Delete all sessions in this project? This cannot be undone.",confirmLabel:"Delete all",confirmVariant:"danger"}),i.jsx(wt,{isOpen:d!==null,onClose:()=>{h(null),m("")},title:"Rename session",size:"sm",footer:i.jsx(Rk,{onCancel:()=>{h(null),m("")},onSave:ne,saving:!1,saveDisabled:p.trim()==="",saveLabel:"Rename"}),children:i.jsx("input",{type:"text",value:p,onChange:Oe=>m(Oe.target.value),onKeyDown:Oe=>{Oe.key==="Enter"&&ne()},onFocus:Oe=>Oe.target.select(),className:"w-full px-3 py-2 text-sm text-text-primary bg-bg-tertiary border border-border rounded focus:outline-none focus:ring-1 focus:ring-accent-primary",autoFocus:!0})}),i.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-stable",children:O.length===0?i.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:M?"No matching sessions":"No sessions"}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"divide-y divide-border",ref:U,onClick:te,children:fB(O,C,_,z,Q,e,T,D,I,W)}),j&&i.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"Loading more..."}),i.jsx("div",{ref:Z,className:"h-px"})]})})]});return i.jsx("aside",{className:`
275
+ `+(b==="group"?`sudo chmod g+w "${n}"`:"sudo usermod -aG <group> $USER"))}catch(E){c("Failed to fix permissions: "+(E instanceof Error?E.message:"Unknown error"))}finally{l(!1)}},[n,r,t]),x=(d==null?void 0:d.userInGroup)??!1,y=(d==null?void 0:d.groupHasWrite)??!1,w=(d==null?void 0:d.sudoAvailable)??!1,C=(d==null?void 0:d.groupName)??"",_=x&&!y,S=!x&&y,v=!x&&!y;return i.jsx(wt,{isOpen:e,onClose:t,title:"Permission Denied",size:"sm",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"text-sm text-text-secondary",children:[i.jsx("p",{children:_?i.jsxs(i.Fragment,{children:["The group ",i.jsx("strong",{children:C})," doesn't have write access:"]}):S?i.jsxs(i.Fragment,{children:["You're not a member of group ",i.jsx("strong",{children:C}),":"]}):i.jsxs(i.Fragment,{children:["You're not a member of group ",i.jsx("strong",{children:C})," and it doesn't have write access:"]})}),i.jsx("p",{className:"mt-2 font-mono text-xs bg-bg-tertiary p-2 rounded break-all",children:n})]}),u?i.jsx("div",{className:"p-3 bg-accent-error/10 border border-accent-error/30 rounded text-sm text-accent-error whitespace-pre-wrap",children:u}):d?i.jsxs("div",{className:"flex flex-col gap-2",children:[_&&i.jsxs(i.Fragment,{children:[i.jsx(Ze,{type:"button",variant:"primary",onClick:()=>m("group"),disabled:a||!w,className:"w-full",children:a?"Granting access...":"Extend group permissions"}),i.jsx("div",{className:"text-xs text-text-secondary",children:"Or manually execute:"}),i.jsxs("code",{className:"text-xs text-text-muted p-2 bg-bg-tertiary rounded break-all",children:['sudo chmod g+w "',n,'"']})]}),S&&i.jsxs(i.Fragment,{children:[i.jsx(Ze,{type:"button",variant:"primary",onClick:()=>m("join_group"),disabled:a||!w,className:"w-full",children:a?"Joining group...":"Join group"}),i.jsx("div",{className:"text-xs text-text-secondary",children:"Or manually execute:"}),i.jsxs("code",{className:"text-xs text-text-muted p-2 bg-bg-tertiary rounded break-all",children:["sudo usermod -aG ",C," $USER"]})]}),v&&i.jsxs(i.Fragment,{children:[i.jsx(Ze,{type:"button",variant:"primary",onClick:()=>m("join_group_and_group"),disabled:a||!w,className:"w-full",children:a?"Joining group...":"Join group & grant write permissions"}),i.jsx("div",{className:"text-xs text-text-secondary",children:"Or manually execute:"}),i.jsxs("code",{className:"text-xs text-text-muted p-2 bg-bg-tertiary rounded break-all",children:["sudo usermod -aG ",C," $USER",i.jsx("br",{}),'sudo chmod g+w "',n,'"']})]}),!w&&!u&&i.jsxs("div",{className:"text-xs text-text-secondary",children:[i.jsx("p",{children:"Passwordless sudo is not available. Please fix permissions manually:"}),i.jsxs("code",{className:"block mt-1 p-2 bg-bg-tertiary rounded break-all",children:['sudo chmod g+w "',n,'"']})]}),i.jsx("div",{className:"flex justify-end",children:i.jsx(Ze,{type:"button",variant:"secondary",onClick:t,disabled:a,children:"Cancel"})})]}):null]})})}function Nk({isOpen:e,onClose:t}){const[,n]=Ln(),r=Ft(j=>j.listProjects),[a,l]=N.useState(""),[u,c]=N.useState(null),[d,h]=N.useState(!1),[p,m]=N.useState(""),[x,y]=N.useState(null),w=N.useRef(null);N.useEffect(()=>{e&&(Se("/api/config").then(j=>j.json()).then(j=>{j.workdir&&m(j.workdir)}),l(""),c(null),h(!1),y(null),setTimeout(()=>{var j;(j=w.current)==null||j.focus()},100))},[e]);const C=N.useCallback(async j=>{j.preventDefault();const T=Z6(a);if(!T.valid){c(T.error);return}const D=`${p}/${a}`;await v(D)},[a,n,t,p]),_=N.useCallback(()=>{y(null)},[]),S=N.useCallback(async()=>{const j=`${p}/${a}`;await v(j)},[p,a,n,t,y,c,h]);async function v(j){h(!0),c(null),y(null);try{const T=await Se("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,workdir:j})});if(!T.ok){const I=await T.json().catch(()=>({}));if(I.code==="EACCES"){y(j),h(!1);return}throw new Error(I.error||"Failed to create project")}const L=(await T.json()).project;t(),await r(),n(`/p/${L.id}`)}catch(T){c(T instanceof Error?T.message:"Failed to create project"),h(!1)}}const b=N.useCallback(()=>{l(""),c(null),t()},[t]),E=a?`${p}/${a}`:"";return i.jsxs(i.Fragment,{children:[i.jsx(wt,{isOpen:e,onClose:b,title:"Create New Project",size:"sm",children:i.jsxs("form",{onSubmit:C,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"project-name",className:"block text-sm font-medium text-text-secondary mb-2",children:"Project Name"}),i.jsx(oi,{ref:w,id:"project-name",value:a,onChange:j=>{l(j.target.value),c(null)},placeholder:"my-project",disabled:d,"data-testid":"create-project-name-input",className:"w-full"}),a&&i.jsxs("div",{className:"mt-2 text-xs text-text-muted",children:["Full path: ",i.jsx("span",{className:"font-mono",children:E})]}),u&&i.jsx("div",{className:"mt-3 p-3 bg-accent-error/10 border border-accent-error/30 rounded text-sm text-accent-error",children:u})]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ze,{type:"button",variant:"secondary",onClick:b,disabled:d,children:"Cancel"}),i.jsx(Ze,{type:"submit",variant:"primary",disabled:d||!a.trim(),"data-testid":"create-project-submit-button",className:"min-w-[100px]",children:d?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Es,{className:"h-4 w-4"}),"Creating..."]}):"Create"})]})]})}),x&&i.jsx(jk,{isOpen:!!x,onClose:_,path:x,onRetry:S})]})}function Tk(){const[e,t]=N.useState(null);return N.useEffect(()=>{Se("/api/config").then(n=>n.json()).then(n=>{n.workdir&&t(n.workdir)})},[]),e}function _S({projects:e,currentProject:t}){const[,n]=Ln(),r=Ft(_=>_.loadProject),a=Ft(_=>_.toggleStar),l=Ft(_=>_.createProject),u=Ft(_=>_.listProjects),[c,d]=N.useState(!1),[h,p]=N.useState(!1),m=Tk(),x=N.useCallback(async _=>{const S=P1(_),v=await l(S,_);return v&&"id"in v?(await u(),p(!1),n(`/p/${v.id}`),!0):!1},[l,u,n]),w=N.useMemo(()=>{const _=e.filter(v=>v.isStarred).sort((v,b)=>v.name.localeCompare(b.name)),S=e.filter(v=>!v.isStarred).sort((v,b)=>v.name.localeCompare(b.name));return[..._,...S]},[e]).map(_=>({label:i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[i.jsx("span",{className:"truncate flex-1",children:_.name}),i.jsx("button",{onClick:S=>{S.stopPropagation(),S.preventDefault(),S.nativeEvent.stopImmediatePropagation(),a(_.id,!_.isStarred)},className:"flex-shrink-0 p-1 hover:bg-bg-tertiary rounded transition-colors",title:_.isStarred?"Unstar project":"Star project",children:_.isStarred?i.jsx(N1,{className:"w-3.5 h-3.5 text-yellow-500"}):i.jsx(T1,{className:"w-3.5 h-3.5 text-text-muted hover:text-yellow-500"})})]}),icon:_.id===(t==null?void 0:t.id)?i.jsx(Pr,{}):void 0,href:`/p/${_.id}`,closeOnClick:!0,onClick:()=>{r(_.id)}})),C=[{label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Or,{className:"w-4 h-4"}),i.jsx("span",{children:"Open Project"})]}),onClick:()=>p(!0)},{label:i.jsxs("div",{className:"flex items-center gap-2 text-accent-primary",children:[i.jsx(Es,{className:"w-4 h-4"}),i.jsx("span",{children:"New Project"})]}),onClick:()=>d(!0)}];return i.jsxs(i.Fragment,{children:[i.jsx(Zl,{items:w,footerItems:C,trigger:i.jsxs("button",{className:`text-text-secondary hover:text-text-primary text-sm truncate flex items-center gap-1 ${t?"hover:underline":""}`,title:(t==null?void 0:t.name)??"Select project",children:[(t==null?void 0:t.name)??i.jsx("span",{className:"text-text-muted",children:"Select project..."}),i.jsx(yn,{})]}),minWidth:"250px"}),c&&i.jsx(Nk,{isOpen:c,onClose:()=>d(!1)}),h&&i.jsx(Cd,{initialPath:m??void 0,onSelect:x,onClose:()=>p(!1)})]})}function Ak(e){const t=new Date(e),r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),u=String(t.getDate()).padStart(2,"0");return`${r} ${a}/${l}/${u}`}function Gd(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}:${r}`}function eB(e){const t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),a=new Date(t.getFullYear(),t.getMonth(),t.getDate()),l=Math.floor((r.getTime()-a.getTime())/(1e3*60*60*24)),u=Gd(e);if(l===0)return`today ${u}`;if(l===1)return`yesterday ${u}`;if(l<7)return`${l} days ago ${u}`;{const c=t.getFullYear(),d=String(t.getMonth()+1).padStart(2,"0"),h=String(t.getDate()).padStart(2,"0");return`${c}/${d}/${h} ${u}`}}function Lk(e){const t=new Date(e);return{year:t.getFullYear(),month:String(t.getMonth()+1).padStart(2,"0"),day:String(t.getDate()).padStart(2,"0")}}function tB(e){const{year:t,month:n,day:r}=Lk(e);return`${t}-${n}-${r}`}function Dk(e){const t=new Map;for(const a of e){const l=tB(a.updatedAt);t.has(l)||t.set(l,[]),t.get(l).push(a)}for(const[a,l]of t)l.sort((u,c)=>{const d=new Date(u.updatedAt).getTime();return new Date(c.updatedAt).getTime()-d});const n=Array.from(t.keys()).sort((a,l)=>l.localeCompare(a)),r=new Map;for(const a of n)r.set(a,t.get(a));return r}function nB(e){const{year:t,month:n,day:r}=Lk(e);return`${t}/${n}/${r} ${Gd(e)}`}function dd(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function rB({sessions:e,currentProject:t,currentSession:n,isOpen:r,onOpenChange:a}){var x;const l=Re(y=>y.loadSession),u=50,c=e.filter(y=>y.projectId===t.id).slice(0,15),d=Dk(c),h=N.useMemo(()=>{const y=[];y.push({label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Es,{className:"w-4 h-4 text-accent-primary"}),i.jsx("span",{className:"text-sm",children:"New session"})]}),href:`/p/${t.id}/new`,onClick:()=>{}});for(const[w,C]of d){const _=C[0];if(_){y.push({label:i.jsx("div",{className:"px-3 py-2 text-text-muted text-xs font-medium cursor-default",children:Ak(_.updatedAt)}),onClick:()=>{}});for(const S of C)y.push({label:i.jsxs("div",{className:"min-w-[160px]",children:[i.jsx("div",{className:"truncate text-sm",children:dd(S.title??S.id.slice(0,8),u)}),i.jsx("div",{className:"text-text-muted text-xs",children:Gd(S.updatedAt)})]}),icon:S.id===(n==null?void 0:n.id)?i.jsx(Pr,{}):void 0,href:`/p/${t.id}/s/${S.id}`,onClick:()=>{l(S.id)}})}}return y},[t.id,d,n==null?void 0:n.id]),p=((x=n==null?void 0:n.metadata)==null?void 0:x.title)??(n?n.id.slice(0,8):null),m=p?dd(p,u):"No session selected";return i.jsx(Zl,{items:h,isOpen:r,onOpenChange:a,trigger:i.jsxs("button",{className:"text-text-secondary hover:text-text-primary hover:underline text-sm truncate flex items-center gap-1",title:p??"","data-testid":"header-session-dropdown",children:[m,i.jsx(yn,{})]}),minWidth:"280px"})}function sB({items:e,trigger:t,isActive:n=!1}){const[r,a]=N.useState(!1),l=N.useRef(null);return N.useEffect(()=>{function u(c){l.current&&!l.current.contains(c.target)&&a(!1)}if(r)return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),i.jsxs("div",{className:"relative",ref:l,children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),className:`flex items-center gap-1 px-1.5 py-0.5 rounded transition-colors ${n?"bg-bg-tertiary":"hover:bg-bg-tertiary"}`,children:[typeof t=="string"?i.jsx("span",{className:"text-sm text-text-secondary font-medium",children:t}):t,i.jsx(yn,{className:"w-3 h-3 text-text-muted flex-shrink-0 transition-transform",rotate:r?180:0})]}),r&&e.length>0&&i.jsx("div",{className:"absolute top-full left-0 mt-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:e.map((u,c)=>{const d=u.label&&typeof u.label=="object"&&u.label.type===Jn?u.label:null;if(d){const h=d.props.href||"";return i.jsxs(Jn,{href:h,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[u.icon,d.props.children]},c)}return u.href?i.jsxs("a",{href:u.href,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[u.icon,u.label]},c):i.jsxs("button",{type:"button",onClick:()=>{var h;(h=u.onClick)==null||h.call(u),a(!1)},className:"flex items-center gap-2 px-3 py-2 text-sm w-full text-left border-b border-border hover:bg-bg-tertiary transition-colors",children:[u.icon,u.label]},c)})})]})}function iB({currentProject:e,sessions:t,currentSession:n,projectIdFromUrl:r}){if(!(e!=null&&e.id)||e.id!==r)return null;const a=t.filter(u=>u.projectId===e.id).sort((u,c)=>new Date(c.updatedAt).getTime()-new Date(u.updatedAt).getTime()).slice(0,5),l=[{label:i.jsxs(Jn,{href:`/p/${e.id}/new`,className:"flex items-center gap-2",children:[i.jsx(Es,{className:"w-3 h-3 text-accent-primary"}),i.jsx("span",{className:"text-sm",children:"New Session"})]})},...a.map(u=>({label:i.jsx(Jn,{href:`/p/${e.id}/s/${u.id}`,className:"flex items-center gap-2 truncate text-sm",children:i.jsx("span",{children:dd(u.title??u.id.slice(0,8),50)})}),icon:u.id===(n==null?void 0:n.id)?i.jsx(Pr,{className:"w-3 h-3"}):void 0})),{label:i.jsxs(Jn,{href:"/",className:"flex items-center gap-2 text-text-muted hover:text-text-primary",children:[i.jsx(eT,{className:"w-3 h-3"}),i.jsx("span",{className:"text-sm",children:"Projects"})]})}];return i.jsx(sB,{items:l,trigger:i.jsx("span",{className:"text-sm text-text-secondary font-medium",children:e.name})})}function aB({onMenuClick:e,onCriteriaToggle:t}){const[n,r]=N.useState(!1),[a,l]=N.useState(!1),[u,c]=N.useState(!!document.fullscreenElement),[d,h]=Ln();N.useEffect(()=>{const D=()=>c(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",D),()=>document.removeEventListener("fullscreenchange",D)},[]);const p=d.startsWith("/p/"),m=/^\/p\/[^/]+\/s\/[^/]+$/.test(d),x=Re(D=>D.currentSession),y=Re(D=>D.sessions),w=Ft(D=>D.currentProject),C=Ft(D=>D.projects),_=Kt(D=>D.startAutoRefresh),S=Kt(D=>D.stopAutoRefresh),v=Dr(D=>D.setOpen),b=Dr(D=>D.isOpen),E=Cs(D=>D.status==="available"),j=Cs(D=>D.check);N.useEffect(()=>{Cs.getState().status==="idle"&&j()},[j]),N.useEffect(()=>{const D=()=>l(!0);return window.addEventListener("open-session-dropdown",D),()=>window.removeEventListener("open-session-dropdown",D)},[]);const T=Gl();return Dl(T.terminalToggle,()=>{Dr.getState().toggleOpen()},{capture:!0}),N.useEffect(()=>(_(),()=>S()),[_,S]),i.jsxs("header",{className:"h-8 bg-secondary border-b border-border flex items-center justify-between px-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e&&m&&i.jsx("button",{onClick:e,className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:T.sessionSearch?`Toggle session list (${qu(T.sessionSearch)})`:"Toggle session list",children:i.jsx(j_,{})}),i.jsx(Jn,{href:"/",className:"text-accent-primary font-semibold text-sm hover:underline flex-shrink-0 hidden md:inline",children:"OpenFox"}),w&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),i.jsx("span",{className:"hidden md:inline",children:i.jsx(_S,{projects:C,currentProject:w})}),i.jsx("span",{className:"md:hidden",children:i.jsx(iB,{currentProject:w,sessions:y,currentSession:x,projectIdFromUrl:p&&d.split("/")[2]||null},w==null?void 0:w.id)}),i.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),i.jsx("span",{className:"hidden md:inline",children:i.jsx(rB,{sessions:y,currentProject:w,currentSession:x,isOpen:a,onOpenChange:l})})]}),!w&&i.jsx("span",{className:"hidden md:inline",children:i.jsx(_S,{projects:C})})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[m&&i.jsx("button",{onClick:()=>{var D,L,I;document.fullscreenElement?(D=document.exitFullscreen)==null||D.call(document):(I=(L=document.documentElement).requestFullscreen)==null||I.call(L)},className:"max-sm:block hidden p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:u?"Exit fullscreen":"Enter fullscreen",children:u?i.jsx(rT,{}):i.jsx(sT,{})}),p&&i.jsx("button",{onClick:()=>v(!b),className:`p-2.5 rounded hover:bg-bg-tertiary transition-colors ${b?"text-accent-primary":"text-text-muted hover:text-text-primary"}`,title:"Toggle terminal (double Ctrl)",children:i.jsx(dT,{})}),i.jsxs("button",{onClick:()=>r(!0),className:"relative p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:E?"Settings — update available":"Settings",children:[i.jsx(lT,{}),E&&i.jsx("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-accent-primary"})]}),i.jsx("button",{onClick:()=>{localStorage.removeItem("openfox_token"),h("/")},className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Logout",children:i.jsx(aT,{})}),t&&m&&i.jsx("button",{onClick:t,className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:T.criteriaSidebar?`Toggle criteria sidebar (${qu(T.criteriaSidebar)})`:"Toggle criteria sidebar",children:i.jsx(j_,{})})]}),i.jsx(V6,{isOpen:n,onClose:()=>r(!1)}),i.jsx(J6,{isOpen:b,onClose:()=>v(!1)})]})}function Rk({onCancel:e,onSave:t,saving:n,saveDisabled:r,cancelLabel:a="Cancel",saveLabel:l=n?"Saving...":"Save"}){return i.jsxs("div",{className:"flex justify-end gap-2 flex-shrink-0",children:[i.jsx(Ze,{variant:"secondary",onClick:e,children:a}),i.jsx(Ze,{variant:"primary",onClick:t,disabled:r??n,children:l})]})}const Au=Mn()(e=>({config:null,loading:!1,fetchConfig:async t=>{e({loading:!0});try{const r=await(await Se(`/api/workspace/config?workdir=${encodeURIComponent(t)}`)).json();e({config:r.config??null,loading:!1})}catch{e({loading:!1})}},saveConfig:async(t,n)=>{const r=await Se(`/api/workspace/config?workdir=${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error("Failed to save workspace config");const a=await r.json();e({config:a.config??n})}})),oB=["/","/etc","/bin","/sbin","/lib","/lib64","/usr","/var","/opt","/root","/run","/tmp","/home","/mnt","/media"],lB=["/proc/","/sys/","/dev/","/boot/","/etc/","/lost+found/"];function cB(e,t=oB,n=lB){if(!e)return null;const r=e.replace(/\/+$/,"")||"/";if(t.includes(r))return"exact";for(const a of n)if(r.startsWith(a))return"virtual_fs";return null}function uB({isOpen:e,onClose:t,project:n}){const r=Ft(re=>re.updateProject),a=Au(re=>re.config),l=Au(re=>re.loading),u=Au(re=>re.fetchConfig),c=Au(re=>re.saveConfig),d=()=>{try{Pt.send("context.checkDynamic",{})}catch{}t()},[h,p]=N.useState(n.customInstructions??""),[m,x]=N.useState(n.dangerLevel??""),[y,w]=N.useState(!1),[C,_]=N.useState(!1),[S,v]=N.useState(!1),[b,E]=N.useState(null),[j,T]=N.useState(""),[D,L]=N.useState(!1),[I,P]=N.useState(""),[W,H]=N.useState(!1),[R,U]=N.useState(""),[V,G]=N.useState(!1),[Z,X]=N.useState(!1),[$,O]=N.useState([]),[M,q]=N.useState(""),[z,ee]=N.useState({}),[Q,ne]=N.useState(!1),[K,B]=N.useState(new Set),te=y||C||D||W||Q;N.useEffect(()=>{e&&(p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),H(!1),ne(!1),B(new Set),u(n.workdir))},[e,n,u]),N.useEffect(()=>{a!=null&&a.setup&&a.setup.length>0?T(a.setup.join(" && ")):T(""),P((a==null?void 0:a.rootDir)??""),ee((a==null?void 0:a.mcpOverrides)??{})},[a]);const se=Al(re=>re.servers),xe=re=>z[re]??{},oe=re=>{var He;const _e=xe(re);if(_e.disabled!==void 0)return _e.disabled;const Le=se.find(qe=>qe.name===re);return!!((He=Le==null?void 0:Le.config)!=null&&He.disabled)},Oe=(re,_e)=>{var He;return((He=xe(re).disabledTools)==null?void 0:He.includes(_e))??!1},Me=re=>{ee(_e=>({..._e,[re]:{..._e[re],disabled:!oe(re)}})),ne(!0)},ze=(re,_e)=>{ee(Le=>{const He=Le[re]??{},qe=He.disabledTools??[],Ke=qe.includes(_e)?qe.filter(tt=>tt!==_e):[...qe,_e];return{...Le,[re]:{...He,disabledTools:Ke.length>0?Ke:void 0}}}),ne(!0)},$e=re=>{B(_e=>{if(_e.has(re)){const He=new Set(_e);return He.delete(re),He}const Le=new Set(_e);return Le.add(re),Le})},je=re=>{p(re.target.value),w(!0)},rt=re=>{x(re),_(!0)},Qe=re=>{T(re.target.value),L(!0)},fe=re=>{P(re.target.value),H(!0)},ce=N.useCallback(async()=>{const re=m===""?null:m;await r(n.id,{customInstructions:h||null,dangerLevel:re});const _e=j.trim()?j.split("&&").map(Le=>Le.trim()).filter(Boolean):[];await c(n.workdir,{..._e.length>0?{setup:_e}:{},rootDir:I.trim(),...Object.keys(z).length>0?{mcpOverrides:z}:{mcpOverrides:void 0}}),w(!1),_(!1),L(!1),H(!1),ne(!1),d()},[n.id,m,h,j,I,z,r,c,n.workdir,d]),de=async()=>{const re=I.trim(),_e=(a==null?void 0:a.rootDir)??"";if(re){const Le=cB(re);if(Le==="exact"){const He=re.replace(/\/+$/,"")||"/";E(`Cannot use "${He}" directly as workspace root. Use a subdirectory like "${He}/${n.name}" instead.`);return}if(Le==="virtual_fs"){E(`Cannot use paths under "${re}" for workspaces.`);return}}if(!W||!re||re===_e){v(!0),E(null);try{await ce()}catch(Le){E(Le instanceof Error?Le.message:"Failed to save settings")}finally{v(!1)}return}U(re),v(!0),E(null);try{const Le=await Se(`/api/workspace/config/validate?workdir=${encodeURIComponent(n.workdir)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rootDir:re,workdir:n.workdir,projectName:n.name})});if(!Le.ok){const qe=await Le.json().catch(()=>({}));E((qe==null?void 0:qe.error)??"Failed to validate workspace root directory"),v(!1);return}const He=await Le.json();if(!He.exists){q(He.resolvedPath),v(!1),G(!0);return}if(He.workspaces&&He.workspaces.length>0){O(He.workspaces),v(!1),X(!0);return}E(null),await ce()}catch(Le){E(Le instanceof Error?Le.message:"Failed to validate settings"),v(!1)}},he=async()=>{G(!1),v(!0);try{const re=await Se(`/api/workspace/config/validate?workdir=${encodeURIComponent(n.workdir)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rootDir:R,workdir:n.workdir,projectName:n.name,createIfMissing:!0})});if(!re.ok){const Le=await re.json().catch(()=>({}));E((Le==null?void 0:Le.error)??"Failed to create directory"),v(!1);return}const _e=await re.json();if(_e.workspaces&&_e.workspaces.length>0){O(_e.workspaces),X(!0),v(!1);return}await ce()}catch(re){E(re instanceof Error?re.message:"Failed to create directory")}finally{v(!1)}},De=async()=>{X(!1),v(!0),E(null);try{await ce()}catch(re){E(re instanceof Error?re.message:"Failed to save settings")}finally{v(!1)}},Ue=()=>{G(!1),X(!1),p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),H(!1),d()};return i.jsxs(wt,{isOpen:e,onClose:Ue,title:`${n.name} Settings`,size:"lg",footer:i.jsx(Rk,{onCancel:Ue,onSave:de,saving:S,saveDisabled:!te||S}),children:[i.jsxs("div",{className:"flex flex-col gap-5 -mt-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Default Danger Level"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Default danger level for new sessions in this project. Existing sessions are not affected."}),i.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-1 rounded bg-bg-tertiary/50 w-fit",children:[i.jsx("button",{type:"button",onClick:()=>rt(""),className:`px-3 py-1 text-sm font-medium rounded transition-colors ${m===""?"bg-bg-tertiary text-text-primary border border-border":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Use global default (Normal)",children:"Default"}),i.jsx("button",{type:"button",onClick:()=>rt("normal"),className:`px-3 py-1 text-sm font-medium rounded transition-colors ${m==="normal"?"bg-accent-success/20 text-accent-success border border-accent-success/30":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),i.jsx("button",{type:"button",onClick:()=>rt("dangerous"),className:`px-3 py-1 text-sm font-medium rounded transition-colors ${m==="dangerous"?"bg-red-500/20 text-red-400 border border-red-500/30":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Project Path"}),i.jsx("p",{className:"text-sm text-text-muted font-mono",children:n.workdir})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Project Instructions"}),i.jsx("p",{className:"text-sm text-text-muted mb-3 flex-shrink-0",children:"These instructions are injected into prompts when working in this project. They are applied after global instructions but before AGENTS.md files."}),i.jsx("textarea",{value:h,onChange:je,placeholder:"Enter project-specific instructions...",className:"w-full h-32 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:S})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Workspace Setup Command"}),i.jsxs("p",{className:"text-sm text-text-muted mb-3",children:["Command(s) to run after creating a workspace (shared clone). Use"," ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:"&&"})," to chain multiple commands. Example:"," ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:"npm install --prefer-offline"})]}),l&&i.jsx("div",{className:"text-xs text-text-muted mb-2",children:"Loading config..."}),i.jsx("input",{type:"text",value:j,onChange:Qe,placeholder:"npm install --prefer-offline",className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:l||S})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"Workspace Root Directory"}),i.jsxs("p",{className:"text-sm text-text-muted mb-3",children:["Override the default workspace location. Leave empty to use the global directory"," ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:"~/.local/share/openfox/workspaces/"}),". Supports absolute paths or paths relative to the project."]}),i.jsx("input",{type:"text",value:I,onChange:fe,placeholder:"/absolute/or/relative/path",className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:l||S})]}),se.length>0&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:"MCP Servers"}),i.jsx("p",{className:"text-sm text-text-muted mb-3",children:"Override MCP server availability for this project. These overrides apply to new conversations in this project and can be further overridden per conversation from the chat MCP selector."}),i.jsx("div",{className:"space-y-2",children:se.map(re=>{const _e=oe(re.name);return i.jsx(wk,{server:re,expanded:K.has(re.name),onToggleExpand:$e,serverToggleEnabled:!_e,onServerToggle:()=>Me(re.name),tools:re.tools.map(Le=>({...Le,enabled:!Oe(re.name,Le.name)})),onToolToggle:Le=>ze(re.name,Le),statusDot:Gg(_e?"disabled":re.status),statusColor:Vg(_e?"disabled":re.status)},re.name)})})]}),b&&i.jsx("div",{className:"text-sm text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:b})]}),V&&i.jsxs(wt,{isOpen:V,onClose:()=>G(!1),title:"Directory not found",size:"md",footer:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{type:"button",onClick:()=>G(!1),className:"px-4 py-2 text-sm font-medium rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:"Cancel"}),i.jsx("button",{type:"button",onClick:he,className:"px-4 py-2 text-sm font-medium rounded bg-accent-primary text-white hover:opacity-90 transition-colors",children:"Create"})]}),children:[i.jsxs("p",{className:"text-sm text-text-primary",children:["The directory ",i.jsx("code",{className:"text-xs bg-bg-tertiary px-1 rounded",children:M})," does not exist."]}),i.jsx("p",{className:"text-sm text-text-muted mt-2",children:"Would you like to create it?"})]}),Z&&i.jsxs(wt,{isOpen:Z,onClose:()=>X(!1),title:"Orphaned workspaces",size:"md",footer:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{type:"button",onClick:()=>X(!1),className:"px-4 py-2 text-sm font-medium rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:"Cancel"}),i.jsx("button",{type:"button",onClick:De,className:"px-4 py-2 text-sm font-medium rounded bg-red-500 text-white hover:opacity-90 transition-colors",children:"Confirm change"})]}),children:[i.jsxs("p",{className:"text-sm text-text-primary",children:[$.length," existing workspace(s) will not be migrated and will become inaccessible:"]}),i.jsx("ul",{className:"mt-2 space-y-1",children:$.map(re=>i.jsx("li",{className:"text-sm font-mono text-text-muted",children:re.name},re.name))}),i.jsx("p",{className:"text-sm text-text-muted mt-3",children:"Existing workspaces will remain in the old location but will no longer be accessible from this project."})]})]})}const dB={sm:"w-3 h-3",md:"w-4 h-4",lg:"w-5 h-5",xl:"w-6 h-6"},hB="M6 18L18 6M6 6l12 12";function ec({onClick:e,className:t="",size:n="md",variant:r="default"}){const a=r==="overlay"?"bg-accent-error text-white rounded-full flex items-center justify-center hover:bg-accent-error/80 transition-colors":r==="sidebar"?"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors":r==="modal"?"text-text-muted hover:text-text-primary transition-colors":"hover:text-white transition-colors";return i.jsx(wd,{onClick:e,icon:hB,iconSize:dB[n],className:`${a} ${t}`,title:"Close"})}function Kr(e,t){const n=new Set(t.map(r=>r.id));return[...e.filter(r=>!n.has(r.id)),...t]}function qp(e,t){if(!t)return e;const n=e.toLowerCase(),r=t.toLowerCase(),a=new Array(e.length).fill(!1),l=n.indexOf(r);if(l>=0)for(let p=l;p<l+r.length;p++)a[p]=!0;else{let p=0;for(let m=0;m<e.length&&p<r.length;m++)n[m]===r[p]&&(a[m]=!0,p++)}const u=Array.from(e),c=[];let d="",h=a[0]??!1;for(let p=0;p<u.length;p++){const m=u[p]??"";a[p]===h?d+=m:(c.push(h?i.jsx("span",{className:"font-semibold text-accent-primary",children:d},c.length):d),d=m,h=a[p]??!1)}return c.push(h?i.jsx("span",{className:"font-semibold text-accent-primary",children:d},c.length):d),i.jsx(i.Fragment,{children:c})}function ai(e,t){if(!t)return!0;const n=t.toLowerCase().split(/\s+/),r=e.toLowerCase().split(/\s+/);return n.every(a=>{for(const l of r){let u=0;for(let c=0;c<l.length&&u<a.length;c++)l[c]===a[u]&&u++;if(u===a.length)return!0}return!1})}function Ok(e,t,n,r,a){switch(e.key){case"ArrowDown":e.preventDefault(),n(l=>Math.min(l+1,t));break;case"ArrowUp":e.preventDefault(),n(l=>Math.max(l-1,0));break;case"Enter":e.preventDefault(),r();break;case"Escape":e.preventDefault(),a();break}}function Ik({projectId:e,isOpen:t=!0,onClose:n}){const[,r]=Ln(),[a,l]=N.useState(!1),[u,c]=N.useState(null),[d,h]=N.useState(null),[p,m]=N.useState(""),[x,y]=N.useState(!1),w=Re(oe=>oe.sessions),C=Re(oe=>oe.currentSession),_=Re(oe=>oe.unreadSessionIds),S=Re(oe=>oe.deleteSession),v=Re(oe=>oe.deleteAllSessions),b=Re(oe=>oe.loadMoreSessions),E=Re(oe=>oe.sessionsHasMore),j=Re(oe=>oe.sessionsPaginationLoading),T=Re(oe=>oe.sessionsWithPendingConfirmations),D=Re(oe=>oe.pendingPathConfirmations),L=Ft(oe=>oe.currentProject),[I,P]=N.useState(""),[W,H]=N.useState(-1),R=N.useRef(null),U=N.useRef(null),V=N.useRef(!1),G=Gl();Dl(G.sessionSearch,()=>{var oe;if(t&&document.activeElement===R.current){n==null||n();return}t||(V.current=!0,n==null||n()),(oe=R.current)==null||oe.focus()});const Z=N.useRef(null),X=N.useCallback(()=>{E&&!j&&L&&b(L.id)},[E,j,L,b]);N.useEffect(()=>{if(!Z.current||!E)return;const oe=new IntersectionObserver(Oe=>{const Me=Oe[0];Me&&Me.isIntersecting&&X()},{threshold:.1});return oe.observe(Z.current),()=>oe.disconnect()},[E,X]);const $=w.filter(oe=>oe.projectId===(L==null?void 0:L.id)),O=N.useMemo(()=>I?$.filter(oe=>{var ze;const Oe=oe.title??"",Me=(((ze=oe.recentUserPrompts)==null?void 0:ze.map($e=>$e.content))??[]).join(" ");return ai(Oe,I)||ai(Me,I)}):$,[$,I]),M=I.length>0,q=M&&O.length===0;N.useEffect(()=>{H(O.length>0?0:-1)},[O.length]),N.useEffect(()=>{var Oe;if(W<0)return;const oe=(Oe=U.current)==null?void 0:Oe.querySelector(`[data-sidx="${W}"]`);oe==null||oe.scrollIntoView({block:"nearest"})},[W]);const z=(oe,Oe)=>{Oe==null||Oe.stopPropagation(),c(oe)},ee=()=>{u&&(S(u),(C==null?void 0:C.id)===u&&r(`/p/${e}`),c(null))},Q=(oe,Oe)=>{Oe==null||Oe.stopPropagation();const Me=w.find($e=>$e.id===oe),ze=(Me==null?void 0:Me.title)??oe.slice(0,6);m(ze),h(oe)},ne=()=>{if(!d||p.trim()==="")return;const oe=Re.getState().renameSession;oe(d,p.trim()),h(null),m("")},K=()=>{y(!0)},B=()=>{v(e),r(`/p/${e}`),y(!1)},te=oe=>{if(!V.current)return;oe.target.closest('a[href*="/s/"]')&&(V.current=!1,n==null||n())},se=()=>{var oe;P(""),(oe=R.current)==null||oe.focus()},xe=oe=>{var Oe;switch(oe.key){case"Escape":P(""),(Oe=R.current)==null||Oe.blur();break;case"ArrowDown":oe.preventDefault(),H(Me=>Me<O.length-1?Me+1:Me);break;case"ArrowUp":oe.preventDefault(),H(Me=>Me>0?Me-1:0);break;case"Enter":{oe.preventDefault();const Me=O[W];Me&&(r(`/p/${e}/s/${Me.id}`),V.current&&(V.current=!1,n==null||n()));break}}};return i.jsxs(i.Fragment,{children:[t&&n&&i.jsx("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:n}),(()=>{const oe=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-4 border-b border-border flex gap-2",children:[i.jsx(Jn,{href:`/p/${e}/new`,className:"flex-1 block text-center rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-1.5 text-sm","data-testid":"sidebar-new-session-button",children:"+ New Session"}),i.jsx(Zl,{items:[{label:"Edit project settings",onClick:()=>l(!0)},{label:"Delete all sessions",onClick:K,danger:!0}],trigger:i.jsx("button",{className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Options",children:i.jsx(C1,{})})}),n&&i.jsx(ec,{onClick:n,className:"md:hidden",variant:"sidebar",size:"md"})]}),i.jsxs("div",{className:"px-4 py-2 border-b border-border",children:[i.jsxs("div",{className:"relative flex items-center",children:[i.jsx(Wi,{className:"absolute left-2.5 w-3.5 h-3.5 text-text-muted pointer-events-none"}),i.jsx("input",{ref:R,type:"text",value:I,onChange:Oe=>P(Oe.target.value),onKeyDown:xe,placeholder:"Search sessions...",className:"w-full bg-bg-tertiary border border-border rounded pl-8 pr-8 py-1.5 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:ring-1 focus:ring-accent-primary/50 focus:border-accent-primary transition-colors"}),I&&i.jsx("button",{type:"button",onClick:se,className:"absolute right-1.5 p-0.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors","aria-label":"Clear search",children:i.jsx(js,{className:"w-3.5 h-3.5"})})]}),M&&!q&&i.jsxs("div",{className:"mt-1 text-xs text-text-muted px-1",children:[O.length," ",O.length===1?"match":"matches"]})]}),L&&i.jsx(uB,{isOpen:a,onClose:()=>l(!1),project:L}),i.jsx(Rl,{isOpen:u!==null,onClose:()=>c(null),onConfirm:ee,title:"Delete session?",message:"This session will be permanently deleted.",confirmLabel:"Delete session",confirmVariant:"danger"}),i.jsx(Rl,{isOpen:x,onClose:()=>y(!1),onConfirm:B,title:"Delete all sessions?",message:"Delete all sessions in this project? This cannot be undone.",confirmLabel:"Delete all",confirmVariant:"danger"}),i.jsx(wt,{isOpen:d!==null,onClose:()=>{h(null),m("")},title:"Rename session",size:"sm",footer:i.jsx(Rk,{onCancel:()=>{h(null),m("")},onSave:ne,saving:!1,saveDisabled:p.trim()==="",saveLabel:"Rename"}),children:i.jsx("input",{type:"text",value:p,onChange:Oe=>m(Oe.target.value),onKeyDown:Oe=>{Oe.key==="Enter"&&ne()},onFocus:Oe=>Oe.target.select(),className:"w-full px-3 py-2 text-sm text-text-primary bg-bg-tertiary border border-border rounded focus:outline-none focus:ring-1 focus:ring-accent-primary",autoFocus:!0})}),i.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-stable",children:O.length===0?i.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:M?"No matching sessions":"No sessions"}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"divide-y divide-border",ref:U,onClick:te,children:fB(O,C,_,z,Q,e,T,D,I,W)}),j&&i.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"Loading more..."}),i.jsx("div",{ref:Z,className:"h-px"})]})})]});return i.jsx("aside",{className:`
276
276
  ${t?"md:w-[300px] md:shrink-0":"md:w-0 md:shrink-0 md:overflow-hidden md:border-r-0"}
277
277
  md:relative md:h-auto md:translate-x-0
278
278
 
@@ -281,14 +281,14 @@ WARNING: This link could potentially be dangerous`)){const S=window.open();if(S)
281
281
  transition-transform duration-300 ease-in-out
282
282
  ${t?"translate-x-0":"-translate-x-full"}
283
283
  `,children:oe})})()]})}function fB(e,t,n,r,a,l,u,c,d,h){const p=Dk(e);let m=0;return Array.from(p).map(([x,y])=>{const w=y[0];return w?i.jsxs("div",{children:[i.jsx("div",{className:"px-4 py-2 bg-bg-tertiary/30 text-text-muted text-xs font-medium",children:Ak(w.updatedAt)}),y.map(C=>{const _=m++,S=(t==null?void 0:t.id)===C.id,v=_===h,b=n.includes(C.id),E=C.isRunning,j=u.includes(C.id)||S&&c.length>0;return i.jsx("div",{"data-sidx":_,className:`w-full px-4 py-3 text-left hover:bg-bg-tertiary/50 transition-colors group ${S?"bg-bg-tertiary":""} ${v?"bg-accent-primary/10":""}`,children:i.jsxs(Jn,{href:`/p/${l}/s/${C.id}`,className:`block ${S?"text-accent-primary":"text-text-primary"} hover:text-accent-primary`,children:[i.jsxs("div",{className:"flex justify-between items-center mb-1",children:[i.jsx("span",{className:`font-medium truncate text-sm ${S?"text-accent-primary":"text-text-primary"}`,children:d?qp(C.title??C.id.slice(0,6),d):C.title??C.id.slice(0,6)}),i.jsx(Zl,{items:[{label:"Rename session",onClick:T=>a(C.id,T)},{label:"Delete session",onClick:T=>r(C.id,T),danger:!0}],trigger:i.jsx("button",{onClick:T=>T.preventDefault(),className:"p-1.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-all",title:"Options",children:i.jsx(C1,{})})})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[j?i.jsx("span",{title:"Awaiting confirmation",children:i.jsx(ng,{className:"w-3 h-3 text-red-400 flex-shrink-0"})}):E?i.jsx(cT,{}):b&&!S?i.jsx("span",{"aria-label":"Unread activity",title:"Unread activity",className:"w-2 h-2 rounded-full bg-amber-400 flex-shrink-0"}):null,i.jsx("span",{className:"text-text-muted text-xs flex-shrink-0",children:Gd(C.updatedAt)}),i.jsxs("span",{className:"text-text-muted text-xs flex-shrink-0",children:[C.messageCount," messages"]})]})]})},C.id)})]},x):null})}const SS=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧"];function mB(){var u;const e=Ft(c=>c.currentProject),t=Re(c=>c.currentSession),n=_d(),r=N.useRef(0),a=N.useRef(null);N.useEffect(()=>(n?(a.current||(r.current=0),a.current=window.setInterval(()=>{r.current=(r.current+1)%SS.length,l()},150),l()):(a.current&&(clearInterval(a.current),a.current=null),l()),()=>{a.current&&(clearInterval(a.current),a.current=null)}),[n,e,t]);const l=()=>{var p;const d=(p=t==null?void 0:t.metadata)==null?void 0:p.title,h=n?`${SS[r.current]} `:"";e&&d?document.title=`${h}${e.name} - ${d} | OpenFox`:e?document.title=`${h}${e.name} | OpenFox`:document.title=`${h}OpenFox`};return typeof window<"u"&&((u=t==null?void 0:t.metadata)!=null&&u.title)&&window.document.documentElement.setAttribute("data-session-title",t.metadata.title),null}function Mk({isOpen:e,onClose:t,projectName:n,onConfirm:r}){const a=()=>{r(),t()};return i.jsx(Rl,{isOpen:e,onClose:t,onConfirm:a,title:"Delete Project",confirmLabel:"Delete",confirmVariant:"danger",message:i.jsxs(i.Fragment,{children:["This will permanently delete the project"," ",i.jsx("span",{className:"font-semibold text-text-primary",children:n})," and all its sessions from OpenFox. The project files on disk will remain untouched."]})})}function pB({isOpen:e,onClose:t}){const[,n]=Ln(),[r,a]=N.useState(!1),l=Tk(),[u,c]=N.useState(!1),d=Ft(L=>L.projects),h=Ft(L=>L.createProject),p=Ft(L=>L.listProjects),m=Ft(L=>L.deleteProject),[x,y]=N.useState(null),[w,C]=N.useState(null);N.useEffect(()=>{e&&p()},[e,p]);const _=L=>{n(`/p/${L}`),t()},S=(L,I)=>{I.stopPropagation(),y(L)},v=()=>{x&&(m(x.id),y(null))},b=async L=>j(L);function E(L){return L!=null&&typeof L=="object"&&"error"in L&&L.error!=null&&typeof L.error=="object"&&"code"in L.error&&L.error.code==="EACCES"}async function j(L){const I=P1(L),P=await h(I,L);return p(),E(P)?(C(P.error.path||L),!1):P&&"id"in P?(n(`/p/${P.id}`),t(),!0):!1}const T=N.useCallback(()=>{C(null)},[]),D=N.useCallback(async()=>{const L=w;C(null),L&&await j(L)},[w]);return e?i.jsxs(wt,{isOpen:e,onClose:t,title:"Open Project",size:"xl",footer:i.jsx("div",{className:"flex justify-end gap-2",children:i.jsx(Ze,{variant:"secondary",onClick:t,children:"Close"})}),children:[i.jsxs("div",{className:"flex flex-col sm:flex-row flex-1 -m-4",children:[i.jsxs("div",{className:"w-full sm:w-1/2 border-b sm:border-b-0 sm:border-r border-border flex flex-col max-h-[40vh] sm:max-h-[50vh]",children:[i.jsx("div",{className:"p-3 border-b border-border bg-bg-tertiary/30 shrink-0",children:i.jsx("h3",{className:"font-medium text-sm text-text-secondary",children:"Recent Projects"})}),i.jsx("div",{className:"flex-1 overflow-y-auto",children:d.length===0?i.jsxs("div",{className:"p-6 text-center text-text-muted text-sm",children:[i.jsx("p",{className:"mb-2",children:"No recent projects"}),i.jsx("p",{className:"text-xs",children:'Click "Create new project" to add one'})]}):i.jsx("div",{className:"divide-y divide-border",children:d.map(L=>i.jsxs("div",{className:"group flex items-center gap-3 p-3 hover:bg-bg-tertiary/50 transition-colors",children:[i.jsxs("button",{onClick:()=>_(L.id),className:"flex-1 flex items-center gap-3 text-left",children:[i.jsx(Or,{className:"w-5 h-5 text-accent-primary"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"font-medium truncate",children:L.name}),i.jsx("div",{className:"text-xs text-text-muted truncate",children:B1(L.workdir,32)})]})]}),i.jsx("button",{onClick:I=>S(L,I),className:"text-accent-error/70 hover:text-accent-error p-1",title:"Delete project",children:i.jsx(lo,{className:"w-4 h-4"})})]},L.id))})})]}),i.jsx("div",{className:"w-full sm:w-1/2 flex flex-col items-center justify-center p-6 sm:p-8 text-center",children:i.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-sm",children:[i.jsx(Ze,{variant:"primary",onClick:()=>c(!0),children:"Select existing project"}),i.jsx(Ze,{variant:"secondary",onClick:()=>a(!0),"data-testid":"open-project-create-button",children:"Create new project"})]})})]}),r&&i.jsx(Nk,{isOpen:r,onClose:()=>a(!1)}),x&&i.jsx(Mk,{isOpen:!0,onClose:()=>y(null),projectName:x.name,onConfirm:v}),u&&i.jsx(Cd,{initialPath:l??void 0,onSelect:L=>{b(L)},onClose:()=>c(!1)}),w&&i.jsx(jk,{isOpen:!0,onClose:T,path:w,onRetry:D})]}):null}function gB(){const[e,t]=N.useState(!1),[n,r]=N.useState(null),[a,l]=N.useState(""),[u,c]=N.useState(""),d=N.useRef(null),h=Re(U=>U.sessions),p=Ft(U=>U.projects),m=Ft(U=>U.loading),x=Ft(U=>U.listProjects),y=Re(U=>U.listSessions),w=Ft(U=>U.deleteProject),C=Re(U=>U.connectionStatus);N.useEffect(()=>{C==="connected"&&(x(),y())},[C,x,y]),N.useEffect(()=>{const U=setTimeout(()=>c(a),150);return()=>clearTimeout(U)},[a]);const{matchCount:_,filteredSessionIds:S,relevanceScores:v,matchTypes:b,promptSnippets:E}=N.useMemo(()=>{if(!u)return{matchCount:0,filteredSessionIds:null,relevanceScores:null,matchTypes:null,promptSnippets:null};const U=new Map(p.map($=>[$.id,$])),V=new Map,G=new Map,Z=new Map,X=h.filter($=>{var K;const O=U.get($.projectId),M=(O==null?void 0:O.name)??"",q=$.title??"",z=((K=$.recentUserPrompts)==null?void 0:K.map(B=>B.content))??[],ee=z.join(" ");let Q=0,ne="";if(ai(q,u)&&(Q+=10,ne="title"),ai(ee,u)){Q+=3,ne=ne==="title"?"title":"prompts";const B=z.find(te=>ai(te,u));if(B){const te=B.toLowerCase().indexOf(u.toLowerCase());if(te>=0){const se=Math.max(0,te-30),xe=Math.min(B.length,te+u.length+30);Z.set($.id,(se>0?"…":"")+B.slice(se,xe)+(xe<B.length?"…":""))}else Z.set($.id,B.slice(0,80)+(B.length>80?"…":""))}}return ai(M,u)&&(Q+=1,ne=ne||"project"),V.set($.id,Q),G.set($.id,ne),Q>0});return{matchCount:X.length,filteredSessionIds:new Set(X.map($=>$.id)),relevanceScores:V,matchTypes:G,promptSnippets:Z}},[h,u,p]),j=N.useMemo(()=>{const U=new Map;for(const V of h){const G=new Date(V.updatedAt).getTime(),Z=U.get(V.projectId)??0;G>Z&&U.set(V.projectId,G)}return U},[h]),T=N.useMemo(()=>{const U=new Map;for(const V of h){const G=U.get(V.projectId);G?G.push(V):U.set(V.projectId,[V])}for(const[,V]of U)V.sort((G,Z)=>new Date(Z.updatedAt).getTime()-new Date(G.updatedAt).getTime());return U},[h]),D=N.useMemo(()=>{let U=p;return u&&S&&(U=p.filter(V=>{const G=T.get(V.id);return G==null?void 0:G.some(Z=>S.has(Z.id))})),[...U].sort((V,G)=>{const Z=j.get(V.id)??new Date(V.updatedAt).getTime();return(j.get(G.id)??new Date(G.updatedAt).getTime())-Z})},[p,T,u,S,j]),L=N.useCallback(U=>{const V=T.get(U);return V?u&&S&&v?V.filter(G=>S.has(G.id)).sort((G,Z)=>{const X=(v.get(Z.id)??0)-(v.get(G.id)??0);return X!==0?X:new Date(Z.updatedAt).getTime()-new Date(G.updatedAt).getTime()}):V.slice(0,5):[]},[T,u,S,v]),I=()=>{t(!0)},P=()=>{var U;l(""),c(""),(U=d.current)==null||U.focus()},W=U=>{var V;U.key==="Escape"&&(P(),(V=d.current)==null||V.blur())},H=u.length>0,R=H&&_===0;return i.jsxs("div",{className:"flex-1 flex flex-col overflow-y-auto bg-primary",children:[i.jsxs("div",{className:"max-w-5xl mx-auto w-full p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6 md:mb-8 flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-3xl font-bold text-accent-primary",children:"OpenFox"}),i.jsx("p",{className:"text-text-secondary",children:"Local LLM-powered coding assistant with contract-driven execution"})]}),i.jsx(Ze,{variant:"primary",onClick:I,children:"Open Project"})]}),h.length>0&&i.jsxs("div",{className:"mb-4 md:mb-6 relative",children:[i.jsxs("div",{className:"relative flex items-center",children:[i.jsx(Wi,{className:"absolute left-3 w-4 h-4 text-text-muted pointer-events-none"}),i.jsx("input",{ref:d,type:"text",value:a,onChange:U=>l(U.target.value),onKeyDown:W,placeholder:"Search sessions by title or keyword...",className:"w-full bg-bg-secondary border border-border rounded-lg pl-10 pr-10 py-2.5 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 focus:border-accent-primary transition-colors"}),a&&i.jsx("button",{type:"button",onClick:P,className:"absolute right-3 p-0.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors","aria-label":"Clear search",children:i.jsx(js,{className:"w-4 h-4"})})]}),H&&!R&&i.jsxs("div",{className:"mt-1.5 text-xs text-text-muted px-1",children:[_," ",_===1?"match":"matches"]})]}),R?i.jsxs("div",{className:"text-center py-16 text-text-muted",children:[i.jsx(Wi,{className:"w-10 h-10 mx-auto mb-4 opacity-40"}),i.jsxs("p",{className:"text-lg",children:["No sessions matching ",i.jsxs("span",{className:"text-text-primary font-medium",children:["“",u,"”"]})]}),i.jsx("p",{className:"mt-2 text-sm",children:"Try a different keyword or clear the search"})]}):D.map(U=>{const V=L(U.id);return i.jsx("div",{className:"mb-6 md:mb-8",children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-lg overflow-hidden",children:[i.jsxs("div",{className:"p-3 md:p-4 border-b border-border flex items-center justify-between gap-2",children:[i.jsxs(Jn,{href:`/p/${U.id}`,className:"flex items-center gap-2 cursor-pointer hover:opacity-80 transition-opacity flex-1",children:[i.jsx(Or,{className:"w-5 h-5 text-accent-primary flex-shrink-0"}),i.jsx("span",{className:"text-text-primary font-semibold",children:U.name})]}),i.jsx(Jn,{href:`/p/${U.id}/new`,className:"rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-1.5 py-1 text-xs",children:"+ New Session"}),i.jsx("button",{type:"button",onClick:()=>r({id:U.id,name:U.name}),className:"p-1.5 rounded text-text-muted hover:text-accent-error hover:bg-accent-error/10 transition-colors",title:"Delete project",children:i.jsx(lo,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"divide-y divide-border",children:V.length>0?V.map(G=>{const Z=p.find(M=>G.projectId===M.id),X=Z?`/p/${Z.id}/s/${G.id}`:"#",$=G.title??G.id.slice(0,8),O=b==null?void 0:b.get(G.id);return i.jsx(Jn,{href:X,className:"block p-3 md:p-4 hover:bg-bg-tertiary/50 cursor-pointer transition-colors",children:i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm text-text-muted truncate",children:H&&O==="title"?qp($,u):$}),H&&O&&O!=="title"&&i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1",children:[i.jsx("span",{className:"text-[10px] font-medium text-accent-primary border border-accent-primary/30 bg-accent-primary/8 rounded px-1 py-0.5 leading-none",children:O==="prompts"?"prompts":"project"}),O==="prompts"&&(E==null?void 0:E.get(G.id))&&i.jsx("span",{className:"text-[11px] text-text-muted truncate max-w-[250px]",children:qp(E.get(G.id),u)})]})]})}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx("span",{className:"text-text-muted text-xs",children:eB(G.updatedAt)}),i.jsxs("span",{className:"text-text-muted text-xs",children:[G.messageCount," msgs"]})]})]})},G.id)}):i.jsx("div",{className:"p-3 md:p-4 text-text-muted text-sm",children:"No sessions yet"})})]})},U.id)}),!H&&D.length===0&&!m&&i.jsx("div",{className:"text-center py-12 text-text-muted",children:"No projects yet. Open a project to get started."}),m&&i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(hi,{})})]}),e&&i.jsx(pB,{isOpen:e,onClose:()=>t(!1)}),n&&i.jsx(Mk,{isOpen:!0,onClose:()=>r(null),projectName:n.name,onConfirm:()=>w(n.id)})]})}function xB(){const[,e]=oo("/p/:projectId/new"),[,t]=Ln(),n=e==null?void 0:e.projectId,r=Re(u=>u.createSession),a=Re(u=>u.resetPendingSessionCreate),l=N.useCallback(async()=>{if(!n)return;const u=await r(n);u?(t(`/p/${n}/s/${u.id}`),a()):(t(`/p/${n}`),a())},[n,r,t,a]);return N.useEffect(()=>{l()},[l]),i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx(hi,{})})}function yB(){const e=Ft(t=>t.currentProject);return i.jsx("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center",children:i.jsxs("div",{className:"max-w-md",children:[i.jsx("h2",{className:"text-xl font-semibold text-text-primary mb-2",children:(e==null?void 0:e.name)??"Project"}),i.jsx("p",{className:"text-text-secondary mb-6",children:"No session selected"}),i.jsxs("div",{className:"flex flex-col gap-3",children:[e&&i.jsx(Jn,{href:`/p/${e.id}/new`,"data-testid":"create-new-session-button",className:"block w-full rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-2 text-center",children:"Create New Session"}),i.jsx("p",{className:"text-sm text-text-muted",children:"Or select an existing session from the sidebar"})]})]})})}const gl=e=>Math.round(e*10)/10;function bB(e){return typeof e.totalTime=="number"&&!Number.isNaN(e.totalTime)}function Kp(e){return{providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model}}function vB(e){return`${e.providerId}::${e.model}`}function _B(e){return`${e.providerName} > ${e.model}`}function wS(e){let t=0,n=0,r=0,a=0,l=0,u=0;const c=[],d=[];let h=0;for(const[x,y]of e.entries()){const w=y.stats,C=Kp(w);t+=w.totalTime,n+=w.toolTime,r+=w.prefillTokens,a+=w.generationTokens;const _=w.prefillSpeed>0?w.prefillTokens/w.prefillSpeed:0,S=w.generationSpeed>0?w.generationTokens/w.generationSpeed:0;l+=_,u+=S,c.push({messageId:y.id,timestamp:y.timestamp,...C,mode:w.mode,responseIndex:x+1,prefillTokens:w.prefillTokens,generationTokens:w.generationTokens,prefillSpeed:w.prefillSpeed,generationSpeed:w.generationSpeed,totalTime:w.totalTime,aiTime:w.totalTime-w.toolTime,toolTime:w.toolTime});const v=w.llmCalls??[];for(const b of v)h+=1,d.push({messageId:y.id,timestamp:b.timestamp??y.timestamp,providerId:b.providerId,providerName:b.providerName,backend:b.backend,model:b.model,mode:w.mode,responseIndex:x+1,sessionCallIndex:h,callIndex:b.callIndex,promptTokens:b.promptTokens,completionTokens:b.completionTokens,ttft:b.ttft,completionTime:b.completionTime,prefillSpeed:b.prefillSpeed,generationSpeed:b.generationSpeed,totalTime:b.totalTime,...b.temperature!==void 0&&{temperature:b.temperature},...b.topP!==void 0&&{topP:b.topP},...b.topK!==void 0&&{topK:b.topK},...b.maxTokens!==void 0&&{maxTokens:b.maxTokens}})}const p=l>0?gl(r/l):0,m=u>0?gl(a/u):0;return{totalTime:gl(t),aiTime:gl(t-n),toolTime:gl(n),prefillTokens:r,generationTokens:a,avgPrefillSpeed:p,avgGenerationSpeed:m,responseCount:e.length,llmCallCount:d.length,dataPoints:c,callDataPoints:d}}function SB(e){const t=e.filter(a=>a.stats!==void 0&&a.stats!==null&&bB(a.stats)).sort((a,l)=>new Date(a.timestamp).getTime()-new Date(l.timestamp).getTime());if(t.length===0)return null;const n=new Map;for(const a of t){const l=vB(Kp(a.stats)),u=n.get(l)??[];n.set(l,[...u,a])}const r=Array.from(n.entries()).map(([a,l])=>{const u=Kp(l[0].stats),c=wS(l);return{...u,key:a,label:_B(u),...c}});return{...wS(t),modelGroups:r}}function wB(e){return N.useMemo(()=>SB(e),[e])}function Wg(){var a;const e=Re(l=>l.gitStatus),t=Re(l=>l.currentSession),[n,r]=N.useState(!0);return N.useEffect(()=>{t!=null&&t.workdir&&r(!1)},[t==null?void 0:t.workdir]),{branch:(e==null?void 0:e.branch)??null,diff:{files:((a=e==null?void 0:e.diff)==null?void 0:a.files)??[],loading:n,error:null}}}function so(e){return e.toLocaleString("en-US").replace(/,/g," ")}function CS(e){return Number.isFinite(e)?e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1):"0"}function Xr(e){if(!Number.isFinite(e))return"0s";if(e<10)return`${e.toFixed(1)}s`;const t=Math.round(e);if(t<60)return`${t}s`;if(t<3600){const u=Math.floor(t/60),c=t%60;return`${u}m ${c}s`}const n=Math.floor(t/3600),r=t%3600,a=Math.floor(r/60),l=r%60;return`${n}h ${a}m ${l}s`}const kS=Object.assign(Object.create(null),{criteria:"Acceptance Criteria",review_findings:"Review Findings",todos:"Tasks"}),ES=Object.assign(Object.create(null),{criteria:"criteria",review_findings:"review findings",todos:"tasks"});function to(e){return Object.hasOwn(kS,e)?kS[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function CB(e){return Object.hasOwn(ES,e)?ES[e]:e.replace(/_/g," ")}const jS=["▁","▂","▃","▄","▅","▆","▇","█"];function kB(e,t,n){if(n===t)return 4;const r=(e-t)/(n-t);return Math.min(7,Math.max(0,Math.round(r*7)))}function EB(e,t){if(e===t){const a=Math.max(Math.abs(e)*.05,1);return{minY:e-a,maxY:t+a}}const n=t-e,r=Math.max(n*.1,.1);return{minY:e-r,maxY:t+r}}function jB(e,t){if(e.length===0||t<=0)return{blocks:"",minX:0,maxX:0,minY:0,maxY:0};const n=[...e].sort((x,y)=>x.x-y.x),r=n[0].x,a=n[n.length-1].x,l=Math.min(...n.map(x=>x.y)),u=Math.max(...n.map(x=>x.y)),{minY:c,maxY:d}=EB(l,u),h=Math.max(0,c),p=Array.from({length:t},()=>" "),m=new Map;for(const x of n){const y=a===r?0:Math.round((x.x-r)/(a-r)*(t-1)),w=m.get(y)??[];m.set(y,[...w,x.y])}for(const[x,y]of m){const w=Math.max(...y);p[x]=jS[kB(w,c,d)]??jS[0]}return{blocks:p.join(""),minX:r,maxX:a,minY:h,maxY:d}}function NS(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function TS({data:e,width:t=60,height:n=78,label:r,xLabel:a,yLabel:l,showAxes:u=!0,formatY:c=NS,formatX:d=NS}){const h=N.useMemo(()=>{const p=jB(e,t),m=Math.max(t*6,240),x=10,y=8,C=[...e].sort((b,E)=>b.x-E.x).map(b=>{const E=p.maxX===p.minX?m/2:x+(b.x-p.minX)/(p.maxX-p.minX)*(m-x*2),j=p.maxY===p.minY?n/2:y+(p.maxY-b.y)/(p.maxY-p.minY)*(n-y*2);return{...b,cx:E,cy:j,leftPercent:E/m*100,topPercent:j/n*100}}),_=C.map((b,E)=>`${E===0?"M":"L"} ${b.cx.toFixed(1)} ${b.cy.toFixed(1)}`).join(" "),v=[p.maxY,(p.maxY+p.minY)/2,p.minY].map(b=>({value:b,y:p.maxY===p.minY?n/2:y+(p.maxY-b)/(p.maxY-p.minY)*(n-y*2)}));return{...p,chartWidth:m,points:C,path:_,gridLines:v}},[e,n,t]);return e.length===0?i.jsxs("div",{className:"font-mono text-text-muted text-xs",children:[r&&i.jsx("div",{className:"mb-1",children:r}),i.jsx("div",{children:"No data"})]}):i.jsxs("div",{className:"font-mono text-xs",children:[r&&i.jsx("div",{className:"text-text-secondary mb-2",children:r}),i.jsxs("div",{className:"flex gap-3",children:[u&&i.jsx("div",{className:"w-12 h-[78px] flex flex-col justify-between text-right text-text-muted",children:h.gridLines.map(p=>i.jsx("span",{children:c(p.value)},`${p.value}-${p.y}`))}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsxs("div",{className:"relative h-[78px]",children:[i.jsxs("svg",{viewBox:`0 0 ${h.chartWidth} ${n}`,className:"w-full h-[78px] overflow-visible",preserveAspectRatio:"none","aria-hidden":"true",children:[h.gridLines.map(p=>i.jsx("line",{x1:"0",x2:h.chartWidth,y1:p.y,y2:p.y,stroke:"currentColor",strokeDasharray:"3 4",className:"text-border/60"},`grid-${p.y}`)),h.points.map(p=>i.jsx("line",{x1:p.cx,x2:p.cx,y1:n-4,y2:p.cy,stroke:"currentColor",className:"text-border/40"},`guide-${p.cx}-${p.cy}`)),h.points.length>1&&i.jsx("path",{d:h.path,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-accent-primary/45"})]}),h.points.map(p=>i.jsx("div",{className:"absolute -translate-x-1/2 -translate-y-1/2",style:{left:`${p.leftPercent}%`,top:`${p.topPercent}%`},title:`${d(p.x)} -> ${c(p.y)}`,children:i.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-accent-primary/20 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary"})})},`point-${p.x}-${p.y}`))]})})]}),u&&i.jsxs("div",{className:"flex items-start gap-3 text-text-muted mt-1",children:[i.jsx("span",{className:"w-12"}),i.jsxs("span",{className:"flex-1 flex justify-between",children:[i.jsx("span",{children:d(h.minX)}),i.jsx("span",{children:a}),i.jsx("span",{children:d(h.maxX)})]})]}),l&&u&&i.jsx("div",{className:"text-text-muted mt-1 text-center",children:l})]})}function NB({data:e,prefillLabel:t="Prefill Speed (tok/s) by Response",generationLabel:n="Generation Speed (tok/s) by Response",xLabel:r="response",width:a=60}){const l=e.map(c=>({x:c.x,y:c.ppSpeed})),u=e.map(c=>({x:c.x,y:c.tgSpeed}));return i.jsxs("div",{className:"space-y-5",children:[i.jsx(TS,{data:l,width:a,label:t,xLabel:r}),i.jsx(TS,{data:u,width:a,label:n,xLabel:r})]})}function TB(e){const t=new Map;for(const n of e.callDataPoints){const r=t.get(n.messageId)??[];t.set(n.messageId,[...r,n])}return e.dataPoints.map(n=>{const r=[...t.get(n.messageId)??[]].sort((a,l)=>a.callIndex-l.callIndex);return{...n,callCount:r.length,calls:r,isExpandable:r.length>1}})}function AB(e){return{mode:"responses",xLabel:"response",prefillLabel:"Prefill Speed (tok/s) by Response",generationLabel:"Generation Speed (tok/s) by Response",points:e.dataPoints.map(t=>({x:t.responseIndex,ppSpeed:t.prefillSpeed,tgSpeed:t.generationSpeed}))}}function LB(e){return{mode:"calls",xLabel:"context",prefillLabel:"Prefill Speed (tok/s) vs Context",generationLabel:"Generation Speed (tok/s) vs Context",points:e.callDataPoints.map(t=>({x:t.promptTokens,ppSpeed:t.prefillSpeed,tgSpeed:t.generationSpeed}))}}function DB(e){return e.callDataPoints.length>0?LB(e):AB(e)}function Gi(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function Sl(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function RB(e){if(e.length===0)return"0 ctx";const t=Math.min(...e),n=Math.max(...e);return t===n?`${Gi(t)} ctx`:`${Gi(t)}-${Gi(n)} ctx`}function hd(e){return`${Sl(e)} t/s`}function Pk(e){try{return new Date(e).toLocaleTimeString("en-US",{hour12:!1})}catch{return e}}function OB(e){return{exportedAt:new Date().toISOString(),providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model,label:e.label,summary:{totalTime:e.totalTime,aiTime:e.aiTime,toolTime:e.toolTime,prefillTokens:e.prefillTokens,generationTokens:e.generationTokens,avgPrefillSpeed:e.avgPrefillSpeed,avgGenerationSpeed:e.avgGenerationSpeed,responseCount:e.responseCount,llmCallCount:e.llmCallCount},responses:e.dataPoints.map(t=>({responseIndex:t.responseIndex,timestamp:t.timestamp,mode:t.mode,prefillTokens:t.prefillTokens,generationTokens:t.generationTokens,prefillSpeed:t.prefillSpeed,generationSpeed:t.generationSpeed,totalTime:t.totalTime,aiTime:t.aiTime,toolTime:t.toolTime})),llmCalls:e.callDataPoints.map(t=>({sessionCallIndex:t.sessionCallIndex,responseIndex:t.responseIndex,callIndex:t.callIndex,timestamp:t.timestamp,mode:t.mode,promptTokens:t.promptTokens,completionTokens:t.completionTokens,ttft:t.ttft,completionTime:t.completionTime,prefillSpeed:t.prefillSpeed,generationSpeed:t.generationSpeed,totalTime:t.totalTime}))}}function IB({isOpen:e,onClose:t,stats:n}){const r=N.useRef(null),[a,l]=N.useState({}),[u,c]=N.useState(()=>{var w;return((w=n.modelGroups[0])==null?void 0:w.key)??""});N.useEffect(()=>{var w;n.modelGroups.some(C=>C.key===u)||c(((w=n.modelGroups[0])==null?void 0:w.key)??"")},[u,n.modelGroups]);const d=N.useMemo(()=>n.modelGroups.find(w=>w.key===u)??n.modelGroups[0],[u,n.modelGroups]),h=N.useMemo(()=>d?TB(d):[],[d]),p=N.useMemo(()=>d?DB(d):{mode:"responses",xLabel:"response",prefillLabel:"",generationLabel:"",points:[]},[d]),m=N.useCallback(w=>{l(C=>({...C,[w]:!C[w]}))},[]),x=N.useCallback(()=>{if(!d)return;const w=OB(d);navigator.clipboard.writeText(JSON.stringify(w,null,2)).catch(C=>console.error("Failed to copy:",C))},[d]),y=N.useCallback(async()=>{if(r.current)try{const w=(await J(async()=>{const{default:S}=await import("./html2canvas.esm-QH1iLAAe.js");return{default:S}},[])).default,C=await w(r.current,{backgroundColor:"#1a1a1a",scale:2}),_=document.createElement("a");_.download=`openfox-stats-${new Date().toISOString().slice(0,10)}.png`,_.href=C.toDataURL("image/png"),_.click()}catch(w){console.error("Failed to export PNG:",w),x()}},[x]);return i.jsx(wt,{isOpen:e,onClose:t,title:"Session Stats",size:"lg",children:i.jsxs("div",{ref:r,className:"space-y-6",children:[i.jsx("section",{children:i.jsx("div",{className:"flex flex-wrap gap-2",children:n.modelGroups.map(w=>i.jsx("button",{onClick:()=>c(w.key),className:`px-3 py-1.5 rounded border text-xs transition-colors ${w.key===(d==null?void 0:d.key)?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-primary hover:bg-bg-tertiary/40"}`,title:w.label,children:w.label},w.key))})}),d&&i.jsxs("section",{children:[i.jsx("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:"Summary"}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[i.jsx(ys,{label:"AI Time",value:Xr(d.aiTime)}),i.jsx(ys,{label:"Total Time",value:Xr(d.totalTime)}),i.jsx(ys,{label:"Tool Time",value:Xr(d.toolTime)}),i.jsx(ys,{label:"Responses",value:d.responseCount.toString()}),i.jsx(ys,{label:"LLM Calls",value:d.llmCallCount.toString()})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-3",children:[i.jsx(ys,{label:"Prefill Tokens",value:Gi(d.prefillTokens),subValue:`@ ${Sl(d.avgPrefillSpeed)} tok/s`}),i.jsx(ys,{label:"Gen Tokens",value:Gi(d.generationTokens),subValue:`@ ${Sl(d.avgGenerationSpeed)} tok/s`}),i.jsx(ys,{label:"Avg PP Speed",value:`${Sl(d.avgPrefillSpeed)}`,subValue:"tok/s"}),i.jsx(ys,{label:"Avg TG Speed",value:`${Sl(d.avgGenerationSpeed)}`,subValue:"tok/s"})]})]}),d&&p.points.length>1&&i.jsxs("section",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-text-secondary uppercase tracking-wide",children:"Performance Progression"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:x,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Copy JSON"}),i.jsx("button",{onClick:y,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Save PNG"})]})]}),i.jsx("div",{className:"bg-bg-tertiary/50 rounded p-4",children:i.jsx(NB,{data:p.points,width:50,prefillLabel:p.prefillLabel,generationLabel:p.generationLabel,xLabel:p.xLabel})})]}),d&&i.jsxs("section",{children:[i.jsxs("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:["Response Log (",d.responseCount," responses)"]}),i.jsx("div",{className:"overflow-y-auto bg-bg-tertiary/30 rounded",children:i.jsxs("table",{className:"w-full table-fixed border-separate border-spacing-0 text-xs",children:[i.jsxs("colgroup",{children:[i.jsx("col",{className:"w-[7%]"}),i.jsx("col",{className:"w-[14%]"}),i.jsx("col",{className:"w-[10%]"}),i.jsx("col",{className:"w-[14%]"}),i.jsx("col",{className:"w-[14%]"}),i.jsx("col",{className:"w-[14%]"}),i.jsx("col",{className:"w-[11%]"}),i.jsx("col",{className:"w-[2%]"})]}),i.jsx("thead",{children:i.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-text-muted/80",children:[i.jsx("th",{className:"px-3 py-2 text-center font-medium",children:"#"}),i.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"At"}),i.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Time"}),i.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Context"}),i.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"PP t/s"}),i.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"TG t/s"}),i.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Calls"}),i.jsx("th",{className:"px-2 py-2"})]})}),i.jsx("tbody",{children:h.map((w,C)=>i.jsxs(N.Fragment,{children:[i.jsx(MB,{row:w,index:C,isExpanded:a[w.messageId]??!1,onToggle:w.isExpandable?()=>m(w.messageId):void 0}),(a[w.messageId]??!1)&&w.calls.map((_,S)=>i.jsx(PB,{dataPoint:_,index:S},`${_.messageId}-${_.callIndex}`))]},w.messageId))})]})})]})]})})}function ys({label:e,value:t,subValue:n}){return i.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[i.jsx("div",{className:"text-text-muted text-xs mb-1",children:e}),i.jsx("div",{className:"text-text-primary text-lg font-semibold",children:t}),n&&i.jsx("div",{className:"text-text-muted text-xs",children:n})]})}function MB({row:e,index:t,isExpanded:n,onToggle:r}){const a=e.calls.length>0?RB(e.calls.map(l=>l.promptTokens)):`${Gi(e.prefillTokens)} ctx`;return i.jsxs("tr",{onClick:r,className:`${t%2===0?"bg-bg-tertiary/20":""} ${r?"cursor-pointer hover:bg-bg-tertiary/35 transition-colors":""}`,children:[i.jsx("td",{className:"px-3 py-2 text-center text-text-muted align-middle",children:e.responseIndex}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:Pk(e.timestamp)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:Xr(e.totalTime)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:a.replace(/ ctx$/,"")}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:hd(e.prefillSpeed)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:hd(e.generationSpeed)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callCount}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:e.isExpandable?n?"v":">":""})]})}function PB({dataPoint:e,index:t}){const n=e.temperature!==void 0||e.topP!==void 0||e.topK!==void 0||e.maxTokens!==void 0;return i.jsxs(i.Fragment,{children:[i.jsxs("tr",{className:`${t%2===0?"bg-bg-tertiary/10":"bg-bg-tertiary/5"}`,children:[i.jsxs("td",{className:"px-3 py-2 pl-6 text-center text-text-muted align-middle border-l border-border/60",children:["c",e.callIndex]}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:Pk(e.timestamp)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:Xr(e.totalTime)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Gi(e.promptTokens)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:hd(e.prefillSpeed)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:hd(e.generationSpeed)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callIndex}),i.jsx("td",{className:"px-2 py-2"})]}),n&&i.jsx("tr",{className:`${t%2===0?"bg-bg-tertiary/5":"bg-bg-tertiary/[2.5%]"}`,children:i.jsx("td",{colSpan:8,className:"px-6 py-1.5 border-l border-border/60",children:i.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-text-muted",children:[e.temperature!==void 0&&i.jsxs("span",{children:["temp: ",e.temperature.toFixed(2)]}),e.topP!==void 0&&i.jsxs("span",{children:["topP: ",e.topP.toFixed(2)]}),e.topK!==void 0&&i.jsxs("span",{children:["topK: ",e.topK]}),e.maxTokens!==void 0&&i.jsxs("span",{children:["maxTok: ",e.maxTokens]})]})})})]})}const BB={passed:{icon:"✓",color:"text-accent-success"},completed:{icon:"◉",color:"text-purple-400"},failed:{icon:"✗",color:"text-accent-error"},resolved:{icon:"✓",color:"text-accent-success"},dismissed:{icon:"–",color:"text-text-muted"},open:{icon:"○",color:"text-accent-warning"},pending:{icon:"○",color:"text-text-muted"},in_progress:{icon:"◌",color:"text-accent-warning"}},Bk=["open","in_progress","pending","completed","resolved","dismissed","passed","failed"];function $B(e){return BB[e]??{icon:"○",color:"text-text-muted"}}function qg(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}const po=N.memo(function({status:t,className:n="text-xs leading-tight flex-shrink-0"}){const{icon:r,color:a}=$B(t);return i.jsx("span",{className:`${a} ${n}`,children:r})});function fd({entries:e,title:t}){const n=N.useMemo(()=>e.reduce((r,a)=>(r[a.status]=(r[a.status]??0)+1,r),{}),[e]);return i.jsxs("h3",{className:"text-sm font-semibold text-text-primary mb-2 flex items-center justify-between",children:[i.jsx("span",{children:t}),Object.keys(n).length>0&&i.jsx("span",{className:"font-normal text-xs flex items-center gap-1.5",children:Bk.map(r=>{const a=n[r];return a?i.jsxs("span",{className:"flex items-center gap-0.5",children:[i.jsx(po,{status:r}),i.jsx("span",{children:a})]},r):null})})]})}const $k=N.memo(function({entries:t,title:n,onClearAll:r}){const[a,l]=N.useState(!1),u=N.useCallback(()=>{l(!1),r==null||r()},[r]);return t.length===0?null:i.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[n&&i.jsx("div",{className:"px-1.5 py-1 border-b border-border bg-secondary",children:i.jsx("span",{className:"text-xs font-medium text-text-muted",children:n})}),i.jsx("div",{className:"bg-primary",children:t.map((c,d)=>i.jsxs("div",{className:`flex items-start gap-1 px-1.5 py-1 ${d>0?"border-t border-border":""}`,children:[i.jsx(po,{status:c.status}),i.jsxs("div",{className:"flex-1 min-w-0 text-xs truncate",children:[i.jsxs("span",{className:"text-text-muted",children:["[",c.id,"]"]})," ",qg(c.description)]})]},c.id??d))}),r&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary flex items-center gap-2",children:i.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-error transition-colors ml-auto cursor-pointer",title:"Clear all",children:[i.jsx(lo,{className:"w-3 h-3"}),"Clear all"]})}),a&&i.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:i.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[i.jsx("span",{className:"text-xs text-accent-error",children:"Clear all?"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:u,className:"text-xs text-accent-error hover:text-accent-error/70 transition-colors cursor-pointer",children:"Yes"}),i.jsx("button",{onClick:()=>l(!1),className:"text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:"No"})]})]})})]})]})}),zB={criteria:["pending","completed","passed","failed"],todos:["pending","in_progress","completed"],review_findings:["open","resolved","dismissed"]},HB=["pending","completed","failed","dismissed"];function UB(e){return zB[e]??HB}function FB(e,t){const n=t.indexOf(e);return n===-1?t[0]??"pending":t[(n+1)%t.length]??"pending"}function zk({entries:e,sessionId:t,metadataKey:n,title:r,isOpen:a,onClose:l}){const[u,c]=N.useState(e),[d,h]=N.useState(null),[p,m]=N.useState(""),[x,y]=N.useState(!1),[w,C]=N.useState(""),_=N.useRef(null),S=N.useRef(null),v=N.useCallback(()=>{const H=S.current;H&&(H.style.height="auto",H.style.height=H.scrollHeight+"px")},[]);N.useEffect(()=>{c(e)},[e]),N.useEffect(()=>{var H;d&&(v(),(H=S.current)==null||H.focus())},[d,v]),N.useEffect(()=>{var H;x&&((H=_.current)==null||H.focus())},[x]);const b=N.useCallback(H=>{c(H),Se(`/api/sessions/${t}/metadata/${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:H})}).catch(R=>console.error(`Failed to sync ${n}:`,R))},[t,n]),E=N.useCallback(H=>{const R=UB(n),U=u.map(V=>V.id===H?{...V,status:FB(V.status,R)}:V);b(U)},[u,n,b]),j=N.useCallback((H,R)=>{h(H),m(R)},[]),T=N.useCallback((H,R,U)=>{var Z;const V=(R.trim()||((Z=U.find(X=>X.id===H))==null?void 0:Z.description))??"",G=U.map(X=>X.id===H?{...X,description:V}:X);b(G)},[b]),D=N.useCallback(()=>{d&&(T(d,p,u),h(null))},[d,p,u,T]),L=N.useCallback(H=>{H.key==="Enter"&&D(),H.key==="Escape"&&(H.stopPropagation(),h(null))},[D]),I=N.useCallback(H=>{b(u.filter(R=>R.id!==H))},[u,b]),P=N.useCallback(()=>{const H=w.trim();if(!H)return;const R=u.map(V=>Number(V.id)).filter(V=>Number.isInteger(V)&&V>=0),U=String(Math.max(-1,...R)+1);b([...u,{id:U,description:H,status:"pending"}]),C("")},[w,u,b]),W=N.useCallback(H=>{H.key==="Enter"&&(H.preventDefault(),P()),H.key==="Escape"&&(y(!1),C(""))},[P]);return i.jsxs(wt,{isOpen:a,onClose:l,title:r,size:"full",showCloseButton:!0,closeOnEscape:!0,children:[i.jsxs("ul",{className:"space-y-1",children:[u.map((H,R)=>{const U=d===H.id,V=i.jsxs("button",{onClick:()=>j(H.id,H.description),className:"text-sm text-text-primary text-left hover:text-accent-primary transition-colors w-full cursor-pointer",title:"Click to edit",children:[i.jsxs("span",{className:"text-text-muted",children:["[",H.id,"]"]})," ",i.jsx("span",{children:qg(H.description)})]}),G=U?i.jsx("textarea",{ref:S,value:p,onChange:Z=>{m(Z.target.value),v()},onBlur:D,onKeyDown:L,className:"w-full bg-bg-tertiary text-text-primary text-sm px-2 py-1 rounded border border-border focus:outline-none focus:border-accent-primary resize-none",rows:1}):V;return i.jsxs("li",{className:`flex items-start gap-2 px-2 py-1.5 ${R>0?"border-t border-border":""}`,children:[i.jsx("button",{onClick:()=>E(H.id),className:"flex-shrink-0 cursor-pointer hover:opacity-70 transition-opacity mt-0.5",title:"Click to cycle status",children:i.jsx(po,{status:H.status})}),i.jsx("div",{className:"flex-1 min-w-0",children:G}),i.jsx("button",{onClick:()=>I(H.id),className:"flex-shrink-0 text-text-muted hover:text-accent-error transition-colors cursor-pointer mt-0.5 ml-auto",title:"Delete entry",children:i.jsx("span",{className:"flex",children:i.jsx(js,{className:"w-4 h-4"})})})]},H.id)}),u.length===0&&i.jsx("p",{className:"text-sm text-text-muted italic text-center py-4",children:"No entries yet."})]}),i.jsx("div",{className:"mt-4 pt-3 border-t border-border",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted text-sm leading-tight",children:"○"}),i.jsx("input",{ref:_,value:w,onChange:H=>C(H.target.value),onKeyDown:W,placeholder:"New entry...",className:"flex-1 bg-bg-tertiary text-text-primary text-sm px-2 py-1 rounded border border-border focus:outline-none focus:border-accent-primary placeholder-text-muted"}),i.jsxs("button",{onClick:P,className:"flex items-center gap-1 text-sm text-accent-primary hover:text-accent-primary/70 transition-colors cursor-pointer",title:"Add entry",children:[i.jsx(Es,{className:"w-4 h-4"}),"Add"]})]})})]})}const Ot=Mn((e,t)=>({defaults:[],userItems:[],projectItems:[],activeWorkflowId:"default",loading:!1,templateVariables:[],fetchTemplateVariables:async()=>{try{const r=await(await Se("/api/workflows/template-variables")).json();e({templateVariables:r.variables??[]})}catch{}},fetchWorkflows:async()=>{e({loading:!0});try{const r=await(await Se("/api/workflows")).json();e({defaults:r.defaults??[],userItems:r.userItems??[],projectItems:r.projectItems??[],activeWorkflowId:r.activeWorkflowId??"default",loading:!1})}catch{e({loading:!1})}},fetchWorkflow:async n=>{try{const r=await Se(`/api/workflows/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await Se(`/api/workflows/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createWorkflow:async(n,r)=>{const a=await ui("POST","/api/workflows",{...n,destination:r});return a.success&&await t().fetchWorkflows(),a},updateWorkflow:async(n,r)=>{const a=await ui("PUT",`/api/workflows/${n}`,r);return a.success&&await t().fetchWorkflows(),a},deleteWorkflow:async n=>{try{const r=await Se(`/api/workflows/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateWorkflow:async(n,r)=>vd(`/api/workflows/${n}/duplicate`,()=>t().fetchWorkflows(),r)})),VB={pending:"completed",completed:"passed",passed:"failed",failed:"pending"};async function GB(e,t){await Se(`/api/sessions/${e}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:t})})}function Lu({id:e,agents:t}){const n=Hl(t,e),r=t.find(a=>a.id===e);return i.jsx("span",{className:"font-medium rounded px-1",style:{backgroundColor:`${n}20`,color:n},children:(r==null?void 0:r.name)??e})}function WB({id:e}){const t=Ot(u=>u.defaults),n=Ot(u=>u.userItems),a=N.useMemo(()=>[...t,...n],[t,n]).find(u=>u.id===e),l=(a==null?void 0:a.color)??"#3b82f6";return i.jsx("span",{className:"font-medium rounded px-1",style:{backgroundColor:`${l}20`,color:l},children:(a==null?void 0:a.name)??e})}function Hk({entries:e,sessionId:t}){const[n,r]=N.useState(e),[a,l]=N.useState(!1),[u,c]=N.useState(null),[d,h]=N.useState(""),[p,m]=N.useState(""),[x,y]=N.useState(!1),[w,C]=N.useState(!1),_=mt(X=>X.defaults),S=mt(X=>X.userItems),v=mt(X=>X.projectItems),b=N.useMemo(()=>[..._,...S,...v],[_,S,v]),E=N.useRef(null),j=N.useRef(null);N.useEffect(()=>{r(e)},[e]),N.useEffect(()=>{var X;a&&((X=E.current)==null||X.focus())},[a]),N.useEffect(()=>{var X;u&&((X=j.current)==null||X.focus())},[u]);const T=N.useCallback(X=>{r(X),GB(t,X)},[t]),D=N.useCallback(X=>{var z;const $=X.map(ee=>ee.trim()).filter(Boolean);if($.length===0)return;const O=n.map(ee=>Number(ee.id)).filter(ee=>Number.isInteger(ee)&&ee>=0),M=Math.max(-1,...O)+1,q=$.map((ee,Q)=>({id:String(M+Q),description:ee,status:"pending"}));T([...n,...q]),h(""),(z=E.current)==null||z.focus()},[n,T]),L=N.useCallback(()=>{D([d])},[D,d]),I=N.useCallback(X=>{const $=X.clipboardData.getData("text/plain").split(/\r\n|\r|\n/);$.length<2||(X.preventDefault(),D($))},[D]),P=N.useCallback(()=>{l(!1),h("")},[]),W=N.useCallback((X,$)=>{c(X),m($)},[]),H=N.useCallback(()=>{if(!u)return;const X=p.trim(),$=n.map(O=>O.id===u?{...O,description:X||O.description}:O);T($),c(null)},[u,p,n,T]),R=N.useCallback(X=>{const $=n.map(O=>O.id===X?{...O,status:VB[O.status]??"pending"}:O);T($)},[n,T]),U=N.useCallback(X=>{T(n.filter($=>$.id!==X))},[n,T]),V=N.useCallback(()=>{T([]),y(!1)},[T]),G=N.useCallback(X=>{X.key==="Enter"&&(X.preventDefault(),L()),X.key==="Escape"&&P()},[L,P]),Z=N.useCallback(X=>{X.key==="Enter"&&H(),X.key==="Escape"&&c(null)},[H]);return i.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[i.jsxs("div",{className:"bg-primary",children:[n.length===0&&!a&&i.jsxs("div",{className:"px-1.5 py-2 text-xs text-text-muted italic text-center",children:["No criteria yet."," ",i.jsx("button",{onClick:()=>C(!0),className:"text-accent-primary hover:underline not-italic cursor-pointer",children:"Learn more"})]}),n.map((X,$)=>{const O=X.status,M=u===X.id;return i.jsxs("div",{className:`flex items-start gap-1 px-1.5 py-1 group ${$>0?"border-t border-border":""}`,children:[i.jsx("button",{onClick:()=>R(X.id),className:"text-xs leading-tight flex-shrink-0 cursor-pointer hover:opacity-70 transition-opacity",title:`Status: ${X.status} (click to cycle)`,children:i.jsx(po,{status:O})}),i.jsx("div",{className:"flex-1 min-w-0",children:M?i.jsx("input",{ref:j,value:p,onChange:q=>m(q.target.value),onBlur:H,onKeyDown:Z,className:"w-full bg-bg-tertiary text-text-primary text-xs px-1.5 py-0.5 rounded border border-border focus:outline-none focus:border-accent-primary"}):i.jsxs("button",{onClick:()=>W(X.id,X.description),className:"text-xs text-text-primary text-left hover:text-accent-primary transition-colors w-full truncate cursor-pointer",title:"Click to edit",children:["[",X.id,"] ",qg(X.description)]})}),i.jsx("button",{onClick:()=>U(X.id),className:"flex-shrink-0 opacity-0 group-hover:opacity-100 text-text-muted hover:text-accent-error transition-all ml-0.5 cursor-pointer flex items-center self-center",title:"Delete criterion",children:i.jsx(js,{className:"w-4 h-4"})})]},X.id)})]}),a&&i.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-text-muted text-xs leading-tight flex-shrink-0",children:"○"}),i.jsx("input",{ref:E,value:d,onChange:X=>h(X.target.value),onKeyDown:G,onPaste:I,placeholder:"New criterion...",className:"flex-1 bg-bg-tertiary text-text-primary text-xs px-1.5 py-0.5 rounded border border-border focus:outline-none focus:border-accent-primary placeholder-text-muted"})]})}),i.jsxs("div",{className:"px-1.5 py-1 border-t border-border bg-secondary flex items-center gap-2",children:[a?i.jsxs(i.Fragment,{children:[i.jsxs("button",{onClick:L,className:"flex items-center gap-1 text-xs text-accent-primary hover:text-accent-primary/70 transition-colors cursor-pointer",title:"Add criterion",children:[i.jsx(Es,{className:"w-3 h-3"}),"Add"]}),i.jsx("button",{onClick:P,className:"flex items-center gap-1 text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",title:"Cancel",children:"Cancel"})]}):i.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-primary transition-colors cursor-pointer",title:"Add criterion",children:[i.jsx(Es,{className:"w-3 h-3"}),"Add"]}),n.length>0&&i.jsxs("button",{onClick:()=>y(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-error transition-colors ml-auto cursor-pointer",title:"Clear all criteria",children:[i.jsx(lo,{className:"w-3 h-3"}),"Clear all"]}),i.jsx("button",{onClick:()=>C(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-primary transition-colors cursor-pointer",title:"About criteria",children:i.jsx(tg,{className:"w-3 h-3"})})]}),x&&i.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:i.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[i.jsx("span",{className:"text-xs text-accent-error",children:"Clear all criteria?"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:V,className:"text-xs text-accent-error hover:text-accent-error/70 transition-colors cursor-pointer",children:"Yes"}),i.jsx("button",{onClick:()=>y(!1),className:"text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:"No"})]})]})}),i.jsx(wt,{isOpen:w,onClose:()=>C(!1),title:"About Acceptance Criteria",size:"md",children:i.jsxs("div",{className:"space-y-3 text-sm text-text-secondary",children:[i.jsx("p",{children:"Each criterion defines a specific requirement that needs to be met."}),i.jsxs("p",{children:["To use this feature, start in ",i.jsx(Lu,{id:"planner",agents:b})," mode and",i.jsxs("strong",{className:"text-text-primary",children:[" ","ask the agent to define acceptance criteria that matches your goal"]}),". Then launch the ",i.jsx(WB,{id:"default"})," builtin workflow to launch the automation part."]}),i.jsx("p",{children:"This workflow will automatically:"}),i.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[i.jsxs("li",{children:["Launch the ",i.jsx(Lu,{id:"builder",agents:b}),' agent, that will be forced to continue until it marks all criteria as "completed"']}),i.jsxs("li",{children:["Then launch the ",i.jsx(Lu,{id:"verifier",agents:b})," subagent, that will verify each criterion. If every criterion is fulfilled, then it goes to the next step, otherwise, it gives feedback to the main agent until 100% of the criteria are met."]}),i.jsxs("li",{children:["Launch a ",i.jsx(Lu,{id:"code_reviewer",agents:b})," subagent, that will analyze the code to provide actionable feedback to the main agent."]})]}),i.jsx("div",{className:"bg-bg-tertiary rounded p-3 space-y-1.5",children:i.jsx("p",{children:"This lets smaller models follow complex plans to completion and improves the chances that nothing from your plan is missed."})})]})})]})}function Uk({isOpen:e,onClose:t}){const n=Qn(C=>C.config),r=Qn(C=>C.saveConfig),[a,l]=N.useState(""),[u,c]=N.useState(""),[d,h]=N.useState(!1),[p,m]=N.useState(!1),[x,y]=N.useState(!1);N.useEffect(()=>{e&&(l((n==null?void 0:n.command)??""),c((n==null?void 0:n.url)??""),h((n==null?void 0:n.hotReload)??!1),m((n==null?void 0:n.disableInspect)??!1))},[e,n]);const w=async()=>{!a.trim()||!u.trim()||(y(!0),await r({command:a.trim(),url:u.trim(),hotReload:d,disableInspect:p}),y(!1),t())};return i.jsx(wt,{isOpen:e,onClose:t,title:"Dev Server Config",size:"sm",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Command"}),i.jsx("input",{className:"input w-full",type:"text",value:a,onChange:C=>l(C.target.value),placeholder:"npm run dev"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Dev URL"}),i.jsx("input",{className:"input w-full",type:"text",value:u,onChange:C=>c(C.target.value),placeholder:"http://localhost:3000"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"hotReload",checked:d,onChange:C=>h(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),i.jsx("label",{htmlFor:"hotReload",className:"text-xs text-text-secondary",children:"Hot Reload"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"disableInspect",checked:p,onChange:C=>m(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),i.jsx("label",{htmlFor:"disableInspect",className:"text-xs text-text-secondary",children:"Disable inspect feedback"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx("button",{className:"btn btn-secondary",onClick:t,children:"Cancel"}),i.jsx("button",{className:"btn btn-primary",onClick:w,disabled:x||!a.trim()||!u.trim(),children:x?"Saving...":"Save"})]})]})})}const AS={30:"text-black",31:"text-red-400",32:"text-accent-success",33:"text-accent-warning",34:"text-blue-400",35:"text-purple-400",36:"text-cyan-400",37:"text-gray-300",90:"text-gray-500",91:"text-red-500",92:"text-green-500",93:"text-yellow-400",94:"text-blue-500",95:"text-pink-400",96:"text-cyan-500",97:"text-white"},qB={40:"bg-black",41:"bg-red-900",42:"bg-green-900",43:"bg-yellow-900",44:"bg-blue-900",45:"bg-purple-900",46:"bg-cyan-900",47:"bg-gray-700"},LS={1:"font-bold",2:"opacity-75",4:"underline",7:"bg-bg-secondary"},KB="text-text-primary";function YB(e){const t=[],n=new RegExp("\x1B\\[([0-9;]+)m","g");let r=0,a="text-text-primary",l;try{for(;(l=n.exec(e))!==null;){if(l.index>r){const h=e.slice(r,l.index);h&&t.push({text:h,className:a})}const u=l[1];if(!u)continue;const c=u.split(";").map(Number);if(c.length===0||c[0]===0){a="text-text-primary";continue}const d=[];for(const h of c)if(h>=30&&h<=37){const p=AS[h];p&&d.push(p)}else if(h>=40&&h<=47){const p=qB[h];p&&d.push(p)}else if(h>=90&&h<=97){const p=AS[h];p&&d.push(p)}else if(h in LS){const p=LS[h];p&&d.push(p)}else h===39?d.push(KB):h===49&&(a=a.split(" ").filter(p=>!p.startsWith("bg-")).join(" "));d.length>0&&(a=d.join(" ")),r=n.lastIndex}if(r<e.length){const u=e.slice(r);u&&t.push({text:u,className:a})}return t}catch(u){return console.warn("ANSI parsing failed, stripping codes:",u),[{text:XB(e),className:"text-text-primary"}]}}function XB(e){return e.replace(new RegExp("\x1B\\[([0-9;]+)m","g"),"")}function md(e){const t=YB(e),n=[];return t.forEach((r,a)=>{const l=r.text.split(`
284
- `);l.forEach((u,c)=>{n.push(si.createElement("span",{key:`${a}-${c}`,className:r.className,style:{display:"inline-block",whiteSpace:"pre-wrap"}},u)),c<l.length-1&&n.push(si.createElement("br",{key:`${a}-${c}-br`}))})}),n.length===1?n[0]:n}function Fk({logs:e,preRef:t,preClassName:n="text-sm font-mono"}){return i.jsx("pre",{ref:t,className:n,children:e.length===0?i.jsx("span",{className:"text-text-muted",children:"No output yet"}):e.map((r,a)=>i.jsx("span",{className:r.stream==="stderr"?"text-accent-warning":"",children:md(r.content)},a))})}function Kg({isActive:e,onToggle:t,className:n,style:r}){return i.jsxs("button",{type:"button",onClick:()=>t(!e),className:n,style:r,children:[e?i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):i.jsx(yn,{className:"w-3 h-3"}),e?"live":"scroll to bottom"]})}const Wd=(e,t)=>{const n=N.useRef(!0),r=N.useRef(null),[a,l]=N.useState(!0),u=()=>{const c=e.current;c&&(c.scrollTop=c.scrollHeight)};return N.useEffect(()=>{const c=e.current;if(!c)return;const d=y=>{if(y.deltaY>0){requestAnimationFrame(()=>requestAnimationFrame(()=>{c.scrollHeight-c.scrollTop-c.offsetHeight<100&&(n.current=!0,l(!0))}));return}n.current=!1,l(!1)},h=y=>{y.touches[0]&&(r.current=y.touches[0].clientY)},p=y=>{if(r.current===null)return;const w=y.touches[0];if(!w)return;if(w.clientY-r.current>0){n.current=!1,l(!1);return}requestAnimationFrame(()=>requestAnimationFrame(()=>{c.scrollHeight-c.scrollTop-c.offsetHeight<100&&(n.current=!0,l(!0))}))},m=new MutationObserver(()=>{n.current&&requestAnimationFrame(u)}),x=setInterval(()=>{n.current&&u()},1e3);return c.addEventListener("wheel",d,{passive:!0}),c.addEventListener("touchstart",h,{passive:!0}),c.addEventListener("touchmove",p,{passive:!0}),m.observe(c,{childList:!0,subtree:!0,characterData:!0}),()=>{c.removeEventListener("wheel",d),c.removeEventListener("touchstart",h),c.removeEventListener("touchmove",p),m.disconnect(),clearInterval(x)}},[t==null?void 0:t.id]),{force_scroll_to_bottom:()=>{n.current=!0,l(!0),u()},isAutoScrollActive:a,setAutoScroll:c=>{n.current=c,l(c),c&&u()}}},Yg=N.memo(function({title:t,logs:n,onClose:r,preClassName:a}){const l=N.useRef(null),{isAutoScrollActive:u,setAutoScroll:c}=Wd(l,null);return i.jsx(wt,{isOpen:!0,onClose:r,title:t,size:"full",headerRight:i.jsx(Kg,{isActive:u,onToggle:c,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),children:i.jsx("div",{ref:l,className:"h-full overflow-y-auto scrollbar-stable",children:i.jsx(Fk,{logs:n,preClassName:a})})})}),QB=N.memo(function({logs:t,anchorRef:n,isHiding:r,isAutoScrollActive:a,onSetAutoScroll:l}){const[u,c]=N.useState(null),d=N.useRef(null),h=N.useRef(l);return h.current=l,N.useEffect(()=>{var m;const p=(m=n.current)==null?void 0:m.getBoundingClientRect();p&&c({bottom:window.innerHeight-p.bottom,right:window.innerWidth-p.right,width:p.width,height:p.height})},[n]),N.useEffect(()=>{const p=d.current;if(!p)return;const m=x=>{if(x.deltaY<0){h.current(!1);return}x.deltaY>0&&requestAnimationFrame(()=>requestAnimationFrame(()=>{p.scrollHeight-p.scrollTop-p.offsetHeight<100&&h.current(!0)}))};return p.addEventListener("wheel",m,{passive:!0}),()=>p.removeEventListener("wheel",m)},[]),N.useEffect(()=>{d.current&&a&&(d.current.scrollTop=d.current.scrollHeight)},[t,a,u]),i.jsx("div",{className:`relative ${u?"":"hidden"}`,children:i.jsx("pre",{ref:d,className:"fixed z-40 text-sm font-mono text-text-primary bg-bg-primary p-2 rounded border border-border overflow-auto transition-all duration-150 ease-out select-text",style:u?{bottom:u.bottom,right:u.right,width:u.width*2,maxHeight:u.height*3,transformOrigin:"bottom right",transform:r?"scale(0.01)":"scale(1)",opacity:r?0:1}:void 0,children:t.map((p,m)=>i.jsx("span",{className:p.stream==="stderr"?"text-accent-warning":"",children:md(p.content)},m))})})}),Vk=N.memo(function({workdir:t,compact:n,onExpand:r,onConfigure:a}){const l=Qn(V=>V.setWorkdir),u=Qn(V=>V.status),c=Qn(V=>V.config),d=Qn(V=>V.logs),h=Qn(V=>V.start),p=Qn(V=>V.stop),m=Qn(V=>V.fetchLogs),[x,y]=N.useState(!1),[w,C]=N.useState(!1),[_,S]=N.useState(!1),[v,b]=N.useState(!1),E=N.useRef(null),{isAutoScrollActive:j,setAutoScroll:T}=Wd(E,null),D=N.useRef(null),L=N.useRef(null),I=N.useRef(null),P=()=>{const V=u==null?void 0:u.inspectProxyPort;if(!V){u!=null&&u.url&&window.open(u.url,"_blank");return}const G=`${window.location.protocol}//${window.location.hostname}:${V}`;window.open(G,"_blank")},W=(u==null?void 0:u.state)??"off",H=c!==null,R=W==="running"||W==="warning";N.useEffect(()=>{l(t??null)},[t,l]),N.useEffect(()=>{R&&m()},[R,m]);const U=()=>{R?p():h()};return i.jsxs("div",{className:`space-y-3 ${n?"":"mt-2 pt-3 border-t border-border"}`,children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 ${W==="running"?"bg-accent-success":W==="warning"?"bg-accent-warning":W==="error"?"bg-accent-error":"bg-text-muted"}`}),i.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Dev Server"})]}),i.jsx("button",{onClick:()=>{a?a():y(!0)},className:"p-1.5 rounded hover:bg-bg-tertiary transition-colors text-text-muted",title:"Configure dev server",children:i.jsx(iT,{})})]}),H?i.jsx(i.Fragment,{children:W==="running"||W==="warning"?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:U,className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:[i.jsx(ng,{}),"Stop"]}),(u==null?void 0:u.url)&&i.jsxs("button",{onClick:()=>P(),className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",title:u.url,children:[i.jsx(E1,{}),"Open"]})]}):i.jsx("button",{onClick:U,className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",children:"Start"})}):i.jsx("button",{onClick:()=>{a?a():y(!0)},className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-muted hover:bg-border transition-colors",children:"Configure"}),i.jsxs("div",{ref:I,className:`relative ${H&&R?"":"hidden"}`,onMouseEnter:()=>{!H||!R||n||(L.current&&clearTimeout(L.current),D.current=setTimeout(()=>{S(!0),b(!1)},500))},onMouseLeave:()=>{D.current&&clearTimeout(D.current),b(!0),L.current=setTimeout(()=>S(!1),150)},children:[i.jsx(Fk,{logs:d,preRef:E,preClassName:"text-sm bg-bg-primary p-2 rounded overflow-auto max-h-[200px] border border-border"}),H&&R&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"absolute bottom-1 right-1 z-50 flex items-center gap-1",children:[!n&&(_||v)&&i.jsx(Kg,{isActive:j,onToggle:T,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),i.jsx("button",{onClick:()=>n?r==null?void 0:r():C(!0),className:"px-2 py-0.5 rounded text-xs font-medium bg-accent-primary/30 text-text-primary hover:bg-accent-primary/50 transition-colors",children:"Expand"})]}),!n&&(_||v)&&I.current&&di.createPortal(i.jsx(QB,{logs:d,anchorRef:I,isHiding:v,isAutoScrollActive:j,onSetAutoScroll:T}),document.body)]})]}),!a&&i.jsx(Uk,{isOpen:x,onClose:()=>y(!1)}),w&&i.jsx(Yg,{title:"Dev Server Logs",logs:d,onClose:()=>C(!1)})]})}),JB=N.memo(function({sessionId:t}){var y;const n=wl(w=>w.processes),r=wl(w=>w.stopProcess),[a,l]=N.useState(null),[u,c]=N.useState([]),d=n.filter(w=>w.status!=="exited"),h=d.filter(w=>w.status==="running").length;if(n.length===0)return null;const p=w=>{switch(w){case"running":return"bg-accent-success";case"starting":return"bg-accent-warning";case"stopping":return"bg-accent-warning";case"exited":return"bg-text-muted";default:return"bg-text-muted"}},m=w=>{const C=wl.getState().logs[w]??[];c(C.map(_=>({content:_.content,stream:_.stream}))),l(w)},x=w=>{t&&r(w,t)};return i.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",children:[i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 bg-accent-primary"}),i.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Background"}),i.jsxs("span",{className:"text-xs text-text-muted",children:["(",h," running)"]})]})}),i.jsx("div",{className:"space-y-2",children:d.map(w=>i.jsx("div",{className:"border border-border rounded p-2",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[i.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${p(w.status)}`}),i.jsx("span",{className:"text-sm text-text-primary truncate",title:w.name,children:w.name}),i.jsxs("span",{className:"text-xs text-text-muted",children:["[",w.status,"]"]})]}),i.jsxs("div",{className:"flex gap-1 ml-2",children:[i.jsx("button",{onClick:()=>m(w.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-border text-text-secondary transition-colors",title:"View logs",children:"Logs"}),i.jsx("button",{onClick:()=>x(w.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-accent-error/20 text-text-secondary hover:text-accent-error transition-colors",title:"Stop process",children:"Stop"})]})]})},w.id))}),a&&i.jsx(Yg,{title:((y=d.find(w=>w.id===a))==null?void 0:y.name)??"",logs:u,onClose:()=>{l(null),c([])}})]})});function Gk(){return Qt.getState().platform??null}function Wk(e){const t=e.replace(/\\/g,"/");return encodeURI(t).replace(/#/g,"%23").replace(/\?/g,"%3F")}function qk(e,t,n){const r=Gk(),a=e.startsWith("/")||e.match(/^[a-zA-Z]:[/\\]/)?e:n?`${n.replace(/\\/g,"/").replace(/\/$/,"")}/${e}`:e,l=Wk(a);if(r!=null&&r.isWSL&&r.wslDistro)return`${`vscode://vscode-remote/wsl+${r.wslDistro}${l}`}:${t??1}`;const u=`vscode://file/${l}`;return t?`${u}:${t}`:u}function ZB(e){const t=Gk(),n=Wk(e.replace(/\\/g,"/"));return t!=null&&t.isWSL&&t.wslDistro?`vscode://vscode-remote/wsl+${t.wslDistro}${n}`:`vscode://file/${n}`}function e8({file:e,showEditorLink:t,workdir:n}){const r=B1(e.path,28),a=e.status==="added"?"text-accent-success":e.status==="deleted"?"text-accent-error":"text-accent-primary",l=e.status==="added"?`+${e.additions}`:e.status==="deleted"?`-${e.deletions}`:e.additions>0||e.deletions>0?`+${e.additions}, -${e.deletions}`:"",u=t&&n?qk(e.path,void 0,n):void 0,c=i.jsxs(i.Fragment,{children:[i.jsx("span",{className:`truncate ${a}`,title:e.path,children:r}),l&&i.jsx("span",{className:`shrink-0 font-mono${e.status==="added"?" text-accent-success":e.status==="deleted"?" text-accent-error":" text-text-muted"}`,children:l})]});return u?i.jsx("a",{href:u,className:"flex items-center justify-between gap-1 py-0.5 text-xs min-w-0 hover:bg-bg-tertiary rounded px-1 transition-colors no-underline",title:`Open ${e.path} in VSCode`,children:c}):i.jsx("div",{className:"flex items-center justify-between gap-1 py-0.5 text-xs min-w-0",children:c})}function t8(){const{diff:e}=Wg(),t=Ht(a=>a.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",n=Re(a=>a.currentSession),r=(n==null?void 0:n.workspace)??(n==null?void 0:n.workdir);return e.loading?i.jsx("div",{className:"mt-3",children:i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-muted",children:[i.jsx("span",{className:"w-3 h-3 border border-border border-t-accent-primary rounded-full animate-spin"}),i.jsx("span",{children:"Checking changes..."})]})}):e.files.length===0?i.jsx("div",{className:"mt-3",children:i.jsx("p",{className:"text-xs text-text-muted text-center",children:"No changes"})}):i.jsx("div",{className:"mt-3 max-h-[150px] overflow-y-auto",children:i.jsx("div",{className:"pr-1",children:e.files.map((a,l)=>i.jsx(e8,{file:a,showEditorLink:t,workdir:r},l))})})}function Kk(e){const[t,n]=N.useState(!1),[r,a]=N.useState(null),[l,u]=N.useState(!1),[c,d]=N.useState(""),h=N.useCallback(()=>{t||e()},[t,e]),p=c.trim().length>0&&!t,m=N.useCallback(()=>{a(null),n(!1),d(""),u(!0)},[]);return{busy:t,setBusy:n,error:r,setError:a,loading:l,setLoading:u,newName:c,setNewName:d,handleClose:h,canCreate:p,resetState:m}}function Yk({isOpen:e,onClose:t,title:n,busy:r,loading:a,children:l}){const u=i.jsx("div",{className:"flex gap-2 justify-end",children:i.jsx("button",{onClick:t,className:"px-4 py-2 text-sm rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary transition-colors",children:"Cancel"})});return i.jsx(wt,{isOpen:e,onClose:t,title:n,size:"md",footer:u,children:a||r?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(hi,{})}):l})}function Xk({icon:e,title:t,placeholder:n,buttonLabel:r,value:a,onChange:l,onCreate:u,canCreate:c,busy:d}){return i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-text-primary mb-2",children:t}),i.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded border border-border bg-bg-primary focus-within:border-accent-primary mb-3",children:[i.jsx("span",{className:"w-4 h-4 shrink-0 text-text-muted flex items-center",children:e}),i.jsx("input",{type:"text",value:a,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&c&&u()},placeholder:n,className:"flex-1 bg-transparent text-sm text-text-primary outline-none font-mono placeholder-text-muted"})]}),i.jsx("button",{onClick:u,disabled:!c||d,className:"w-full px-4 py-2 text-sm rounded bg-accent-primary text-white hover:opacity-90 transition-colors disabled:opacity-50",children:r})]})}function Qk({isOpen:e,onClose:t,projectId:n,sessionId:r,currentWorkspace:a,currentBranch:l}){const u=Re(R=>R.loadSession),{busy:c,setBusy:d,error:h,setError:p,loading:m,setLoading:x,newName:y,setNewName:w,handleClose:C,canCreate:_,resetState:S}=Kk(t),[v,b]=N.useState([]),[E,j]=N.useState(null),[T,D]=N.useState(null),[L,I]=N.useState(!1);N.useEffect(()=>{e&&(S(),j(null),D(null),I(!1),Se(`/api/projects/${n}/workspaces`).then(R=>R.json()).then(R=>{b(R.workspaces),x(!1)}).catch(()=>{b([]),x(!1)}))},[e,n,S,x]);const P=N.useCallback(async R=>{p(null),d(!0);try{const U=await Se(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R})});if(!U.ok){const V=await U.json().catch(()=>({error:"Failed to switch workspace"}));p(V.error),d(!1);return}await u(r),t()}catch(U){p(U instanceof Error?U.message:"Failed to switch workspace"),d(!1)}},[r,u,t,p,d]),W=N.useCallback(async(R,U)=>{p(null),D(null),I((U==null?void 0:U.force)===!0),d(!0);try{const V=await Se(`/api/sessions/${r}/delete-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R,force:(U==null?void 0:U.force)===!0})});if(!V.ok){const X=await V.json().catch(()=>({error:"Failed to delete workspace"}));p(X.error),X.conflictingSessionIds&&D(X.conflictingSessionIds),I(!1),d(!1);return}j(null),I(!1),await u(r);const Z=await(await Se(`/api/projects/${n}/workspaces`)).json();b(Z.workspaces),d(!1),x(!1)}catch(V){p(V instanceof Error?V.message:"Failed to delete workspace"),I(!1),d(!1)}},[r,n,u,p,d]),H=N.useCallback(async()=>{p(null),d(!0);try{const R=await Se(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:y.trim()})});if(!R.ok){const U=await R.json().catch(()=>({error:"Failed to create workspace"}));p(U.error),d(!1);return}await u(r),t()}catch(R){p(R instanceof Error?R.message:"Failed to create workspace"),d(!1)}},[y,r,u,t,p,d]);return i.jsx(Yk,{isOpen:e,onClose:C,title:"Switch Workspace",busy:c,loading:m,children:i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-text-primary mb-2",children:"Workspaces"}),i.jsxs("div",{className:"max-h-48 overflow-y-auto space-y-0.5 bg-bg-tertiary/30 rounded p-2 mb-4",children:[i.jsxs("button",{onClick:()=>P("original"),disabled:c,className:`w-full text-left px-3 py-1.5 text-sm rounded transition-colors flex items-center gap-2 ${a?"hover:bg-bg-tertiary text-text-secondary":"bg-accent-primary/10 text-accent-primary cursor-default"}`,children:[i.jsx(Or,{className:"w-4 h-4 shrink-0"}),i.jsx("span",{className:"font-mono truncate",children:"original"}),i.jsx("span",{className:"text-xs text-text-muted ml-auto",children:l??"unknown"}),!a&&i.jsx("span",{className:"text-[10px] text-accent-primary ml-1",children:"(current)"})]}),v.slice().sort((R,U)=>R.name===a?-1:U.name===a?1:R.name.localeCompare(U.name)).map(R=>i.jsx("div",{className:"group relative",children:E===R.name?i.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-sm rounded bg-accent-error/10",children:[i.jsxs("span",{className:"text-xs text-accent-error",children:["Delete ",R.name,"?"]}),i.jsx("button",{onClick:()=>W(R.name),disabled:c,className:"ml-auto text-xs px-2 py-0.5 rounded bg-accent-error text-white hover:opacity-90",children:"Confirm"}),i.jsx("button",{onClick:()=>j(null),disabled:c,className:"text-xs px-2 py-0.5 rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary",children:"Cancel"})]}):i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>{!c&&R.name!==a&&P(R.name)},disabled:c||R.name===a,className:`w-full text-left px-3 py-1.5 text-sm rounded transition-colors flex items-center gap-2 ${R.name===a?"bg-accent-primary/10 text-accent-primary cursor-default":"hover:bg-bg-tertiary text-text-secondary"} ${c?"opacity-70":""}`,children:[i.jsx(Or,{className:"w-4 h-4 shrink-0"}),i.jsx("span",{className:"font-mono truncate",children:R.name}),i.jsx("span",{className:"text-xs text-text-muted ml-auto",children:R.branch??"unknown"}),R.name===a&&i.jsx("span",{className:"text-[10px] text-accent-primary ml-1",children:"(current)"})]}),R.name!==a&&!c&&i.jsx("button",{onClick:U=>{U.stopPropagation(),p(null),D(null),j(R.name)},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 text-xs text-text-muted hover:text-accent-error transition-opacity px-1 py-0.5 rounded",title:"Delete workspace",children:"✕"})]})},R.path))]}),i.jsx(Xk,{icon:i.jsx(Or,{}),title:"Create new workspace",placeholder:"workspace name",buttonLabel:"Create Workspace",value:y,onChange:w,onCreate:H,canCreate:_,busy:c}),h&&i.jsxs("div",{className:"mt-3 text-sm bg-accent-error/10 p-2 rounded",role:"alert",children:[i.jsx("p",{className:"text-accent-error",children:h}),T&&T.length>0&&i.jsxs("div",{className:"mt-2 space-y-1",children:[i.jsx("p",{className:"text-xs text-text-muted",children:"Conflicting sessions:"}),i.jsx("ul",{className:"space-y-0.5",children:T.map(R=>i.jsx("li",{children:i.jsx(Jn,{href:`/p/${n}/s/${R}`,className:"text-xs font-mono text-accent-primary hover:underline break-all",children:R})},R))}),i.jsx("button",{onClick:()=>W(E??"",{force:!0}),disabled:c||!E,className:"mt-2 text-xs px-2 py-1 rounded bg-accent-warning text-black hover:opacity-90 disabled:opacity-50","aria-label":"Force delete workspace, switching other sessions to original",children:L?"Processing...":"Force Delete (switch other sessions to original)"})]})]})]})})}function Jk({isOpen:e,onClose:t,sessionId:n}){const r=Re(D=>D.loadSession),{busy:a,setBusy:l,error:u,setError:c,loading:d,setLoading:h,newName:p,setNewName:m,handleClose:x,canCreate:y,resetState:w}=Kk(t),[C,_]=N.useState([]),[S,v]=N.useState(""),[b,E]=N.useState("");N.useEffect(()=>{e&&(w(),v(""),_([]),E(""),Se(`/api/sessions/${n}/branches`).then(D=>D.json()).then(D=>{_(D.branches),E(D.defaultBranch??""),h(!1)}).catch(()=>{_([]),h(!1)}))},[e,n,w,h]);const j=N.useCallback(async D=>{c(null),l(!0);try{const L=await Se(`/api/sessions/${n}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:D})});if(!L.ok){const I=await L.json().catch(()=>({error:"Failed to switch branch"}));c(I.error),l(!1);return}await r(n),t()}catch(L){c(L instanceof Error?L.message:"Failed to switch branch"),l(!1)}},[n,r,t,c,l]),T=N.useCallback(async()=>{c(null),l(!0);try{const D={name:p.trim()};S&&(D.sourceBranch=S);const L=await Se(`/api/sessions/${n}/checkout-new`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!L.ok){const I=await L.json().catch(()=>({error:"Failed to create branch"}));c(I.error),l(!1);return}await r(n),t()}catch(D){c(D instanceof Error?D.message:"Failed to create branch"),l(!1)}},[p,S,n,r,t,c,l]);return i.jsx(Yk,{isOpen:e,onClose:x,title:"Switch Branch",busy:a,loading:d,children:i.jsxs("div",{children:[C.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("p",{className:"text-sm font-medium text-text-primary mb-2",children:"Branches"}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5 bg-bg-tertiary/30 rounded p-2",children:C.map(D=>i.jsxs("button",{onClick:()=>{D.current||j(D.name)},disabled:a,className:`w-full text-left px-3 py-1.5 text-sm rounded transition-colors flex items-center gap-2 ${D.current?"bg-accent-primary/10 text-accent-primary cursor-default":"hover:bg-bg-tertiary text-text-secondary"}`,children:[i.jsx(Vi,{className:"w-3.5 h-3.5 shrink-0"}),i.jsx("span",{className:"font-mono truncate",children:D.name}),D.current&&i.jsx("span",{className:"ml-auto text-xs text-text-muted",children:"(current)"}),!D.current&&i.jsx("span",{className:"ml-auto text-xs text-accent-primary",children:"Switch"})]},D.name))})]}),i.jsx(Xk,{icon:i.jsx(Vi,{}),title:"Create new branch",placeholder:"feature/my-branch",buttonLabel:"Create Branch",value:p,onChange:m,onCreate:T,canCreate:y,busy:a}),p.trim()&&i.jsxs("div",{className:"mt-2",children:[i.jsxs("label",{className:"text-xs text-text-muted mb-1 block",children:["From branch (optional — defaults to ",b||"project default",")"]}),i.jsxs("div",{className:"relative",children:[i.jsx(Vi,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-text-muted pointer-events-none"}),i.jsx("input",{type:"text",value:S,onChange:D=>v(D.target.value),placeholder:b||"main",className:"w-full text-sm bg-bg-primary border border-border-default rounded pl-8 pr-2 py-1.5 text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]})]}),u&&i.jsx("p",{className:"mt-3 text-sm text-accent-error bg-accent-error/10 p-2 rounded",children:u})]})})}function Zk({workspaceName:e,branch:t,workdir:n,showEditorLink:r,sessionId:a,projectId:l,onEditWorkspace:u,onEditBranch:c}){const[d,h]=N.useState(!1),[p,m]=N.useState(!1);return t===null?null:i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r&&n?i.jsxs("a",{href:ZB(n),className:"flex items-center gap-2 min-w-0 flex-1 no-underline group",title:"Open workspace in VSCode",children:[i.jsx(Or,{className:"w-4 h-4 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary group-hover:text-accent-primary transition-colors",children:e})]}):i.jsxs(i.Fragment,{children:[i.jsx(Or,{className:"w-4 h-4 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary",children:e})]}),i.jsx("button",{onClick:()=>{u?u():h(!0)},className:"ml-auto px-2 py-0.5 text-xs rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary transition-colors",children:"Edit"})]}),i.jsx("div",{className:"h-px bg-border"}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Vi,{}),i.jsx("span",{className:"truncate text-text-secondary",children:t}),i.jsx("button",{onClick:()=>{c?c():m(!0)},className:"ml-auto px-2 py-0.5 text-xs rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary transition-colors",children:"Edit"})]})]}),i.jsx(t8,{}),!u&&i.jsx(Qk,{isOpen:d,onClose:()=>h(!1),projectId:l,sessionId:a,currentWorkspace:e,currentBranch:t}),!c&&i.jsx(Jk,{isOpen:p,onClose:()=>m(!1),sessionId:a})]})}function n8(e,t){return t||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function r8(e,t){return t||e>85?"bg-accent-error":e>60?"bg-accent-warning":"bg-accent-success"}function Xg({percent:e,dangerZone:t=!1,size:n="md",className:r=""}){const a=n==="sm"?"w-12":"w-20",l=n==="sm"?"h-1":"h-1.5";return i.jsx("div",{className:`${l} bg-bg-tertiary rounded-full overflow-hidden ${a} ${r}`,children:i.jsx("div",{className:`h-full transition-all duration-300 ${r8(e,t)}`,style:{width:`${Math.min(e,100)}%`}})})}function s8({dangerZone:e,size:t="md"}){return e?i.jsx("span",{className:"text-accent-error animate-pulse text-[10px] font-medium",children:"Low!"}):null}function i8({code:e,variant:t}){const n=t==="inline"?"span":t==="block-nowrap"?"div":"pre";return i.jsx(n,{className:"language-",children:i.jsx("code",{className:"language-",children:e})})}const io=N.memo(function({code:t,language:n,variant:r,showLineNumbers:a=!1,startLine:l=1}){const{showSyntaxHighlighting:u}=Xi(),[c,d]=N.useState(null),h=bk(),p=N.useRef(t);if(N.useEffect(()=>{u&&(p.current=t,yk(t,n,h).then(x=>{p.current===t&&d(x)}))},[t,n,h,u]),!u||!c)return i.jsx(i8,{code:t,variant:r});if(r==="inline")return i.jsx("span",{dangerouslySetInnerHTML:{__html:c}});const m=a?"":"shiki-plain";return i.jsx("div",{className:m,style:{"--shiki-start":l},dangerouslySetInnerHTML:{__html:c}})});function e2({src:e,alt:t,isOpen:n,onClose:r}){return n?i.jsx(wt,{isOpen:n,onClose:r,title:"",size:"full",children:i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx("img",{src:e,alt:t,className:"max-w-full max-h-[80vh] object-contain rounded-lg shadow-2xl"})})}):null}const pd=N.memo(function({type:t,children:n}){const r=t==="removed"?"diff-removed-bg diff-removed-border":"diff-added-bg diff-added-border",a=t==="removed"?"line-through decoration-red-400/30":"";return i.jsx("div",{className:`border-l-[3px] ${r}`,children:i.jsx("div",{className:`min-w-0 py-3 ${a}`,children:i.jsx("div",{className:"shiki-compact shiki-transparent-bg",children:n})})})}),a8=N.memo(function({oldString:t,newString:n,filePath:r}){const a=N.useMemo(()=>Vd(r),[r]),l=t.length>0,u=n.length>0;return!l&&!u?i.jsx("div",{className:"text-xs text-text-muted italic p-2",children:"No changes"}):i.jsxs("div",{className:"rounded overflow-hidden border border-border",children:[l&&i.jsx(pd,{type:"removed",children:i.jsx(io,{code:t,language:a,variant:"block",showLineNumbers:!0})}),u&&i.jsx(pd,{type:"added",children:i.jsx(io,{code:n,language:a,variant:"block",showLineNumbers:!0})})]})}),o8=N.memo(function({content:t,filePath:n}){const r=N.useMemo(()=>Vd(n),[n]);return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto",children:i.jsx(pd,{type:"added",children:i.jsx(io,{code:t,language:r,variant:"block",showLineNumbers:!0})})})}),l8=N.memo(function({regions:t,filePath:n}){const r=N.useMemo(()=>Vd(n),[n]);return t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic p-2",children:"No changes"}):i.jsx("div",{className:"space-y-2",children:t.map((a,l)=>i.jsx(u8,{region:a,language:r},l))})});function c8(e){const t=[];function n(r,a,l){const u=t[t.length-1];u&&u.type===r&&u.startLine+u.lines.length===a?u.lines.push(l):t.push({type:r,startLine:a,lines:[l]})}for(const r of e.beforeContext)n("context",r.lineNumber,r.content);for(const r of e.edits){const a=r.oldContent.split(`
284
+ `);l.forEach((u,c)=>{n.push(si.createElement("span",{key:`${a}-${c}`,className:r.className,style:{display:"inline-block",whiteSpace:"pre-wrap"}},u)),c<l.length-1&&n.push(si.createElement("br",{key:`${a}-${c}-br`}))})}),n.length===1?n[0]:n}function Fk({logs:e,preRef:t,preClassName:n="text-sm font-mono"}){return i.jsx("pre",{ref:t,className:n,children:e.length===0?i.jsx("span",{className:"text-text-muted",children:"No output yet"}):e.map((r,a)=>i.jsx("span",{className:r.stream==="stderr"?"text-accent-warning":"",children:md(r.content)},a))})}function Kg({isActive:e,onToggle:t,className:n,style:r}){return i.jsxs("button",{type:"button",onClick:()=>t(!e),className:n,style:r,children:[e?i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):i.jsx(yn,{className:"w-3 h-3"}),e?"live":"scroll to bottom"]})}const Wd=(e,t)=>{const n=N.useRef(!0),r=N.useRef(null),[a,l]=N.useState(!0),u=()=>{const c=e.current;c&&(c.scrollTop=c.scrollHeight)};return N.useEffect(()=>{const c=e.current;if(!c)return;const d=y=>{if(y.deltaY>0){requestAnimationFrame(()=>requestAnimationFrame(()=>{c.scrollHeight-c.scrollTop-c.offsetHeight<100&&(n.current=!0,l(!0))}));return}n.current=!1,l(!1)},h=y=>{y.touches[0]&&(r.current=y.touches[0].clientY)},p=y=>{if(r.current===null)return;const w=y.touches[0];if(!w)return;if(w.clientY-r.current>0){n.current=!1,l(!1);return}requestAnimationFrame(()=>requestAnimationFrame(()=>{c.scrollHeight-c.scrollTop-c.offsetHeight<100&&(n.current=!0,l(!0))}))},m=new MutationObserver(()=>{n.current&&requestAnimationFrame(u)}),x=setInterval(()=>{n.current&&u()},1e3);return c.addEventListener("wheel",d,{passive:!0}),c.addEventListener("touchstart",h,{passive:!0}),c.addEventListener("touchmove",p,{passive:!0}),m.observe(c,{childList:!0,subtree:!0,characterData:!0}),()=>{c.removeEventListener("wheel",d),c.removeEventListener("touchstart",h),c.removeEventListener("touchmove",p),m.disconnect(),clearInterval(x)}},[t==null?void 0:t.id]),{force_scroll_to_bottom:()=>{n.current=!0,l(!0),u()},isAutoScrollActive:a,setAutoScroll:c=>{n.current=c,l(c),c&&u()}}},Yg=N.memo(function({title:t,logs:n,onClose:r,preClassName:a}){const l=N.useRef(null),{isAutoScrollActive:u,setAutoScroll:c}=Wd(l,null);return i.jsx(wt,{isOpen:!0,onClose:r,title:t,size:"full",headerRight:i.jsx(Kg,{isActive:u,onToggle:c,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),children:i.jsx("div",{ref:l,className:"h-full overflow-y-auto scrollbar-stable",children:i.jsx(Fk,{logs:n,preClassName:a})})})}),QB=N.memo(function({logs:t,anchorRef:n,isHiding:r,isAutoScrollActive:a,onSetAutoScroll:l}){const[u,c]=N.useState(null),d=N.useRef(null),h=N.useRef(l);return h.current=l,N.useEffect(()=>{var m;const p=(m=n.current)==null?void 0:m.getBoundingClientRect();p&&c({bottom:window.innerHeight-p.bottom,right:window.innerWidth-p.right,width:p.width,height:p.height})},[n]),N.useEffect(()=>{const p=d.current;if(!p)return;const m=x=>{if(x.deltaY<0){h.current(!1);return}x.deltaY>0&&requestAnimationFrame(()=>requestAnimationFrame(()=>{p.scrollHeight-p.scrollTop-p.offsetHeight<100&&h.current(!0)}))};return p.addEventListener("wheel",m,{passive:!0}),()=>p.removeEventListener("wheel",m)},[]),N.useEffect(()=>{d.current&&a&&(d.current.scrollTop=d.current.scrollHeight)},[t,a,u]),i.jsx("div",{className:`relative ${u?"":"hidden"}`,children:i.jsx("pre",{ref:d,className:"fixed z-40 text-sm font-mono text-text-primary bg-bg-primary p-2 rounded border border-border overflow-auto transition-all duration-150 ease-out select-text",style:u?{bottom:u.bottom,right:u.right,width:u.width*2,maxHeight:u.height*3,transformOrigin:"bottom right",transform:r?"scale(0.01)":"scale(1)",opacity:r?0:1}:void 0,children:t.map((p,m)=>i.jsx("span",{className:p.stream==="stderr"?"text-accent-warning":"",children:md(p.content)},m))})})}),Vk=N.memo(function({workdir:t,compact:n,onExpand:r,onConfigure:a}){const l=Qn(V=>V.setWorkdir),u=Qn(V=>V.status),c=Qn(V=>V.config),d=Qn(V=>V.logs),h=Qn(V=>V.start),p=Qn(V=>V.stop),m=Qn(V=>V.fetchLogs),[x,y]=N.useState(!1),[w,C]=N.useState(!1),[_,S]=N.useState(!1),[v,b]=N.useState(!1),E=N.useRef(null),{isAutoScrollActive:j,setAutoScroll:T}=Wd(E,null),D=N.useRef(null),L=N.useRef(null),I=N.useRef(null),P=()=>{const V=u==null?void 0:u.inspectProxyPort;if(!V){u!=null&&u.url&&window.open(u.url,"_blank");return}const G=`${window.location.protocol}//${window.location.hostname}:${V}`;window.open(G,"_blank")},W=(u==null?void 0:u.state)??"off",H=c!==null,R=W==="running"||W==="warning";N.useEffect(()=>{l(t??null)},[t,l]),N.useEffect(()=>{R&&m()},[R,m]);const U=()=>{R?p():h()};return i.jsxs("div",{className:`space-y-3 ${n?"":"mt-2 pt-3 border-t border-border"}`,children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 ${W==="running"?"bg-accent-success":W==="warning"?"bg-accent-warning":W==="error"?"bg-accent-error":"bg-text-muted"}`}),i.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Dev Server"})]}),i.jsx("button",{onClick:()=>{a?a():y(!0)},className:"p-1.5 rounded hover:bg-bg-tertiary transition-colors text-text-muted",title:"Configure dev server",children:i.jsx(iT,{})})]}),H?i.jsx(i.Fragment,{children:W==="running"||W==="warning"?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:U,className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:[i.jsx(ng,{}),"Stop"]}),(u==null?void 0:u.url)&&i.jsxs("button",{onClick:()=>P(),className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",title:u.url,children:[i.jsx(E1,{}),"Open"]})]}):i.jsx("button",{onClick:U,className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",children:"Start"})}):i.jsx("button",{onClick:()=>{a?a():y(!0)},className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-muted hover:bg-border transition-colors",children:"Configure"}),i.jsxs("div",{ref:I,className:`relative ${H&&R?"":"hidden"}`,onMouseEnter:()=>{!H||!R||n||(L.current&&clearTimeout(L.current),D.current=setTimeout(()=>{S(!0),b(!1)},500))},onMouseLeave:()=>{D.current&&clearTimeout(D.current),b(!0),L.current=setTimeout(()=>S(!1),150)},children:[i.jsx(Fk,{logs:d,preRef:E,preClassName:"text-sm bg-bg-primary p-2 rounded overflow-auto max-h-[200px] border border-border"}),H&&R&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"absolute bottom-1 right-1 z-50 flex items-center gap-1",children:[!n&&(_||v)&&i.jsx(Kg,{isActive:j,onToggle:T,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),i.jsx("button",{onClick:()=>n?r==null?void 0:r():C(!0),className:"px-2 py-0.5 rounded text-xs font-medium bg-accent-primary/30 text-text-primary hover:bg-accent-primary/50 transition-colors",children:"Expand"})]}),!n&&(_||v)&&I.current&&di.createPortal(i.jsx(QB,{logs:d,anchorRef:I,isHiding:v,isAutoScrollActive:j,onSetAutoScroll:T}),document.body)]})]}),!a&&i.jsx(Uk,{isOpen:x,onClose:()=>y(!1)}),w&&i.jsx(Yg,{title:"Dev Server Logs",logs:d,onClose:()=>C(!1)})]})}),JB=N.memo(function({sessionId:t}){var y;const n=wl(w=>w.processes),r=wl(w=>w.stopProcess),[a,l]=N.useState(null),[u,c]=N.useState([]),d=n.filter(w=>w.status!=="exited"),h=d.filter(w=>w.status==="running").length;if(n.length===0)return null;const p=w=>{switch(w){case"running":return"bg-accent-success";case"starting":return"bg-accent-warning";case"stopping":return"bg-accent-warning";case"exited":return"bg-text-muted";default:return"bg-text-muted"}},m=w=>{const C=wl.getState().logs[w]??[];c(C.map(_=>({content:_.content,stream:_.stream}))),l(w)},x=w=>{t&&r(w,t)};return i.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",children:[i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 bg-accent-primary"}),i.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Background"}),i.jsxs("span",{className:"text-xs text-text-muted",children:["(",h," running)"]})]})}),i.jsx("div",{className:"space-y-2",children:d.map(w=>i.jsx("div",{className:"border border-border rounded p-2",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[i.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${p(w.status)}`}),i.jsx("span",{className:"text-sm text-text-primary truncate",title:w.name,children:w.name}),i.jsxs("span",{className:"text-xs text-text-muted",children:["[",w.status,"]"]})]}),i.jsxs("div",{className:"flex gap-1 ml-2",children:[i.jsx("button",{onClick:()=>m(w.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-border text-text-secondary transition-colors",title:"View logs",children:"Logs"}),i.jsx("button",{onClick:()=>x(w.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-accent-error/20 text-text-secondary hover:text-accent-error transition-colors",title:"Stop process",children:"Stop"})]})]})},w.id))}),a&&i.jsx(Yg,{title:((y=d.find(w=>w.id===a))==null?void 0:y.name)??"",logs:u,onClose:()=>{l(null),c([])}})]})});function Gk(){return Kt.getState().platform??null}function Wk(e){const t=e.replace(/\\/g,"/");return encodeURI(t).replace(/#/g,"%23").replace(/\?/g,"%3F")}function qk(e,t,n){const r=Gk(),a=e.startsWith("/")||e.match(/^[a-zA-Z]:[/\\]/)?e:n?`${n.replace(/\\/g,"/").replace(/\/$/,"")}/${e}`:e,l=Wk(a);if(r!=null&&r.isWSL&&r.wslDistro)return`${`vscode://vscode-remote/wsl+${r.wslDistro}${l}`}:${t??1}`;const u=`vscode://file/${l}`;return t?`${u}:${t}`:u}function ZB(e){const t=Gk(),n=Wk(e.replace(/\\/g,"/"));return t!=null&&t.isWSL&&t.wslDistro?`vscode://vscode-remote/wsl+${t.wslDistro}${n}`:`vscode://file/${n}`}function e8({file:e,showEditorLink:t,workdir:n}){const r=B1(e.path,28),a=e.status==="added"?"text-accent-success":e.status==="deleted"?"text-accent-error":"text-accent-primary",l=e.status==="added"?`+${e.additions}`:e.status==="deleted"?`-${e.deletions}`:e.additions>0||e.deletions>0?`+${e.additions}, -${e.deletions}`:"",u=t&&n?qk(e.path,void 0,n):void 0,c=i.jsxs(i.Fragment,{children:[i.jsx("span",{className:`truncate ${a}`,title:e.path,children:r}),l&&i.jsx("span",{className:`shrink-0 font-mono${e.status==="added"?" text-accent-success":e.status==="deleted"?" text-accent-error":" text-text-muted"}`,children:l})]});return u?i.jsx("a",{href:u,className:"flex items-center justify-between gap-1 py-0.5 text-xs min-w-0 hover:bg-bg-tertiary rounded px-1 transition-colors no-underline",title:`Open ${e.path} in VSCode`,children:c}):i.jsx("div",{className:"flex items-center justify-between gap-1 py-0.5 text-xs min-w-0",children:c})}function t8(){const{diff:e}=Wg(),t=Ht(a=>a.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",n=Re(a=>a.currentSession),r=(n==null?void 0:n.workspace)??(n==null?void 0:n.workdir);return e.loading?i.jsx("div",{className:"mt-3",children:i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-muted",children:[i.jsx("span",{className:"w-3 h-3 border border-border border-t-accent-primary rounded-full animate-spin"}),i.jsx("span",{children:"Checking changes..."})]})}):e.files.length===0?i.jsx("div",{className:"mt-3",children:i.jsx("p",{className:"text-xs text-text-muted text-center",children:"No changes"})}):i.jsx("div",{className:"mt-3 max-h-[150px] overflow-y-auto",children:i.jsx("div",{className:"pr-1",children:e.files.map((a,l)=>i.jsx(e8,{file:a,showEditorLink:t,workdir:r},l))})})}function Kk(e){const[t,n]=N.useState(!1),[r,a]=N.useState(null),[l,u]=N.useState(!1),[c,d]=N.useState(""),h=N.useCallback(()=>{t||e()},[t,e]),p=c.trim().length>0&&!t,m=N.useCallback(()=>{a(null),n(!1),d(""),u(!0)},[]);return{busy:t,setBusy:n,error:r,setError:a,loading:l,setLoading:u,newName:c,setNewName:d,handleClose:h,canCreate:p,resetState:m}}function Yk({isOpen:e,onClose:t,title:n,busy:r,loading:a,children:l}){const u=i.jsx("div",{className:"flex gap-2 justify-end",children:i.jsx("button",{onClick:t,className:"px-4 py-2 text-sm rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary transition-colors",children:"Cancel"})});return i.jsx(wt,{isOpen:e,onClose:t,title:n,size:"md",footer:u,children:a||r?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(hi,{})}):l})}function Xk({icon:e,title:t,placeholder:n,buttonLabel:r,value:a,onChange:l,onCreate:u,canCreate:c,busy:d}){return i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-text-primary mb-2",children:t}),i.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded border border-border bg-bg-primary focus-within:border-accent-primary mb-3",children:[i.jsx("span",{className:"w-4 h-4 shrink-0 text-text-muted flex items-center",children:e}),i.jsx("input",{type:"text",value:a,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&c&&u()},placeholder:n,className:"flex-1 bg-transparent text-sm text-text-primary outline-none font-mono placeholder-text-muted"})]}),i.jsx("button",{onClick:u,disabled:!c||d,className:"w-full px-4 py-2 text-sm rounded bg-accent-primary text-white hover:opacity-90 transition-colors disabled:opacity-50",children:r})]})}function Qk({isOpen:e,onClose:t,projectId:n,sessionId:r,currentWorkspace:a,currentBranch:l}){const u=Re(R=>R.loadSession),{busy:c,setBusy:d,error:h,setError:p,loading:m,setLoading:x,newName:y,setNewName:w,handleClose:C,canCreate:_,resetState:S}=Kk(t),[v,b]=N.useState([]),[E,j]=N.useState(null),[T,D]=N.useState(null),[L,I]=N.useState(!1);N.useEffect(()=>{e&&(S(),j(null),D(null),I(!1),Se(`/api/projects/${n}/workspaces`).then(R=>R.json()).then(R=>{b(R.workspaces),x(!1)}).catch(()=>{b([]),x(!1)}))},[e,n,S,x]);const P=N.useCallback(async R=>{p(null),d(!0);try{const U=await Se(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R})});if(!U.ok){const V=await U.json().catch(()=>({error:"Failed to switch workspace"}));p(V.error),d(!1);return}await u(r),t()}catch(U){p(U instanceof Error?U.message:"Failed to switch workspace"),d(!1)}},[r,u,t,p,d]),W=N.useCallback(async(R,U)=>{p(null),D(null),I((U==null?void 0:U.force)===!0),d(!0);try{const V=await Se(`/api/sessions/${r}/delete-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R,force:(U==null?void 0:U.force)===!0})});if(!V.ok){const X=await V.json().catch(()=>({error:"Failed to delete workspace"}));p(X.error),X.conflictingSessionIds&&D(X.conflictingSessionIds),I(!1),d(!1);return}j(null),I(!1),await u(r);const Z=await(await Se(`/api/projects/${n}/workspaces`)).json();b(Z.workspaces),d(!1),x(!1)}catch(V){p(V instanceof Error?V.message:"Failed to delete workspace"),I(!1),d(!1)}},[r,n,u,p,d]),H=N.useCallback(async()=>{p(null),d(!0);try{const R=await Se(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:y.trim()})});if(!R.ok){const U=await R.json().catch(()=>({error:"Failed to create workspace"}));p(U.error),d(!1);return}await u(r),t()}catch(R){p(R instanceof Error?R.message:"Failed to create workspace"),d(!1)}},[y,r,u,t,p,d]);return i.jsx(Yk,{isOpen:e,onClose:C,title:"Switch Workspace",busy:c,loading:m,children:i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-text-primary mb-2",children:"Workspaces"}),i.jsxs("div",{className:"max-h-48 overflow-y-auto space-y-0.5 bg-bg-tertiary/30 rounded p-2 mb-4",children:[i.jsxs("button",{onClick:()=>P("original"),disabled:c,className:`w-full text-left px-3 py-1.5 text-sm rounded transition-colors flex items-center gap-2 ${a?"hover:bg-bg-tertiary text-text-secondary":"bg-accent-primary/10 text-accent-primary cursor-default"}`,children:[i.jsx(Or,{className:"w-4 h-4 shrink-0"}),i.jsx("span",{className:"font-mono truncate",children:"original"}),i.jsx("span",{className:"text-xs text-text-muted ml-auto",children:l??"unknown"}),!a&&i.jsx("span",{className:"text-[10px] text-accent-primary ml-1",children:"(current)"})]}),v.slice().sort((R,U)=>R.name===a?-1:U.name===a?1:R.name.localeCompare(U.name)).map(R=>i.jsx("div",{className:"group relative",children:E===R.name?i.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-sm rounded bg-accent-error/10",children:[i.jsxs("span",{className:"text-xs text-accent-error",children:["Delete ",R.name,"?"]}),i.jsx("button",{onClick:()=>W(R.name),disabled:c,className:"ml-auto text-xs px-2 py-0.5 rounded bg-accent-error text-white hover:opacity-90",children:"Confirm"}),i.jsx("button",{onClick:()=>j(null),disabled:c,className:"text-xs px-2 py-0.5 rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary",children:"Cancel"})]}):i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>{!c&&R.name!==a&&P(R.name)},disabled:c||R.name===a,className:`w-full text-left px-3 py-1.5 text-sm rounded transition-colors flex items-center gap-2 ${R.name===a?"bg-accent-primary/10 text-accent-primary cursor-default":"hover:bg-bg-tertiary text-text-secondary"} ${c?"opacity-70":""}`,children:[i.jsx(Or,{className:"w-4 h-4 shrink-0"}),i.jsx("span",{className:"font-mono truncate",children:R.name}),i.jsx("span",{className:"text-xs text-text-muted ml-auto",children:R.branch??"unknown"}),R.name===a&&i.jsx("span",{className:"text-[10px] text-accent-primary ml-1",children:"(current)"})]}),R.name!==a&&!c&&i.jsx("button",{onClick:U=>{U.stopPropagation(),p(null),D(null),j(R.name)},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 text-xs text-text-muted hover:text-accent-error transition-opacity px-1 py-0.5 rounded",title:"Delete workspace",children:"✕"})]})},R.path))]}),i.jsx(Xk,{icon:i.jsx(Or,{}),title:"Create new workspace",placeholder:"workspace name",buttonLabel:"Create Workspace",value:y,onChange:w,onCreate:H,canCreate:_,busy:c}),h&&i.jsxs("div",{className:"mt-3 text-sm bg-accent-error/10 p-2 rounded",role:"alert",children:[i.jsx("p",{className:"text-accent-error",children:h}),T&&T.length>0&&i.jsxs("div",{className:"mt-2 space-y-1",children:[i.jsx("p",{className:"text-xs text-text-muted",children:"Conflicting sessions:"}),i.jsx("ul",{className:"space-y-0.5",children:T.map(R=>i.jsx("li",{children:i.jsx(Jn,{href:`/p/${n}/s/${R}`,className:"text-xs font-mono text-accent-primary hover:underline break-all",children:R})},R))}),i.jsx("button",{onClick:()=>W(E??"",{force:!0}),disabled:c||!E,className:"mt-2 text-xs px-2 py-1 rounded bg-accent-warning text-black hover:opacity-90 disabled:opacity-50","aria-label":"Force delete workspace, switching other sessions to original",children:L?"Processing...":"Force Delete (switch other sessions to original)"})]})]})]})})}function Jk({isOpen:e,onClose:t,sessionId:n}){const r=Re(D=>D.loadSession),{busy:a,setBusy:l,error:u,setError:c,loading:d,setLoading:h,newName:p,setNewName:m,handleClose:x,canCreate:y,resetState:w}=Kk(t),[C,_]=N.useState([]),[S,v]=N.useState(""),[b,E]=N.useState("");N.useEffect(()=>{e&&(w(),v(""),_([]),E(""),Se(`/api/sessions/${n}/branches`).then(D=>D.json()).then(D=>{_(D.branches),E(D.defaultBranch??""),h(!1)}).catch(()=>{_([]),h(!1)}))},[e,n,w,h]);const j=N.useCallback(async D=>{c(null),l(!0);try{const L=await Se(`/api/sessions/${n}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:D})});if(!L.ok){const I=await L.json().catch(()=>({error:"Failed to switch branch"}));c(I.error),l(!1);return}await r(n),t()}catch(L){c(L instanceof Error?L.message:"Failed to switch branch"),l(!1)}},[n,r,t,c,l]),T=N.useCallback(async()=>{c(null),l(!0);try{const D={name:p.trim()};S&&(D.sourceBranch=S);const L=await Se(`/api/sessions/${n}/checkout-new`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!L.ok){const I=await L.json().catch(()=>({error:"Failed to create branch"}));c(I.error),l(!1);return}await r(n),t()}catch(D){c(D instanceof Error?D.message:"Failed to create branch"),l(!1)}},[p,S,n,r,t,c,l]);return i.jsx(Yk,{isOpen:e,onClose:x,title:"Switch Branch",busy:a,loading:d,children:i.jsxs("div",{children:[C.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("p",{className:"text-sm font-medium text-text-primary mb-2",children:"Branches"}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5 bg-bg-tertiary/30 rounded p-2",children:C.map(D=>i.jsxs("button",{onClick:()=>{D.current||j(D.name)},disabled:a,className:`w-full text-left px-3 py-1.5 text-sm rounded transition-colors flex items-center gap-2 ${D.current?"bg-accent-primary/10 text-accent-primary cursor-default":"hover:bg-bg-tertiary text-text-secondary"}`,children:[i.jsx(Vi,{className:"w-3.5 h-3.5 shrink-0"}),i.jsx("span",{className:"font-mono truncate",children:D.name}),D.current&&i.jsx("span",{className:"ml-auto text-xs text-text-muted",children:"(current)"}),!D.current&&i.jsx("span",{className:"ml-auto text-xs text-accent-primary",children:"Switch"})]},D.name))})]}),i.jsx(Xk,{icon:i.jsx(Vi,{}),title:"Create new branch",placeholder:"feature/my-branch",buttonLabel:"Create Branch",value:p,onChange:m,onCreate:T,canCreate:y,busy:a}),p.trim()&&i.jsxs("div",{className:"mt-2",children:[i.jsxs("label",{className:"text-xs text-text-muted mb-1 block",children:["From branch (optional — defaults to ",b||"project default",")"]}),i.jsxs("div",{className:"relative",children:[i.jsx(Vi,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-text-muted pointer-events-none"}),i.jsx("input",{type:"text",value:S,onChange:D=>v(D.target.value),placeholder:b||"main",className:"w-full text-sm bg-bg-primary border border-border-default rounded pl-8 pr-2 py-1.5 text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]})]}),u&&i.jsx("p",{className:"mt-3 text-sm text-accent-error bg-accent-error/10 p-2 rounded",children:u})]})})}function Zk({workspaceName:e,branch:t,workdir:n,showEditorLink:r,sessionId:a,projectId:l,onEditWorkspace:u,onEditBranch:c}){const[d,h]=N.useState(!1),[p,m]=N.useState(!1);return t===null?null:i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r&&n?i.jsxs("a",{href:ZB(n),className:"flex items-center gap-2 min-w-0 flex-1 no-underline group",title:"Open workspace in VSCode",children:[i.jsx(Or,{className:"w-4 h-4 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary group-hover:text-accent-primary transition-colors",children:e})]}):i.jsxs(i.Fragment,{children:[i.jsx(Or,{className:"w-4 h-4 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary",children:e})]}),i.jsx("button",{onClick:()=>{u?u():h(!0)},className:"ml-auto px-2 py-0.5 text-xs rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary transition-colors",children:"Edit"})]}),i.jsx("div",{className:"h-px bg-border"}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Vi,{}),i.jsx("span",{className:"truncate text-text-secondary",children:t}),i.jsx("button",{onClick:()=>{c?c():m(!0)},className:"ml-auto px-2 py-0.5 text-xs rounded bg-bg-tertiary text-text-secondary hover:bg-bg-secondary transition-colors",children:"Edit"})]})]}),i.jsx(t8,{}),!u&&i.jsx(Qk,{isOpen:d,onClose:()=>h(!1),projectId:l,sessionId:a,currentWorkspace:e,currentBranch:t}),!c&&i.jsx(Jk,{isOpen:p,onClose:()=>m(!1),sessionId:a})]})}function n8(e,t){return t||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function r8(e,t){return t||e>85?"bg-accent-error":e>60?"bg-accent-warning":"bg-accent-success"}function Xg({percent:e,dangerZone:t=!1,size:n="md",className:r=""}){const a=n==="sm"?"w-12":"w-20",l=n==="sm"?"h-1":"h-1.5";return i.jsx("div",{className:`${l} bg-bg-tertiary rounded-full overflow-hidden ${a} ${r}`,children:i.jsx("div",{className:`h-full transition-all duration-300 ${r8(e,t)}`,style:{width:`${Math.min(e,100)}%`}})})}function s8({dangerZone:e,size:t="md"}){return e?i.jsx("span",{className:"text-accent-error animate-pulse text-[10px] font-medium",children:"Low!"}):null}function i8({code:e,variant:t}){const n=t==="inline"?"span":t==="block-nowrap"?"div":"pre";return i.jsx(n,{className:"language-",children:i.jsx("code",{className:"language-",children:e})})}const io=N.memo(function({code:t,language:n,variant:r,showLineNumbers:a=!1,startLine:l=1}){const{showSyntaxHighlighting:u}=Xi(),[c,d]=N.useState(null),h=bk(),p=N.useRef(t);if(N.useEffect(()=>{u&&(p.current=t,yk(t,n,h).then(x=>{p.current===t&&d(x)}))},[t,n,h,u]),!u||!c)return i.jsx(i8,{code:t,variant:r});if(r==="inline")return i.jsx("span",{dangerouslySetInnerHTML:{__html:c}});const m=a?"":"shiki-plain";return i.jsx("div",{className:m,style:{"--shiki-start":l},dangerouslySetInnerHTML:{__html:c}})});function e2({src:e,alt:t,isOpen:n,onClose:r}){return n?i.jsx(wt,{isOpen:n,onClose:r,title:"",size:"full",children:i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx("img",{src:e,alt:t,className:"max-w-full max-h-[80vh] object-contain rounded-lg shadow-2xl"})})}):null}const pd=N.memo(function({type:t,children:n}){const r=t==="removed"?"diff-removed-bg diff-removed-border":"diff-added-bg diff-added-border",a=t==="removed"?"line-through decoration-red-400/30":"";return i.jsx("div",{className:`border-l-[3px] ${r}`,children:i.jsx("div",{className:`min-w-0 py-3 ${a}`,children:i.jsx("div",{className:"shiki-compact shiki-transparent-bg",children:n})})})}),a8=N.memo(function({oldString:t,newString:n,filePath:r}){const a=N.useMemo(()=>Vd(r),[r]),l=t.length>0,u=n.length>0;return!l&&!u?i.jsx("div",{className:"text-xs text-text-muted italic p-2",children:"No changes"}):i.jsxs("div",{className:"rounded overflow-hidden border border-border",children:[l&&i.jsx(pd,{type:"removed",children:i.jsx(io,{code:t,language:a,variant:"block",showLineNumbers:!0})}),u&&i.jsx(pd,{type:"added",children:i.jsx(io,{code:n,language:a,variant:"block",showLineNumbers:!0})})]})}),o8=N.memo(function({content:t,filePath:n}){const r=N.useMemo(()=>Vd(n),[n]);return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto",children:i.jsx(pd,{type:"added",children:i.jsx(io,{code:t,language:r,variant:"block",showLineNumbers:!0})})})}),l8=N.memo(function({regions:t,filePath:n}){const r=N.useMemo(()=>Vd(n),[n]);return t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic p-2",children:"No changes"}):i.jsx("div",{className:"space-y-2",children:t.map((a,l)=>i.jsx(u8,{region:a,language:r},l))})});function c8(e){const t=[];function n(r,a,l){const u=t[t.length-1];u&&u.type===r&&u.startLine+u.lines.length===a?u.lines.push(l):t.push({type:r,startLine:a,lines:[l]})}for(const r of e.beforeContext)n("context",r.lineNumber,r.content);for(const r of e.edits){const a=r.oldContent.split(`
285
285
  `);for(let u=0;u<a.length;u++)n("removed",r.startLine+u,a[u]);const l=r.newContent.split(`
286
286
  `);for(let u=0;u<l.length;u++)n("added",r.startLine+u,l[u])}for(const r of e.afterContext)n("context",r.lineNumber,r.content);return t}const u8=N.memo(function({region:t,language:n}){const r=c8(t);return i.jsx("div",{className:"rounded overflow-hidden border border-border font-mono text-sm",children:r.map((a,l)=>i.jsx(d8,{section:a,language:n},l))})}),d8=N.memo(function({section:t,language:n}){const r=t.lines.join(`
287
287
  `);return t.type==="context"?i.jsx("div",{children:i.jsx("div",{className:"min-w-0 py-3",children:i.jsx("div",{className:"shiki-compact shiki-transparent-bg",children:i.jsx(io,{code:r,language:n,variant:"block",showLineNumbers:!0,startLine:t.startLine})})})}):i.jsx(pd,{type:t.type,children:i.jsx(io,{code:r,language:n,variant:"block",showLineNumbers:!0,startLine:t.startLine})})});function DS(e){return e.split(`
288
288
  `).filter(t=>!t.startsWith(`
289
289
  [`)&&!t.startsWith("[")).map(t=>t.replace(/^\d+\|/,"")).join(`
290
290
  `)}const h8=N.memo(function({result:t,metadata:n,filePath:r}){const[a,l]=N.useState(!1),u=N.useMemo(()=>Vd(r),[r]),c=n==null?void 0:n.mimeType,d=n==null?void 0:n.base64Data;if(c!=null&&c.startsWith("image/")&&d){const w=`data:${c};base64,${d}`;return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] flex items-center justify-center cursor-pointer hover:border-accent-primary transition-colors",onClick:()=>l(!0),children:i.jsx("img",{src:w,alt:r,className:"max-w-full max-h-[45vh] object-contain"})}),i.jsx(e2,{src:w,alt:r,isOpen:a,onClose:()=>l(!1)})]})}if(!t)return i.jsx("div",{className:"text-xs text-text-muted italic p-2",children:"Empty file"});const h=t;if(u==="markdown"){const w=DS(h);return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto p-2",children:i.jsx(Hn,{content:w})})}const p=DS(h),m=h.split(`
291
- `)[0],x=m==null?void 0:m.match(/^(\d+)\|/),y=x?parseInt(x[1],10):1;return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto",children:i.jsx(io,{code:p,language:u,variant:"block",showLineNumbers:!0,startLine:y})})});function f8({type:e,content:t}){const n=e==="added"?"diff-added-bg":e==="removed"?"diff-removed-bg":"bg-transparent",r=e==="added"?"+":e==="removed"?"-":" ";return i.jsxs("div",{className:`${n} px-2`,children:[i.jsx("span",{className:"select-none text-text-muted w-6 inline-block",children:r}),i.jsx("span",{className:"whitespace-pre-wrap break-words",children:t||" "})]})}function m8({diff:e}){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r||r.type==="unchanged"){n++;continue}if(r.type==="removed"){for(;n<e.length;){const a=e[n];if(!a||a.type!=="removed")break;t.push({type:"removed",content:a.content}),n++}for(;n<e.length;){const a=e[n];if(!a||a.type!=="added")break;t.push({type:"added",content:a.content}),n++}}else if(r.type==="added")for(;n<e.length;){const a=e[n];if(!a||a.type!=="added")break;t.push({type:"added",content:a.content}),n++}}return t.length===0?i.jsx("div",{className:"py-8 text-center text-text-muted",children:"No changes detected."}):i.jsxs("div",{children:[i.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-text-muted uppercase tracking-wide",children:"Changes:"}),i.jsx("div",{className:"font-mono text-xs leading-5",children:t.map((r,a)=>i.jsx(f8,{type:r.type,content:r.content},a))})]})}function Qg({isOpen:e,onClose:t,isRunning:n,onApply:r}){const[a,l]=N.useState(null),[u,c]=N.useState(!1),d=N.useRef(null),h=N.useCallback(()=>{c(!0);const p=Pt.send("context.applyDynamic.preview",{});d.current=p;const m=Pt.subscribe(x=>{if(x.id===p&&x.type==="context.preview"){const y=x.payload;l(y.diff??[]),c(!1),d.current=null,m()}});setTimeout(()=>{d.current===p&&(c(!1),d.current=null,m())},5e3)},[]);return N.useEffect(()=>{e&&(l(null),c(!0),h())},[e,h]),i.jsxs(wt,{isOpen:e,onClose:t,title:"Update system prompt",size:"lg",children:[i.jsxs("p",{className:"text-sm text-text-secondary mb-4",children:["Applying the new system prompt will rebuild the cached prompt, which may cause the next response to take longer while the LLM reprocesses the prefix.",n&&i.jsxs(i.Fragment,{children:[" ","Since the session is currently running, the update will be queued and applied at the start of the next turn."]})]}),u?i.jsx("div",{className:"py-8 text-center text-text-muted",children:"Loading diff..."}):a&&a.length>0?i.jsx("div",{className:"max-h-[60vh] overflow-auto border border-border rounded-lg",children:i.jsx(m8,{diff:a})}):i.jsx("p",{className:"text-sm text-text-tertiary mb-4",children:"The system prompt hash has changed (e.g., due to tool or skill changes), but the actual prompt text appears identical. Applying the update will still rebuild the cached prompt to ensure consistency."}),i.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[i.jsx("button",{onClick:t,className:"px-3 py-1.5 text-sm rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:"Cancel"}),i.jsx("button",{onClick:r,className:"px-3 py-1.5 text-sm rounded bg-accent-primary text-white hover:opacity-90 transition-colors",children:n?"Queue update":"Update"})]})]})}function t2({variant:e="popover",onUpdateSystemPrompt:t}){const n=Re(D=>D.contextState),r=Re(D=>D.currentSession),a=Re(D=>D.compactContext),l=Re(D=>D.queueUpdate),[u,c]=N.useState(!1),[d,h]=N.useState(!1);if(!n||!r)return null;const{currentTokens:p,maxTokens:m,compactionCount:x,dangerZone:y,dynamicContextChanged:w}=n,C=Math.round(p/m*100),_=r.isRunning,S=()=>{_?l():Pt.send("context.applyDynamic",{}),c(!1)},v=e==="sidebar",b=i.jsxs("span",{className:n8(C,y),children:[so(p)," / ",so(m)," (",C,"%)"]}),E=i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xg,{percent:C,dangerZone:y,className:"flex-1"}),i.jsx(s8,{dangerZone:y}),x>0&&i.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary px-1 py-0.5 rounded",children:[x,"x"]})]}),j=i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>h(!d),className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"More options",children:i.jsx(k1,{})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>h(!1)}),i.jsxs("div",{className:"absolute right-0 top-full mt-1.5 z-50 bg-bg-secondary border border-border rounded-lg shadow-xl py-1 min-w-[160px]",children:[i.jsx("button",{onClick:()=>{_||a(),h(!1)},disabled:_,className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors disabled:opacity-40 disabled:cursor-not-allowed",title:_?"Cannot compact while running":"Compact context",children:i.jsx("span",{className:y?"text-accent-error":"",children:"Compact"})}),w&&i.jsx("button",{onClick:()=>{h(!1),t?t():c(!0)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors",title:"Preview and apply system prompt changes",children:i.jsx("span",{className:"text-accent-warning",children:"Update system prompt"})})]})]})]}),T=t?null:i.jsx(Qg,{isOpen:u,onClose:()=>c(!1),isRunning:_,onApply:S});return v?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-start gap-2 mb-4",children:[i.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[i.jsx("div",{className:"text-sm",children:b}),E]}),i.jsx("div",{className:"shrink-0 pt-0.5",children:j})]}),T]}):i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"flex items-center justify-between text-sm",children:b}),E]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("button",{onClick:()=>{_||a()},disabled:_,className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors disabled:opacity-40 disabled:cursor-not-allowed rounded",title:_?"Cannot compact while running":"Compact context",children:i.jsx("span",{className:y?"text-accent-error":"",children:"Compact"})}),w&&i.jsx("button",{onClick:()=>{t?t():c(!0)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors rounded",title:"Preview and apply system prompt changes",children:i.jsx("span",{className:"text-accent-warning",children:"Update system prompt"})})]}),T]})}function RS({messages:e,workdir:t}){var v,b,E;const[n,r]=N.useState(!1),[a,l]=N.useState(!1),[u,c]=N.useState(null),d=wB(e),{branch:h}=Wg(),p=Qt(j=>j.version),m=Re(j=>j.currentSession),x=m!=null&&m.workspace?m.workspace.split("/").pop()??null:null,y=Ht(j=>j.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",w=Cs(j=>j.status),C=Cs(j=>j.check),[_,S]=N.useState(!1);return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsx(t2,{variant:"sidebar"}),d&&i.jsxs("div",{className:"mb-4",children:[i.jsx("button",{onClick:()=>r(!0),className:"w-full flex items-center justify-center px-3 py-2 rounded bg-bg-tertiary hover:bg-bg-secondary transition-colors",title:"View detailed response and call-level stats",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[i.jsx("span",{className:"text-text-secondary",children:Xr(d.aiTime)}),i.jsx("span",{className:"w-px h-3 bg-border"}),i.jsx("span",{className:"text-text-secondary",children:CS(d.avgPrefillSpeed)}),i.jsx("span",{children:"pp"}),i.jsx("span",{className:"w-px h-3 bg-border"}),i.jsx("span",{className:"text-text-secondary",children:CS(d.avgGenerationSpeed)}),i.jsx("span",{children:"tg"})]})}),i.jsx(IB,{isOpen:n,onClose:()=>r(!1),stats:d})]}),i.jsx("div",{className:"flex flex-col flex-1 overflow-y-auto scrollbar-stable",children:i.jsxs("div",{children:[i.jsx("button",{onClick:()=>c("criteria"),className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(fd,{entries:((v=m==null?void 0:m.metadataEntries)==null?void 0:v.criteria)??[],title:"Acceptance Criteria"})}),m&&i.jsx(Hk,{entries:((b=m==null?void 0:m.metadataEntries)==null?void 0:b.criteria)??[],sessionId:m.id}),m&&(()=>{const j=["review_findings","todos"],T=m.metadataEntries??{},D=j.filter(I=>I in T),L=Object.keys(T).filter(I=>I!=="criteria"&&!j.includes(I)).sort();return[...D,...L].filter(I=>{var P;return(((P=T[I])==null?void 0:P.length)??0)>0}).map(I=>i.jsxs("div",{className:"mt-6",children:[i.jsx("button",{onClick:()=>c(I),className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(fd,{entries:T[I],title:to(I)})}),i.jsx($k,{entries:T[I],onClearAll:async()=>{try{await Se(`/api/sessions/${m.id}/metadata/${I}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:[]})})}catch(P){console.error(`Failed to clear ${I}:`,P)}}})]},I))})()]})}),i.jsx(Zk,{workspaceName:x??"original",branch:h,workdir:t,showEditorLink:y,sessionId:(m==null?void 0:m.id)??"",projectId:(m==null?void 0:m.projectId)??""}),i.jsx(Vk,{workdir:t}),i.jsx(JB,{sessionId:m==null?void 0:m.id}),p&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-border text-center text-xs text-text-muted",children:[i.jsxs("div",{className:"flex items-center justify-center gap-1",children:[i.jsx("a",{href:"https://github.com/co-l/openfox",target:"_blank",rel:"noopener noreferrer",className:"hover:text-accent-primary transition-colors",children:"OpenFox"})," - ",i.jsxs("span",{className:"font-mono",children:["v",p]}),i.jsx("button",{onClick:()=>{S(!0),C(!0)},disabled:w==="checking",className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors disabled:opacity-50",title:"Check for updates",children:i.jsx(Sd,{className:`w-3 h-3 ${w==="checking"?"animate-spin":""}`})})]}),w==="available"&&i.jsx("button",{onClick:()=>l(!0),className:"text-accent-primary hover:underline mt-1",children:"Update OpenFox →"}),_&&w==="upToDate"&&i.jsx("div",{className:"mt-1",children:"Up to date"}),w==="error"&&i.jsx("div",{className:"mt-1",children:"Update check failed"})]}),i.jsx(U1,{isOpen:a,onClose:()=>l(!1),versionInfo:null}),i.jsx(zk,{isOpen:u!==null,onClose:()=>c(null),entries:((E=m==null?void 0:m.metadataEntries)==null?void 0:E[u??""])??[],sessionId:(m==null?void 0:m.id)??"",metadataKey:u??"",title:to(u??"")})]})}function p8({children:e,criteriaSidebarOpen:t=!0,onCriteriaSidebarToggle:n,messages:r}){const a=Re(l=>l.currentSession);return i.jsxs("div",{className:"relative h-full overflow-hidden",children:[t&&i.jsx("div",{className:"fixed md:hidden inset-0 bg-secondary/50 z-40",onClick:n}),i.jsxs("div",{className:"flex h-full",children:[i.jsx("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden bg-secondary",children:e}),t?i.jsx("aside",{className:"hidden md:block w-[320px] shrink-0 border-l border-border p-4 overflow-y-auto bg-secondary scrollbar-stable",children:i.jsx(RS,{messages:r,workdir:(a==null?void 0:a.workspace)??(a==null?void 0:a.workdir)})}):i.jsx("aside",{className:"hidden md:block w-0 shrink-0 overflow-hidden border-l-0"}),i.jsx("aside",{className:`
291
+ `)[0],x=m==null?void 0:m.match(/^(\d+)\|/),y=x?parseInt(x[1],10):1;return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto",children:i.jsx(io,{code:p,language:u,variant:"block",showLineNumbers:!0,startLine:y})})});function f8({type:e,content:t}){const n=e==="added"?"diff-added-bg":e==="removed"?"diff-removed-bg":"bg-transparent",r=e==="added"?"+":e==="removed"?"-":" ";return i.jsxs("div",{className:`${n} px-2`,children:[i.jsx("span",{className:"select-none text-text-muted w-6 inline-block",children:r}),i.jsx("span",{className:"whitespace-pre-wrap break-words",children:t||" "})]})}function m8({diff:e}){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r||r.type==="unchanged"){n++;continue}if(r.type==="removed"){for(;n<e.length;){const a=e[n];if(!a||a.type!=="removed")break;t.push({type:"removed",content:a.content}),n++}for(;n<e.length;){const a=e[n];if(!a||a.type!=="added")break;t.push({type:"added",content:a.content}),n++}}else if(r.type==="added")for(;n<e.length;){const a=e[n];if(!a||a.type!=="added")break;t.push({type:"added",content:a.content}),n++}}return t.length===0?i.jsx("div",{className:"py-8 text-center text-text-muted",children:"No changes detected."}):i.jsxs("div",{children:[i.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-text-muted uppercase tracking-wide",children:"Changes:"}),i.jsx("div",{className:"font-mono text-xs leading-5",children:t.map((r,a)=>i.jsx(f8,{type:r.type,content:r.content},a))})]})}function Qg({isOpen:e,onClose:t,isRunning:n,onApply:r}){const[a,l]=N.useState(null),[u,c]=N.useState(!1),d=N.useRef(null),h=N.useCallback(()=>{c(!0);const p=Pt.send("context.applyDynamic.preview",{});d.current=p;const m=Pt.subscribe(x=>{if(x.id===p&&x.type==="context.preview"){const y=x.payload;l(y.diff??[]),c(!1),d.current=null,m()}});setTimeout(()=>{d.current===p&&(c(!1),d.current=null,m())},5e3)},[]);return N.useEffect(()=>{e&&(l(null),c(!0),h())},[e,h]),i.jsxs(wt,{isOpen:e,onClose:t,title:"Update system prompt",size:"lg",children:[i.jsxs("p",{className:"text-sm text-text-secondary mb-4",children:["Applying the new system prompt will rebuild the cached prompt, which may cause the next response to take longer while the LLM reprocesses the prefix.",n&&i.jsxs(i.Fragment,{children:[" ","Since the session is currently running, the update will be queued and applied at the start of the next turn."]})]}),u?i.jsx("div",{className:"py-8 text-center text-text-muted",children:"Loading diff..."}):a&&a.length>0?i.jsx("div",{className:"max-h-[60vh] overflow-auto border border-border rounded-lg",children:i.jsx(m8,{diff:a})}):i.jsx("p",{className:"text-sm text-text-tertiary mb-4",children:"The system prompt hash has changed (e.g., due to tool or skill changes), but the actual prompt text appears identical. Applying the update will still rebuild the cached prompt to ensure consistency."}),i.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[i.jsx("button",{onClick:t,className:"px-3 py-1.5 text-sm rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:"Cancel"}),i.jsx("button",{onClick:r,className:"px-3 py-1.5 text-sm rounded bg-accent-primary text-white hover:opacity-90 transition-colors",children:n?"Queue update":"Update"})]})]})}function t2({variant:e="popover",onUpdateSystemPrompt:t}){const n=Re(D=>D.contextState),r=Re(D=>D.currentSession),a=Re(D=>D.compactContext),l=Re(D=>D.queueUpdate),[u,c]=N.useState(!1),[d,h]=N.useState(!1);if(!n||!r)return null;const{currentTokens:p,maxTokens:m,compactionCount:x,dangerZone:y,dynamicContextChanged:w}=n,C=Math.round(p/m*100),_=r.isRunning,S=()=>{_?l():Pt.send("context.applyDynamic",{}),c(!1)},v=e==="sidebar",b=i.jsxs("span",{className:n8(C,y),children:[so(p)," / ",so(m)," (",C,"%)"]}),E=i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xg,{percent:C,dangerZone:y,className:"flex-1"}),i.jsx(s8,{dangerZone:y}),x>0&&i.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary px-1 py-0.5 rounded",children:[x,"x"]})]}),j=i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>h(!d),className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"More options",children:i.jsx(k1,{})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>h(!1)}),i.jsxs("div",{className:"absolute right-0 top-full mt-1.5 z-50 bg-bg-secondary border border-border rounded-lg shadow-xl py-1 min-w-[160px]",children:[i.jsx("button",{onClick:()=>{_||a(),h(!1)},disabled:_,className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors disabled:opacity-40 disabled:cursor-not-allowed",title:_?"Cannot compact while running":"Compact context",children:i.jsx("span",{className:y?"text-accent-error":"",children:"Compact"})}),w&&i.jsx("button",{onClick:()=>{h(!1),t?t():c(!0)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors",title:"Preview and apply system prompt changes",children:i.jsx("span",{className:"text-accent-warning",children:"Update system prompt"})})]})]})]}),T=t?null:i.jsx(Qg,{isOpen:u,onClose:()=>c(!1),isRunning:_,onApply:S});return v?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-start gap-2 mb-4",children:[i.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[i.jsx("div",{className:"text-sm",children:b}),E]}),i.jsx("div",{className:"shrink-0 pt-0.5",children:j})]}),T]}):i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"flex items-center justify-between text-sm",children:b}),E]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("button",{onClick:()=>{_||a()},disabled:_,className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors disabled:opacity-40 disabled:cursor-not-allowed rounded",title:_?"Cannot compact while running":"Compact context",children:i.jsx("span",{className:y?"text-accent-error":"",children:"Compact"})}),w&&i.jsx("button",{onClick:()=>{t?t():c(!0)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-bg-tertiary transition-colors rounded",title:"Preview and apply system prompt changes",children:i.jsx("span",{className:"text-accent-warning",children:"Update system prompt"})})]}),T]})}function RS({messages:e,workdir:t}){var v,b,E;const[n,r]=N.useState(!1),[a,l]=N.useState(!1),[u,c]=N.useState(null),d=wB(e),{branch:h}=Wg(),p=Kt(j=>j.version),m=Re(j=>j.currentSession),x=m!=null&&m.workspace?m.workspace.split("/").pop()??null:null,y=Ht(j=>j.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",w=Cs(j=>j.status),C=Cs(j=>j.check),[_,S]=N.useState(!1);return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsx(t2,{variant:"sidebar"}),d&&i.jsxs("div",{className:"mb-4",children:[i.jsx("button",{onClick:()=>r(!0),className:"w-full flex items-center justify-center px-3 py-2 rounded bg-bg-tertiary hover:bg-bg-secondary transition-colors",title:"View detailed response and call-level stats",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[i.jsx("span",{className:"text-text-secondary",children:Xr(d.aiTime)}),i.jsx("span",{className:"w-px h-3 bg-border"}),i.jsx("span",{className:"text-text-secondary",children:CS(d.avgPrefillSpeed)}),i.jsx("span",{children:"pp"}),i.jsx("span",{className:"w-px h-3 bg-border"}),i.jsx("span",{className:"text-text-secondary",children:CS(d.avgGenerationSpeed)}),i.jsx("span",{children:"tg"})]})}),i.jsx(IB,{isOpen:n,onClose:()=>r(!1),stats:d})]}),i.jsx("div",{className:"flex flex-col flex-1 overflow-y-auto scrollbar-stable",children:i.jsxs("div",{children:[i.jsx("button",{onClick:()=>c("criteria"),className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(fd,{entries:((v=m==null?void 0:m.metadataEntries)==null?void 0:v.criteria)??[],title:"Acceptance Criteria"})}),m&&i.jsx(Hk,{entries:((b=m==null?void 0:m.metadataEntries)==null?void 0:b.criteria)??[],sessionId:m.id}),m&&(()=>{const j=["review_findings","todos"],T=m.metadataEntries??{},D=j.filter(I=>I in T),L=Object.keys(T).filter(I=>I!=="criteria"&&!j.includes(I)).sort();return[...D,...L].filter(I=>{var P;return(((P=T[I])==null?void 0:P.length)??0)>0}).map(I=>i.jsxs("div",{className:"mt-6",children:[i.jsx("button",{onClick:()=>c(I),className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(fd,{entries:T[I],title:to(I)})}),i.jsx($k,{entries:T[I],onClearAll:async()=>{try{await Se(`/api/sessions/${m.id}/metadata/${I}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:[]})})}catch(P){console.error(`Failed to clear ${I}:`,P)}}})]},I))})()]})}),i.jsx(Zk,{workspaceName:x??"original",branch:h,workdir:t,showEditorLink:y,sessionId:(m==null?void 0:m.id)??"",projectId:(m==null?void 0:m.projectId)??""}),i.jsx(Vk,{workdir:t}),i.jsx(JB,{sessionId:m==null?void 0:m.id}),p&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-border text-center text-xs text-text-muted",children:[i.jsxs("div",{className:"flex items-center justify-center gap-1",children:[i.jsx("a",{href:"https://github.com/co-l/openfox",target:"_blank",rel:"noopener noreferrer",className:"hover:text-accent-primary transition-colors",children:"OpenFox"})," - ",i.jsxs("span",{className:"font-mono",children:["v",p]}),i.jsx("button",{onClick:()=>{S(!0),C(!0)},disabled:w==="checking",className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors disabled:opacity-50",title:"Check for updates",children:i.jsx(Sd,{className:`w-3 h-3 ${w==="checking"?"animate-spin":""}`})})]}),w==="available"&&i.jsx("button",{onClick:()=>l(!0),className:"text-accent-primary hover:underline mt-1",children:"Update OpenFox →"}),_&&w==="upToDate"&&i.jsx("div",{className:"mt-1",children:"Up to date"}),w==="error"&&i.jsx("div",{className:"mt-1",children:"Update check failed"})]}),i.jsx(U1,{isOpen:a,onClose:()=>l(!1),versionInfo:null}),i.jsx(zk,{isOpen:u!==null,onClose:()=>c(null),entries:((E=m==null?void 0:m.metadataEntries)==null?void 0:E[u??""])??[],sessionId:(m==null?void 0:m.id)??"",metadataKey:u??"",title:to(u??"")})]})}function p8({children:e,criteriaSidebarOpen:t=!0,onCriteriaSidebarToggle:n,messages:r}){const a=Re(l=>l.currentSession);return i.jsxs("div",{className:"relative h-full overflow-hidden",children:[t&&i.jsx("div",{className:"fixed md:hidden inset-0 bg-secondary/50 z-40",onClick:n}),i.jsxs("div",{className:"flex h-full",children:[i.jsx("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden bg-secondary",children:e}),t?i.jsx("aside",{className:"hidden md:block w-[320px] shrink-0 border-l border-border p-4 overflow-y-auto bg-secondary scrollbar-stable",children:i.jsx(RS,{messages:r,workdir:(a==null?void 0:a.workspace)??(a==null?void 0:a.workdir)})}):i.jsx("aside",{className:"hidden md:block w-0 shrink-0 overflow-hidden border-l-0"}),i.jsx("aside",{className:`
292
292
  md:hidden
293
293
  p-4 overflow-y-auto bg-secondary
294
294
  transition-all duration-300 ease-in-out
@@ -305,12 +305,12 @@ WARNING: This link could potentially be dangerous`)){const S=window.open();if(S)
305
305
  px-3 py-1 rounded text-xs font-medium
306
306
  transition-colors
307
307
  ${n?"bg-amber-500/20 text-amber-400 cursor-not-allowed opacity-50":"bg-red-500/20 text-red-300 hover:bg-red-500/30 hover:text-red-200"}
308
- `,children:n?"Reconnecting...":"Reconnect"})]})}const mn=Mn((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchCommands:async()=>{await Sk("/api/commands",e,!0)},fetchCommand:async n=>{try{const r=await Se(`/api/commands/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await Se(`/api/commands/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createCommand:async(n,r)=>{const a=await ui("POST","/api/commands",{...n,destination:r});return a.success&&await t().fetchCommands(),a},updateCommand:async(n,r)=>{const a=await ui("PUT",`/api/commands/${n}`,r);return a.success&&await t().fetchCommands(),a},deleteCommand:async n=>{try{const r=await Se(`/api/commands/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async(n,r)=>vd(`/api/commands/${n}/duplicate`,()=>t().fetchCommands(),r)}));function x$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function y$({onClick:e}){return i.jsx("button",{type:"button",onClick:e,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:i.jsx(eg,{})})}function u2({isOpen:e,onClose:t,initialEditId:n}){const r=mn(fe=>fe.defaults),a=mn(fe=>fe.userItems),l=mn(fe=>fe.projectItems),u=mn(fe=>fe.loading),c=mn(fe=>fe.fetchCommands),d=mn(fe=>fe.fetchCommand),h=mn(fe=>fe.fetchDefaultContent),p=mn(fe=>fe.createCommand),m=mn(fe=>fe.updateCommand),x=mn(fe=>fe.deleteCommand),[y,w]=N.useState(null),[C,_]=N.useState(null),{view:S,editingId:v,formError:b,saving:E,formData:j,setView:T,setEditingId:D,setFormError:L,setFormData:I,setSaving:P}=M1(),{requestDelete:W,clearConfirm:H,isConfirming:R}=Wl(),U=N.useRef(!1),V=mt(fe=>fe.defaults),G=mt(fe=>fe.userItems),Z=mt(fe=>fe.fetchAgents),$=[...V,...G].filter(fe=>!fe.subagent),O=N.useRef(c),M=N.useRef(Z),q=N.useRef(d),z=N.useRef(h),ee=N.useRef(n),Q=N.useRef(T),ne=N.useRef(D),K=N.useRef(L),B=N.useRef(H);N.useEffect(()=>{O.current=c,M.current=Z,q.current=d,z.current=h,ee.current=n,Q.current=T,ne.current=D,K.current=L,B.current=H}),N.useEffect(()=>{if(e)if(O.current(),M.current(),U.current||(B.current(),U.current=!0),ee.current){const fe=r.some(ce=>ce.id===ee.current);Q.current("edit"),ne.current(ee.current),K.current(""),fe?z.current(ee.current).then(ce=>{ce&&I({name:ce.metadata.name+" (copy)",id:`${ee.current}-copy-${Date.now()}`,prompt:ce.prompt,agentMode:ce.metadata.agentMode??"",isDefault:!0,destination:"user"})}):q.current(ee.current).then(ce=>{ce&&I({name:ce.metadata.name,id:ce.metadata.id,prompt:ce.prompt,agentMode:ce.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else Q.current("list"),ne.current(null);else U.current=!1},[e]);const te=async fe=>{w(fe);const ce=await h(fe);_((ce==null?void 0:ce.prompt)??null)},se=async fe=>{if(r.some(de=>de.id===fe)){const de=await h(fe);de&&(D(null),I({name:`${de.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:de.prompt,agentMode:de.metadata.agentMode??"",isDefault:!0,destination:"user"}),L(""),T("edit"))}else{const de=await d(fe);de&&(D(null),I({name:`${de.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:de.prompt,agentMode:de.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))}},xe=()=>{I({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),D(null),T("edit")},oe=async fe=>{const ce=await d(fe);ce&&(D(fe),I({name:ce.metadata.name,id:ce.metadata.id,prompt:ce.prompt,agentMode:ce.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))},Oe=async fe=>{await x(fe),H()},Me=async()=>{const fe=v??j.id;if(!fe||!j.name||!j.prompt){L("Name and message are required.");return}P(!0),L("");const ce={metadata:{id:fe,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},de=v?await m(v,ce):await p(ce,j.destination);if(P(!1),!de.success){L(de.error??"Failed to save command.");return}n?t():T("list")},ze=()=>{n?t():(T("list"),w(null),_(null))},$e=fe=>{I(ce=>({...ce,name:fe})),(!v||j.isDefault)&&I(ce=>({...ce,id:x$(fe)}))},je=()=>{w(null),_(null),T("list")},rt=()=>{y&&(w(null),T("edit"),D(y),h(y).then(fe=>{fe&&I({name:`${fe.metadata.name} (copy)`,id:`${y}-copy-${Date.now()}`,prompt:fe.prompt,agentMode:fe.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(y){const fe=r.find(ce=>ce.id===y);return i.jsx(wt,{isOpen:e,onClose:je,title:`Default: ${(fe==null?void 0:fe.name)??y}`,size:"xl",children:i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[i.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),i.jsx("span",{className:"font-mono",children:y})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),i.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:fe==null?void 0:fe.name})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),i.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(fe==null?void 0:fe.agentMode)||"None"})]})]}),i.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),i.jsx("textarea",{value:C??"",readOnly:!0,placeholder:"...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none opacity-60"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[i.jsx(Ze,{variant:"secondary",onClick:je,children:"Close"}),i.jsx(Ze,{variant:"primary",onClick:rt,children:"Duplicate & Customize"})]})]})})}if(S==="edit")return i.jsx(wt,{isOpen:e,onClose:ze,title:v?"Edit Command":"New Command",size:"xl",children:i.jsxs("div",{className:"flex flex-col h-full",children:[b&&i.jsx(Qa,{message:b}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(I1,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!j.isDefault,onNameChange:$e,onIdChange:fe=>I(ce=>({...ce,id:fe}))}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsxs("select",{value:j.agentMode,onChange:fe=>I(ce=>({...ce,agentMode:fe.target.value})),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[i.jsx("option",{value:"",children:"None (keep current mode)"}),$.map(fe=>i.jsx("option",{value:fe.id,children:fe.name},fe.id))]})]}),!v&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Save to:"}),i.jsxs("select",{value:j.destination,onChange:fe=>I(ce=>({...ce,destination:fe.target.value})),className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[i.jsx("option",{value:"user",children:"Global config"}),i.jsx("option",{value:"project",children:"Project (.openfox/)"})]})]})]}),i.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),i.jsx("textarea",{value:j.prompt,onChange:fe=>I(ce=>({...ce,prompt:fe.target.value})),placeholder:"The message that will be sent when this command is triggered...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[i.jsx(Ze,{variant:"secondary",onClick:ze,children:"Cancel"}),i.jsx(Ze,{variant:"primary",onClick:Me,disabled:E||!j.name||!j.prompt,children:E?"Saving...":"Save"})]})]})});const Qe=fe=>fe.map(ce=>i.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[i.jsx("div",{className:"min-w-0 flex-1 mr-3",children:i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("span",{className:"text-text-primary text-sm font-medium",children:ce.name})})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(qi,{onClick:()=>oe(ce.id)}),i.jsx(Ku,{onClick:()=>se(ce.id)}),R(ce.id,"delete")?i.jsx(ig,{onConfirm:()=>Oe(ce.id),onCancel:H}):i.jsx(ag,{onClick:()=>W(ce.id)})]})]},ce.id));return i.jsxs(wt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[i.jsx(O1,{description:"Commands are pre-defined messages you can send with a single click.",onNew:xe}),i.jsxs(og,{loading:u,hasItems:r.length>0||a.length>0||l.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[r.length>0&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),i.jsx("div",{className:"space-y-2",children:r.map(fe=>i.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[i.jsx("div",{className:"min-w-0 flex-1 mr-3",children:i.jsx("span",{className:"text-text-primary text-sm font-medium",children:fe.name})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(y$,{onClick:()=>te(fe.id)}),i.jsx(Ku,{onClick:()=>se(fe.id)})]})]},fe.id))})]}),a.length>0&&i.jsx(R1,{children:Qe(a)}),l.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),i.jsx("div",{className:"space-y-2",children:Qe(l)})]})]})]})}const Oi=150,bs=54,Iu=80,Lr=30,Ua=70,$S=100,Ii=50,Mu=50,zS=4,d2={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},h2=[{value:"step_result",label:"Step result is..."},{value:"metadata_all_match",label:"Metadata all match (key=value)"},{value:"metadata_all_in",label:"Metadata all in list"},{value:"always",label:"Always (fallback)"}],b$=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}];function ex(e,t){if(e.type==="agent"){const n=t.find(r=>r.id===e.agentId);return{name:(n==null?void 0:n.name)??(e.agentId||"Agent"),color:(n==null?void 0:n.color)||"#3b82f6"}}if(e.type==="sub_agent"){const n=t.find(r=>r.id===e.subAgentType);return{name:(n==null?void 0:n.name)??(e.subAgentType||"Sub-Agent"),color:(n==null?void 0:n.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function v$(e,t,n,r){const a=Mu+Ii+Oi+$S+Oi+Ii+Mu,l=a/2,u=Mu+Ii+Oi/2,c=Mu+Ii+Oi+$S+Oi/2,d=[],h=[],p=new Map,m=e.filter(V=>V.type==="agent"||V.type==="shell"),x=e.filter(V=>V.type==="sub_agent"),y=x.length>0,w=y?u:l,C=m.length>0?c:l,_=Ii+Lr/2;d.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:_,w:Iu,h:Lr}),p.set("$start",{cx:w,cy:_,w:Iu,h:Lr});const S=V=>{d.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:V,w:Iu,h:Lr}),p.set("$done",{cx:w,cy:V,w:Iu,h:Lr})};if(e.length===0){const V=_+Lr/2+Ua*2+Lr/2;return S(V),{nodes:d,edges:h,width:a,height:V+Lr/2+Ii,posMap:p}}const v=_+Lr/2+Ua,b=(V,G)=>{V.forEach((Z,X)=>{const $=v+X*(bs+Ua)+bs/2,{name:O,color:M}=ex(Z,r);d.push({id:Z.id,type:"step",label:O,color:M,cx:G,cy:$,w:Oi,h:bs}),p.set(Z.id,{cx:G,cy:$,w:Oi,h:bs})})};b(m,w),b(x,C);const E=m.length>0?v+(m.length-1)*(bs+Ua)+bs/2:_,j=y?v+(x.length-1)*(bs+Ua)+bs/2:_,T=Math.max(E,j)+bs/2+Ua+Lr/2;S(T);const D=[];t&&p.has(t)&&D.push({from:"$start",to:t,label:n,edgeKey:"start",direction:"down",backEdgeIndex:0});let L=0;for(const V of e)V.transitions.forEach((G,Z)=>{var z;if(!G.goto||!p.has(G.goto))return;const X=p.get(V.id),$=p.get(G.goto),O=G.when.type==="step_result"?`${G.when.result}`:G.when.type==="metadata_all_match"?`${G.when.key??"?"}=${G.when.value??"?"}`:G.when.type==="metadata_all_in"?`${G.when.key??"?"} in [${((z=G.when.values)==null?void 0:z.join(","))??"?"}]`:d2[G.when.type]??G.when.type,M=V.id===G.goto;let q;M?q="back":$.cy>X.cy+1?q="down":$.cy<X.cy-1?q="back":q="same",D.push({from:V.id,to:G.goto,label:O,edgeKey:`${V.id}:${Z}`,direction:q,backEdgeIndex:q==="back"?L++:0})});const I=new Map,P=new Map,W=new Map,H=new Map;for(const V of D)V.direction==="down"&&(I.set(V.from,(I.get(V.from)??0)+1),P.set(V.to,(P.get(V.to)??0)+1));const R=new Map,U=new Map;for(const V of D){if(V.direction!=="same")continue;const G=[V.from,V.to].sort().join("|");R.set(G,(R.get(G)??0)+1)}for(const V of D){if(V.direction==="back"||V.direction==="same"){let q=0;if(V.direction==="same"){const z=[V.from,V.to].sort().join("|");q=U.get(z)??0,U.set(z,q+1)}h.push({...V,fromPort:0,toPort:0,sameEdgeIndex:q});continue}const G=I.get(V.from)??1,Z=P.get(V.to)??1,X=W.get(V.from)??0,$=H.get(V.to)??0;W.set(V.from,X+1),H.set(V.to,$+1);const O=G===1?0:-.6+1.2*X/(G-1),M=Z===1?0:-.6+1.2*$/(Z-1);h.push({...V,fromPort:O,toPort:M,sameEdgeIndex:0})}return{nodes:d,edges:h,width:a,height:T+Lr/2+Ii,posMap:p}}function _$({steps:e,entryStep:t,selectedNodeId:n,selectedEdgeKey:r,startConditionLabel:a,agentTypes:l,isReadOnly:u,onSelectNode:c,onSelectEdge:d,onRemoveStep:h,onCreateTransition:p,onReconnectTo:m,onReconnectFrom:x,onDeleteTransition:y}){const w=N.useRef(null),C=N.useRef(!1),[_,S]=N.useState(null),[v,b]=N.useState(null),[E,j]=N.useState(null),{nodes:T,edges:D,width:L,height:I,posMap:P}=N.useMemo(()=>v$(e,t,a,l),[e,t,a,l]),W=N.useCallback(Q=>{var se;const ne=w.current;if(!ne)return{x:0,y:0};const K=ne.createSVGPoint();K.x=Q.clientX,K.y=Q.clientY;const B=(se=ne.getScreenCTM())==null?void 0:se.inverse();if(!B)return{x:0,y:0};const te=K.matrixTransform(B);return{x:te.x,y:te.y}},[]),H=N.useCallback(Q=>!Q||!v||Q==="$start"?!1:v.type==="reconnect-from"?Q!=="$done":!0,[v]),R=N.useCallback((Q,ne)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const K=W(Q);b({type:"new",fromNodeId:ne,mouseX:K.x,mouseY:K.y})},[W,u]),U=N.useCallback((Q,ne)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const K=W(Q);b({type:"reconnect-to",fromNodeId:ne.from,edgeKey:ne.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),V=N.useCallback((Q,ne)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const K=W(Q);b({type:"reconnect-from",fromNodeId:ne.from,fixedTargetId:ne.to,edgeKey:ne.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),G=N.useCallback(Q=>{if(!v)return;const ne=W(Q);b(K=>K?{...K,mouseX:ne.x,mouseY:ne.y}:null)},[v,W]),Z=N.useCallback(()=>{v&&(C.current=!0,E&&H(E)&&(v.type==="new"?p(v.fromNodeId,E):v.type==="reconnect-to"?m(v.edgeKey,E):v.type==="reconnect-from"&&x(v.edgeKey,E)),b(null),j(null))},[v,E,H,p,m,x]),X=N.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);N.useEffect(()=>{if(u)return;const Q=ne=>{ne.target instanceof HTMLInputElement||ne.target instanceof HTMLTextAreaElement||ne.target instanceof HTMLSelectElement||(ne.key==="Delete"||ne.key==="Backspace")&&r&&r!=="start"&&(ne.preventDefault(),y(r),d(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[u,r,y,d]);const $=Q=>{const ne=P.get(Q.from),K=P.get(Q.to);if(!ne||!K)return null;let B,te,se,xe="middle",oe,Oe;if(Q.direction==="down"){const Me=ne.cx+Q.fromPort*(ne.w/2-10),ze=ne.cy+ne.h/2,$e=K.cx+Q.toPort*(K.w/2-10),je=K.cy-K.h/2,rt=je-ze,Qe=$e-Me;B=`M ${Me} ${ze} C ${Me} ${ze+rt*.4}, ${$e-Qe*.2} ${je-rt*.1}, ${$e} ${je}`,te=Me+($e-Me)*.5,se=ze+rt*.6,oe={x:Me,y:ze},Oe={x:$e,y:je}}else if(Q.direction==="back"){const Me=Q.from===Q.to,ze=ne.cx>=L/2,$e=Q.backEdgeIndex*16,je=ze?L-20-$e:20+$e;if(Me){const rt=ne.cx>=L/2,Qe=30+Q.backEdgeIndex*14,fe=ne.cy-ne.h/2,ce=rt?ne.cx+ne.w/2:ne.cx-ne.w/2,de=rt?ce+Qe:ce-Qe,he=ne.cx+(rt?ne.w/4:-ne.w/4),De=fe-20-Q.backEdgeIndex*10;B=`M ${ce} ${ne.cy} C ${de} ${ne.cy}, ${de} ${De}, ${he} ${fe}`,te=de+10,se=De+4,xe="middle",oe={x:ce,y:ne.cy},Oe={x:he,y:fe}}else{const rt=ze?ne.cx+ne.w/2:ne.cx-ne.w/2,Qe=K.cx+(ze?K.w/4:-K.w/4),fe=Math.min(ne.cy,K.cy)-K.h/2-18-Q.backEdgeIndex*14;B=`M ${rt} ${ne.cy} L ${je} ${ne.cy} L ${je} ${fe} L ${Qe} ${fe} L ${Qe} ${K.cy-K.h/2}`,te=je,se=(ne.cy+fe)/2,xe=ze?"start":"end",oe={x:rt,y:ne.cy},Oe={x:Qe,y:K.cy-K.h/2}}}else{const Me=K.cx>ne.cx,ze=Q.sameEdgeIndex===0?-12:12,$e=Me?ne.cx+ne.w/2:ne.cx-ne.w/2,je=Me?K.cx-K.w/2:K.cx+K.w/2,rt=ne.cy+ze,Qe=K.cy+ze,fe=($e+je)/2;B=`M ${$e} ${rt} C ${fe} ${rt}, ${fe} ${Qe}, ${je} ${Qe}`,te=fe,se=(rt+Qe)/2-6,oe={x:$e,y:rt},Oe={x:je,y:Qe}}return{path:B,labelX:te,labelY:se,labelAnchor:xe,fromPt:oe,toPt:Oe}},O=(Q,ne)=>{const K=$(Q);if(!K)return null;const{path:B,labelX:te,labelY:se,labelAnchor:xe}=K,oe=r===Q.edgeKey,Oe=Q.label&&Q.label!=="otherwise";return i.jsxs("g",{children:[i.jsx("path",{d:B,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Me=>{Me.stopPropagation(),u||d(oe?null:Q.edgeKey)}}),i.jsx("path",{d:B,fill:"none",stroke:oe?"#58a6ff":"#484f58",strokeWidth:oe?2.2:1.2,markerEnd:oe?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Oe&&i.jsx("text",{x:te+(xe==="start"?5:xe==="end"?-5:0),y:se+3,textAnchor:xe,className:"text-[8px]",fill:oe?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Q.label})]},ne)},M=()=>{if(!r||v)return null;const Q=D.find(se=>se.edgeKey===r);if(!Q)return null;const ne=$(Q);if(!ne)return null;const{fromPt:K,toPt:B}=ne,te=6;return i.jsxs(i.Fragment,{children:[Q.edgeKey!=="start"&&i.jsx("circle",{cx:K.x,cy:K.y,r:te,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:se=>V(se,Q)}),i.jsx("circle",{cx:B.x,cy:B.y,r:te,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:se=>U(se,Q)})]})},q=()=>{if(!v)return null;let Q,ne,K,B;if(v.type==="reconnect-from"){const xe=P.get(v.fixedTargetId);if(!xe)return null;Q=v.mouseX,ne=v.mouseY,K=xe.cx,B=xe.cy-xe.h/2}else{const xe=P.get(v.fromNodeId);if(!xe)return null;Q=xe.cx,ne=xe.cy+xe.h/2,K=v.mouseX,B=v.mouseY}const te=B-ne,se=Math.abs(te)>10?`M ${Q} ${ne} C ${Q} ${ne+te*.4}, ${K} ${B-te*.4}, ${K} ${B}`:`M ${Q} ${ne} L ${K} ${B}`;return i.jsx("path",{d:se,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},z=Q=>{const ne=Q.cy+Q.h/2,K=(v==null?void 0:v.fromNodeId)===Q.id;return i.jsx("circle",{cx:Q.cx,cy:ne,r:zS,fill:K?"#58a6ff":"#1c2128",stroke:K?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5,className:"cursor-crosshair",onMouseDown:B=>R(B,Q.id)})},ee=Q=>{const ne=Q.cy-Q.h/2,K=v&&E===Q.id&&H(Q.id);return i.jsx("circle",{cx:Q.cx,cy:ne,r:zS,fill:K?"#3fb950":"#1c2128",stroke:K?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5})};return i.jsxs("svg",{ref:w,viewBox:`0 0 ${L} ${I}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:G,onMouseUp:Z,onClick:X,children:[i.jsxs("defs",{children:[i.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:i.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),i.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:i.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),D.map((Q,ne)=>O(Q,ne)),T.map(Q=>{const ne=n===Q.id,K=Q.cx-Q.w/2,B=Q.cy-Q.h/2,te=_===Q.id,se=v&&E===Q.id&&H(Q.id);if(Q.type==="terminal"){const oe=Q.id==="$start",Oe=oe?"#58a6ff":"#3fb950",Me=oe,ze=!oe;return i.jsxs("g",{onClick:$e=>{$e.stopPropagation(),oe&&!u&&d("start")},className:oe&&!u?"cursor-pointer":void 0,children:[se&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),oe&&r==="start"&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:B,width:Q.w,height:Q.h,rx:Q.h/2,fill:Oe,fillOpacity:.08,stroke:Oe,strokeOpacity:.4,strokeWidth:1.5}),i.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Oe,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),Me&&z(Q),ze&&ee(Q)]},Q.id)}const xe=Q.color??"#6b7280";return i.jsxs("g",{onClick:oe=>{oe.stopPropagation(),u||c(ne?null:Q.id)},onMouseEnter:()=>S(Q.id),onMouseLeave:()=>S(null),className:u?void 0:"cursor-pointer",children:[se&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ne&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:B,width:Q.w,height:Q.h,rx:10,fill:xe,fillOpacity:.08,stroke:xe,strokeOpacity:.6,strokeWidth:ne?2:1.5}),i.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:Q.label}),!u&&z(Q),!u&&ee(Q),te&&!v&&!u&&i.jsxs("g",{onClick:oe=>{oe.stopPropagation(),h(Q.id)},className:"cursor-pointer",children:[i.jsx("circle",{cx:K+Q.w-2,cy:B+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),i.jsx("line",{x1:K+Q.w-5,y1:B-1,x2:K+Q.w+1,y2:B+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),i.jsx("line",{x1:K+Q.w+1,y1:B-1,x2:K+Q.w-5,y2:B+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),v&&T.map(Q=>H(Q.id)?i.jsx("rect",{x:Q.cx-Q.w/2-8,y:Q.cy-Q.h/2-8,width:Q.w+16,height:Q.h+16,fill:"transparent",rx:12,onMouseEnter:()=>j(Q.id),onMouseLeave:()=>j(null),onMouseUp:ne=>{ne.stopPropagation(),Z()}},`drop-${Q.id}`):null),q(),M()]})}const Pu="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",bl="block text-[11px] text-text-secondary mb-0.5";function S$({formName:e,formId:t,formDescription:n,formMaxIterations:r,formColor:a,isReadOnly:l,onNameChange:u,onDescriptionChange:c,onMaxIterationsChange:d,onColorChange:h}){return i.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[i.jsxs("div",{className:"min-w-[140px]",children:[i.jsx("label",{className:bl,children:"Name"}),i.jsx("input",{value:e,onChange:p=>u(p.target.value),placeholder:"Workflow name",className:`${Pu} ${l?"opacity-50":""}`,readOnly:l})]}),i.jsxs("div",{className:"min-w-[100px]",children:[i.jsx("label",{className:bl,children:"ID"}),i.jsx("input",{value:t,readOnly:!0,className:`${Pu} font-mono opacity-50`})]}),i.jsxs("div",{className:"flex-1 min-w-[140px]",children:[i.jsx("label",{className:bl,children:"Description"}),i.jsx("input",{value:n,onChange:p=>!l&&c(p.target.value),readOnly:l,placeholder:"What does this workflow do?",className:`${Pu} ${l?"opacity-50":""}`})]}),i.jsxs("div",{className:"w-20",children:[i.jsx("label",{className:bl,children:"Max Iter."}),i.jsx("input",{type:"number",value:r,onChange:p=>!l&&d(Number(p.target.value)),readOnly:l,className:`${Pu} font-mono ${l?"opacity-50":""}`})]}),i.jsxs("div",{children:[i.jsx("label",{className:bl,children:"Color"}),i.jsx("input",{type:"color",value:a,onChange:p=>!l&&h(p.target.value),disabled:l,className:`w-8 h-8 rounded border border-border bg-transparent ${l?"opacity-50":"cursor-pointer"}`})]})]})}function w$({name:e,id:t,color:n,description:r,isBuiltIn:a,actions:l}){return i.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:n}}),i.jsx("span",{className:"text-text-primary text-sm font-medium",children:e}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:t}),a&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),r&&i.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:r})]}),i.jsx("div",{className:"flex items-center gap-1 flex-shrink-0 ml-3",children:l})]})}function HS({title:e,items:t,renderActions:n}){return t.length===0?null:i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsx("div",{className:"space-y-2",children:t.map(r=>i.jsx(w$,{name:r.name,id:r.id,color:r.color??"#3b82f6",description:r.description,actions:n(r)},r.id))})]})}const Fa="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",ap="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",vs="block text-[11px] text-text-secondary mb-0.5";function op({variables:e,onInsert:t}){return e.length===0?null:i.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(n=>i.jsx("button",{type:"button",onClick:()=>t(n.name),title:n.description,className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-bg-primary border border-border text-text-secondary hover:text-accent-primary hover:border-accent-primary/40 transition-colors",children:`{{${n.name}}}`},n.name))})}function C$({step:e,isEntry:t,agentTypes:n,transitionCount:r,templateVariables:a,onUpdate:l,onRemove:u,onSetEntry:c}){const{color:d,name:h}=ex(e,n);return i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:d+"20",color:d},children:h}),t&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[!t&&i.jsx("button",{onClick:c,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),i.jsx("button",{onClick:u,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Type"}),i.jsx("select",{value:e.type,onChange:p=>{const m=p.target.value,x=m==="sub_agent"?"verification":"build";if(m==="agent"){const y=n.find(w=>!w.subagent);l({...e,type:m,phase:x,agentId:(y==null?void 0:y.id)??"builder",name:(y==null?void 0:y.name)??"Agent"})}else if(m==="sub_agent"){const y=n.find(w=>w.subagent);l({...e,type:m,phase:x,subAgentType:(y==null?void 0:y.id)??"",name:(y==null?void 0:y.name)??"Sub-Agent"})}else l({...e,type:m,phase:x,name:"Shell"})},className:ap,children:b$.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))})]}),e.type==="agent"&&i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Agent Type"}),i.jsx("select",{value:e.agentId??"builder",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,agentId:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:ap,children:n.filter(p=>!p.subagent).map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))})]}),e.type==="sub_agent"&&i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Sub-Agent Type"}),i.jsxs("select",{value:e.subAgentType??"",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,subAgentType:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:ap,children:[i.jsx("option",{value:"",children:"— select —"}),n.filter(p=>p.subagent).map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Prompt"}),i.jsx("textarea",{value:e.prompt??"",onChange:p=>l({...e,prompt:p.target.value||void 0}),rows:6,className:`${Fa} resize-y text-xs`,placeholder:"Injected on first entry..."}),i.jsx(op,{variables:a,onInsert:p=>l({...e,prompt:(e.prompt??"")+`{{${p}}}`})})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Nudge Prompt"}),i.jsx("textarea",{value:e.nudgePrompt??"",onChange:p=>l({...e,nudgePrompt:p.target.value||void 0}),rows:6,className:`${Fa} resize-y text-xs`,placeholder:"Injected on re-entry..."}),i.jsx(op,{variables:a,onInsert:p=>l({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${p}}}`})})]})]}),e.type==="shell"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Command"}),i.jsx("textarea",{value:e.command??"",onChange:p=>l({...e,command:p.target.value}),rows:3,className:`${Fa} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),i.jsx(op,{variables:a,onInsert:p=>l({...e,command:(e.command??"")+`{{${p}}}`})})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Timeout (ms)"}),i.jsx("input",{type:"number",value:e.timeout??6e4,onChange:p=>l({...e,timeout:Number(p.target.value)}),className:`${Fa} font-mono text-xs`})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Success Codes"}),i.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:p=>l({...e,successExitCodes:p.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${Fa} font-mono text-xs`})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Sub-group"}),i.jsx("input",{value:e.subGroup??"",onChange:p=>l({...e,subGroup:p.target.value||void 0}),placeholder:"e.g. build, verify, review",className:Fa})]}),i.jsx("div",{className:"pt-1 border-t border-border/50",children:i.jsxs("p",{className:"text-text-muted text-[10px]",children:[r," outgoing transition",r!==1?"s":""," — drag from the bottom port to connect."]})})]})}const Va="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",US="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Mi="block text-[11px] text-text-secondary mb-0.5";function k$({fromLabel:e,toLabel:t,condition:n,subGroup:r,fromStep:a,agentTypes:l,transitionIndex:u,totalTransitions:c,onUpdateCondition:d,onUpdateSubGroup:h,onDelete:p,onMoveUp:m,onMoveDown:x}){var C;const y=a&&(a.type==="sub_agent"||a.type==="agent")?l.find(_=>_.id===(a.type==="sub_agent"?a.subAgentType:a.agentId)):void 0,w=(y==null?void 0:y.results)&&y.results.length>0;return i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:["#",u+1]}),c>1&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:m,disabled:u===0,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move up (higher priority)",children:i.jsx(yn,{className:"w-3 h-3",rotate:180})}),i.jsx("button",{onClick:x,disabled:u===c-1,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move down (lower priority)",children:i.jsx(yn,{className:"w-3 h-3"})})]})]}),i.jsx("button",{onClick:p,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[i.jsx("span",{className:"font-medium text-text-primary",children:e}),i.jsx(_1,{}),i.jsx("span",{className:"font-medium text-text-primary",children:t})]}),i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Condition"}),i.jsx("select",{value:n.type,onChange:_=>{d(_.target.value==="step_result"?{type:"step_result",result:"success"}:{type:_.target.value})},className:US,children:h2.map(_=>i.jsx("option",{value:_.value,children:_.label},_.value))})]}),n.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Result"}),w?i.jsx("select",{value:n.result??y.results[0],onChange:_=>{d({type:"step_result",result:_.target.value})},className:US,children:y.results.map(_=>i.jsx("option",{value:_,children:_},_))}):i.jsx("input",{type:"text",value:n.result??"success",onChange:_=>d({type:"step_result",result:_.target.value}),placeholder:"e.g. success, passed, failed",className:Va})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Metadata Key"}),i.jsx("input",{type:"text",value:n.key??"",onChange:_=>d({...n,key:_.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:Va})]}),i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Field"}),i.jsx("input",{type:"text",value:n.field??"",onChange:_=>d({...n,field:_.target.value}),placeholder:"e.g. status",className:Va})]}),n.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Value"}),i.jsx("input",{type:"text",value:n.value??"",onChange:_=>d({...n,value:_.target.value}),placeholder:"e.g. passed, resolved",className:Va})]}):i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((C=n.values)==null?void 0:C.join(", "))??"",onChange:_=>d({...n,values:_.target.value.split(",").map(S=>S.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:Va})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Sub-group"}),i.jsx("input",{type:"text",value:r??"",onChange:_=>h(_.target.value||void 0),placeholder:"e.g. build, verify",className:Va})]}),i.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function E$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function j$(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const vl="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",FS="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Ga="block text-[11px] text-text-secondary mb-0.5",VS=[];function f2({isOpen:e,onClose:t,initialEditId:n}){var vn,rn;const r=Ot(Ce=>Ce.defaults),a=Ot(Ce=>Ce.userItems),l=Ot(Ce=>Ce.loading),u=Ot(Ce=>Ce.templateVariables),c=Ot(Ce=>Ce.fetchWorkflows),d=Ot(Ce=>Ce.fetchWorkflow),h=Ot(Ce=>Ce.fetchDefaultContent),p=Ot(Ce=>Ce.fetchTemplateVariables),m=Ot(Ce=>Ce.createWorkflow),x=Ot(Ce=>Ce.updateWorkflow),y=Ot(Ce=>Ce.deleteWorkflow),{requestDelete:w,clearConfirm:C,isConfirming:_}=Wl(),[S,v]=N.useState("list"),[b,E]=N.useState(null),[j,T]=N.useState(!1),[D,L]=N.useState(null),[I,P]=N.useState(null),[W,H]=N.useState(""),[R,U]=N.useState(""),[V,G]=N.useState(""),[Z,X]=N.useState("1.0.0"),[$,O]=N.useState("#3b82f6"),[M,q]=N.useState(""),[z,ee]=N.useState(50),[Q,ne]=N.useState(VS),[K,B]=N.useState({type:"always"}),[te,se]=N.useState(""),[xe,oe]=N.useState(!1),Oe=mt(Ce=>Ce.defaults),Me=mt(Ce=>Ce.userItems),ze=mt(Ce=>Ce.projectItems),$e=N.useMemo(()=>[...Oe,...Me,...ze],[Oe,Me,ze]),je=mt(Ce=>Ce.fetchAgents),[rt]=N.useState(null);N.useEffect(()=>{e&&(c(),p(),je(),L(null),P(null),n?r.some(Ne=>Ne.id===n)?h(n).then(Ne=>{Ne&&Qe({...Ne,metadata:{...Ne.metadata,name:Ne.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):d(n).then(Ne=>{Ne&&Qe(Ne,{editingId:n,isReadOnly:!1})}):(v("list"),E(null),T(!1)))},[e,c,d,h,p,n]);const Qe=(Ce,Ne)=>{H(Ce.metadata.name),U(Ce.metadata.id),G(Ce.metadata.description),X(Ce.metadata.version),O(Ce.metadata.color??"#3b82f6"),q(Ce.entryStep),ee(Ce.settings.maxIterations),ne(Ce.steps),B(Ce.startCondition??{type:"always"}),se(""),(Ne==null?void 0:Ne.editingId)!==void 0&&E(Ne.editingId),(Ne==null?void 0:Ne.isReadOnly)!==void 0&&T(Ne.isReadOnly),(Ne==null?void 0:Ne.selectedNodeKey)!==void 0&&L(null),(Ne==null?void 0:Ne.selectedEdgeKey)!==void 0&&P(null),v("edit")},fe=async Ce=>{const Ne=await d(Ce);Ne&&Qe(Ne,{editingId:Ce,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},ce=async()=>{var ot;const Ce=b??R;if(!Ce||!W)return se("Name is required."),!1;if(Q.length===0)return se("Add at least one step."),!1;let Ne=M;if(!Ne||!Q.some(nt=>nt.id===Ne)){if(Ne=((ot=Q.find(nt=>nt.id))==null?void 0:ot.id)??"",!Ne)return se("All steps need an ID."),!1;q(Ne)}oe(!0),se("");const Fe={metadata:{id:Ce,name:W,description:V,version:Z||"1.0.0",color:$},entryStep:Ne,settings:{maxIterations:z},steps:Q,startCondition:K},Ye=b?await x(b,Fe):await m(Fe);return oe(!1),Ye.success?(b||E(Ce),!0):(se(Ye.error??"Failed to save."),!1)},de=async()=>{await ce()},he=async()=>{await ce()&&(n?t():v("list"))},De=()=>{n?t():v("list")},Ue=Ce=>{H(Ce),b||U(E$(Ce))},re=async Ce=>r.some(Fe=>Fe.id===Ce)?await h(Ce):await d(Ce),_e=async Ce=>{const Ne=await re(Ce);Ne&&Qe({...Ne,metadata:{...Ne.metadata,name:Ne.metadata.name+" (copy)",id:`${Ce}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},Le=()=>{E(null),H(""),U(""),G(""),X("1.0.0"),O("#3b82f6"),q(""),ee(50),ne(structuredClone(VS)),B({type:"always"}),se(""),L(null),P(null),T(!1),v("edit")},He=async Ce=>{await y(Ce),C()},qe=N.useCallback(Ce=>{L(Ce),P(null)},[]),Ke=N.useCallback(Ce=>{P(Ce),L(null)},[]),tt=D!==null?Number(D):-1,_t=tt>=0?Q[tt]??null:null,It=N.useCallback(Ce=>{ne(Ne=>Ne.map((Fe,Ye)=>Ye===tt?Ce:Fe))},[tt]),Kt=K.type==="step_result"?`${K.result}`:K.type==="metadata_all_match"?`${K.key??"?"}=${K.value??"?"}`:K.type==="metadata_all_in"?`${K.key??"?"} in [${((vn=K.values)==null?void 0:vn.join(","))??"?"}]`:d2[K.type]??K.type,dt=()=>{const Ce=Q.length,Ne=j$(Q),Fe=$e.find(Ye=>!Ye.subagent);ne([...Q,{id:Ne,name:(Fe==null?void 0:Fe.name)??"Agent",type:"agent",phase:"build",agentId:(Fe==null?void 0:Fe.id)??"builder",transitions:[]}]),M||q(Ne),qe(String(Ce))},kn=N.useCallback((Ce,Ne)=>{Ce==="$start"?(q(Ne),Ke("start")):ne(Fe=>{const Ye=Fe.find(nt=>nt.id===Ce),ot=Ye?Ye.transitions.length:0;return Ke(`${Ce}:${ot}`),Fe.map(nt=>nt.id===Ce?{...nt,transitions:[...nt.transitions,{when:{type:"always"},goto:Ne}]}:nt)})},[Ke]),jt=Ce=>{if(Ce==="start")return null;const Ne=Ce.lastIndexOf(":"),Fe=Ce.slice(0,Ne),Ye=parseInt(Ce.slice(Ne+1));return{stepId:Fe,transIdx:Ye}},Jt=N.useCallback((Ce,Ne)=>{const Fe=jt(Ce);Fe&&ne(Ye=>Ye.map(ot=>ot.id===Fe.stepId?{...ot,transitions:ot.transitions.map((nt,xt)=>xt===Fe.transIdx?Ne(nt):nt)}:ot))},[]),Br=N.useCallback((Ce,Ne)=>{if(Ce==="start"){q(Ne);return}Jt(Ce,Fe=>({...Fe,goto:Ne}))},[Jt]),ve=N.useCallback((Ce,Ne)=>{const Fe=jt(Ce);Fe&&(ne(Ye=>{const ot=Ye.find(xt=>xt.id===Fe.stepId);if(!ot)return Ye;const nt=ot.transitions[Fe.transIdx];return nt?Ye.map(xt=>xt.id===Fe.stepId?{...xt,transitions:xt.transitions.filter((sn,Zt)=>Zt!==Fe.transIdx)}:xt.id===Ne?{...xt,transitions:[...xt.transitions,nt]}:xt):Ye}),P(null))},[]),Ve=N.useCallback(Ce=>{if(Ce==="start"){q(""),P(null);return}const Ne=jt(Ce);Ne&&(ne(Fe=>Fe.map(Ye=>Ye.id===Ne.stepId?{...Ye,transitions:Ye.transitions.filter((ot,nt)=>nt!==Ne.transIdx)}:Ye)),P(null))},[]),ae=N.useCallback((Ce,Ne)=>{if(Ce==="start"){B(Ne);return}Jt(Ce,Fe=>({...Fe,when:Ne}))},[Jt]),me=N.useCallback((Ce,Ne)=>{Ce!=="start"&&Jt(Ce,Fe=>({...Fe,subGroup:Ne||void 0}))},[Jt]),Ie=Ce=>ex(Ce,$e).name,gt=()=>{if(!I)return null;if(I==="start"){const sn=Q.find(Zt=>Zt.id===M);return{type:"start",fromLabel:"Start",toLabel:sn?Ie(sn):"(none)",condition:K}}const Ce=I.lastIndexOf(":"),Ne=I.slice(0,Ce),Fe=parseInt(I.slice(Ce+1)),Ye=Q.find(sn=>sn.id===Ne);if(!Ye)return null;const ot=Ye.transitions[Fe];if(!ot)return null;const nt=Q.find(sn=>sn.id===ot.goto),xt=ot.goto==="$done"?"Done":nt?Ie(nt):ot.goto;return{type:"step",fromLabel:Ie(Ye),toLabel:xt,condition:ot.when,subGroup:ot.subGroup}};if(S==="edit"){const Ce=gt();return i.jsxs(wt,{isOpen:e,onClose:De,title:j?W:b?"Edit Workflow":"New Workflow",size:"full",children:[te&&i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:te}),i.jsx(S$,{formName:W,formId:R,formDescription:V,formMaxIterations:z,formColor:$,isReadOnly:j,onNameChange:Ue,onDescriptionChange:G,onMaxIterationsChange:ee,onColorChange:O}),i.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[i.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[i.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!j&&i.jsx("button",{onClick:dt,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),i.jsxs("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:[i.jsx(_$,{steps:Q,entryStep:M,selectedNodeId:(_t==null?void 0:_t.id)??null,selectedEdgeKey:I,startConditionLabel:Kt,agentTypes:$e,isReadOnly:j,onSelectNode:Ne=>{if(Ne===null){qe(null);return}const Fe=Q.findIndex(Ye=>Ye.id===Ne);qe(Fe>=0?String(Fe):null)},onSelectEdge:Ke,onRemoveStep:Ne=>{var Ye;const Fe=Q.findIndex(ot=>ot.id===Ne);if(ne(ot=>ot.filter(nt=>nt.id!==Ne)),tt===Fe&&qe(null),M===Ne){const ot=Q.filter(nt=>nt.id!==Ne);q(((Ye=ot[0])==null?void 0:Ye.id)??"")}},onCreateTransition:kn,onReconnectTo:Br,onReconnectFrom:ve,onDeleteTransition:Ve}),Q.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[i.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),i.jsx("button",{onClick:dt,className:"px-3 py-1.5 rounded bg-accent-primary/10 text-accent-primary text-xs hover:bg-accent-primary/20",children:"+ Add your first step"})]})]})]}),i.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[i.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:i.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),i.jsx("div",{className:"p-3 overflow-y-auto flex-1 min-h-0",children:j&&(Ce||_t)?i.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):Ce?Ce.type==="start"?i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),M&&i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[i.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),i.jsx(_1,{}),i.jsx("span",{className:"text-text-primary font-medium",children:Ce.toLabel})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Activation Condition"}),i.jsx("select",{value:K.type,onChange:Ne=>B(Ne.target.value==="step_result"?{type:"step_result",result:"success"}:Ne.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:Ne.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:Ne.target.value}),className:FS,children:h2.map(Ne=>i.jsx("option",{value:Ne.value,children:Ne.label},Ne.value))})]}),K.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Result"}),M&&(()=>{const Ne=Q.find(nt=>nt.id===M),Fe=Ne&&(Ne.type==="sub_agent"||Ne.type==="agent")?$e.find(nt=>nt.id===(Ne.type==="sub_agent"?Ne.subAgentType:Ne.agentId)):void 0,Ye=(Fe==null?void 0:Fe.results)&&Fe.results.length>0,ot=(Fe==null?void 0:Fe.results)??[];return Ye?i.jsx("select",{value:K.result??ot[0],onChange:nt=>B({type:"step_result",result:nt.target.value}),className:FS,children:ot.map(nt=>i.jsx("option",{value:nt,children:nt},nt))}):i.jsx("input",{type:"text",value:K.result??"success",onChange:nt=>B({type:"step_result",result:nt.target.value}),placeholder:"e.g. success, passed, failed",className:vl})})()]}),(K.type==="metadata_all_match"||K.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Metadata Key"}),i.jsx("input",{type:"text",value:K.key??"",onChange:Ne=>B({...K,key:Ne.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:vl})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Field"}),i.jsx("input",{type:"text",value:K.field??"",onChange:Ne=>B({...K,field:Ne.target.value}),placeholder:"e.g. status",className:vl})]}),K.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Value"}),i.jsx("input",{type:"text",value:K.value??"",onChange:Ne=>B({...K,value:Ne.target.value}),placeholder:"e.g. passed, resolved",className:vl})]}):i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((rn=K.values)==null?void 0:rn.join(", "))??"",onChange:Ne=>B({...K,values:Ne.target.value.split(",").map(Fe=>Fe.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:vl})]})]}),i.jsx("p",{className:"text-text-muted text-[10px]",children:"Workflow only proceeds when this condition is met. Drag the target handle to change entry step."})]}):(()=>{const Ne=jt(I),Fe=Ne==null?void 0:Ne.stepId,Ye=(Ne==null?void 0:Ne.transIdx)??0,ot=Fe?Q.find(xt=>xt.id===Fe):void 0,nt=(ot==null?void 0:ot.transitions.length)??0;return i.jsx(k$,{fromLabel:Ce.fromLabel,toLabel:Ce.toLabel,condition:Ce.condition,subGroup:"subGroup"in Ce?Ce.subGroup:void 0,fromStep:Ce.type==="step"?Q.find(xt=>xt.id===Ce.fromLabel):void 0,agentTypes:$e,transitionIndex:Ye,totalTransitions:nt,onUpdateCondition:xt=>ae(I,xt),onUpdateSubGroup:xt=>me(I,xt),onDelete:()=>Ve(I),onMoveUp:()=>{ne(xt=>{const sn=xt.find(qt=>qt.id===Fe);if(!sn||Ye===0)return xt;const Zt=[...sn.transitions];return[Zt[Ye-1],Zt[Ye]]=[Zt[Ye],Zt[Ye-1]],xt.map(qt=>qt.id===Fe?{...qt,transitions:Zt}:qt)}),P(`${Fe}:${Ye-1}`)},onMoveDown:()=>{ne(xt=>{const sn=xt.find(qt=>qt.id===Fe);if(!sn||Ye===sn.transitions.length-1)return xt;const Zt=[...sn.transitions];return[Zt[Ye],Zt[Ye+1]]=[Zt[Ye+1],Zt[Ye]],xt.map(qt=>qt.id===Fe?{...qt,transitions:Zt}:qt)}),P(`${Fe}:${Ye+1}`)}})})():_t?i.jsx(C$,{step:_t,isEntry:_t.id===M,agentTypes:$e,transitionCount:_t.transitions.length,templateVariables:u,onUpdate:It,onRemove:()=>{var Ne;if(_t&&(ne(Q.filter((Fe,Ye)=>Ye!==tt)),qe(null),M===_t.id)){const Fe=Q.filter((Ye,ot)=>ot!==tt);q(((Ne=Fe[0])==null?void 0:Ne.id)??"")}},onSetEntry:()=>q(_t.id)}):i.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",i.jsx("br",{}),"Drag from a port to connect."]})})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border",children:[i.jsx(Ze,{variant:"secondary",onClick:De,children:"Close"}),j?i.jsx(Ze,{variant:"primary",onClick:()=>{H(W+" (copy)"),U(`${b}-copy-${Date.now()}`),E(null),T(!1)},children:"Duplicate & Customize"}):i.jsxs(i.Fragment,{children:[i.jsx(Ze,{variant:"primary",onClick:de,children:"Save"}),i.jsx(Ze,{variant:"primary",onClick:he,children:"Save & Close"})]})]})]})}return i.jsx(wt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:i.jsx(D1,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:Le,loading:l,hasItems:r.length>0||a.length>0,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(HS,{title:"Built-in",items:r,renderActions:Ce=>i.jsx(i.Fragment,{children:i.jsx(qi,{onClick:()=>_e(Ce.id),children:i.jsx(eg,{})})})}),i.jsx(HS,{title:"Custom",items:a,renderActions:Ce=>i.jsxs(i.Fragment,{children:[i.jsx(qi,{onClick:()=>fe(Ce.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Ku,{onClick:()=>_e(Ce.id)}),_(Ce.id,"delete")?i.jsx(ig,{onConfirm:()=>He(Ce.id),onCancel:C}):i.jsx(ag,{onClick:()=>w(Ce.id)})]})})]})})})}function N$(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function T$({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:r,onSelectWorkflow:a,onCloseCompleteAction:l,textareaContent:u,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:h}){const[,p]=Ln(),m=mn(z=>z.fetchCommands),x=Ot(z=>z.fetchWorkflows),y=mt(z=>z.fetchAgents),w=mn(z=>z.defaults),C=mn(z=>z.userItems),_=mn(z=>z.projectItems),S=Ot(z=>z.defaults),v=Ot(z=>z.userItems),b=Ot(z=>z.projectItems),E=mt(z=>z.defaults),j=mt(z=>z.userItems),T=mt(z=>z.projectItems),D=Re(z=>{var ee;return(ee=z.currentSession)==null?void 0:ee.mode}),L=Re(z=>{var ee;return((ee=z.currentSession)==null?void 0:ee.dangerLevel)??"normal"}),I=Re(z=>z.switchMode),P=Re(z=>z.switchDangerLevel),W=Re(z=>{var ee;return(ee=z.currentSession)==null?void 0:ee.projectId}),H=N.useRef(void 0),[R,U]=N.useState(""),[V,G]=N.useState(0),Z=N.useRef(null),X=N.useRef(!1);N.useEffect(()=>{e&&(X.current=!0)},[e]),N.useEffect(()=>{if(e){m(),x(),y(),U(""),G(0);const z=setTimeout(()=>{var ee;return(ee=Z.current)==null?void 0:ee.focus()},50);return()=>clearTimeout(z)}},[e,m,x,y]),N.useEffect(()=>{var z;!e&&X.current&&(n==null||n(),(z=H.current)==null||z.call(H),H.current=void 0)},[e,n]);const O=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const z=W??N$(window.location.pathname);z&&p(`/p/${z}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{H.current=l,t()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{t(),c==null||c()}},{id:"toggle-autoscroll",name:h?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{t(),d==null||d(!h)}},...Kr(Kr(E,j),T).filter(z=>!z.subagent&&z.id!==D).map(z=>({id:z.id,name:z.name,prefix:"Agent > Switch to",action:()=>I(z.id)})),...Kr(Kr(w,C),_).map(z=>({id:z.id,name:z.name,prefix:"Command > Launch",action:()=>r(z.id,u)})),...Kr(Kr(S,v),b).map(z=>({id:z.id,name:z.name,prefix:"Workflow > Run",action:()=>a(z.id)})),...["normal","dangerous"].filter(z=>z!==L).map(z=>({id:z,name:z.charAt(0).toUpperCase()+z.slice(1),prefix:"Mode > Switch to",action:()=>P(z)}))].filter(z=>ai(`${z.prefix} ${z.name}`,R)),M=O.length-1,q=z=>{Ok(z,M,G,()=>{var ee;(ee=O[V])==null||ee.action(),t()},t)};return e?di.createPortal(i.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),i.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[i.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[i.jsx("input",{ref:Z,type:"text",value:R,onChange:z=>{U(z.target.value),G(0)},onKeyDown:q,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx(sg,{onClick:t,className:"shrink-0","aria-label":"Close"})]}),i.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:O.length===0?i.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:w.length+C.length+S.length+v.length>0?"No matches":"No agents, commands, or workflows yet"}):O.map((z,ee)=>i.jsxs("button",{type:"button",onClick:()=>{z.action(),t()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${ee===V?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:[i.jsxs("span",{className:"text-text-muted font-normal",children:[z.prefix," "]}),i.jsx("span",{children:z.name})]},z.id))})]})]}),document.body):null}const m2="openfox-message-search-filters",A$=[{key:"user",label:"User prompts"},{key:"thinking",label:"Thinking"},{key:"response",label:"Responses"}];function L$(){try{const e=localStorage.getItem(m2);if(e){const t=JSON.parse(e);return new Set(t)}}catch{}return new Set(["user","thinking","response"])}function D$(e){localStorage.setItem(m2,JSON.stringify([...e]))}function R$(e){var n,r;if(e.type!=="message")return null;const t=e.message;if(t.role==="user")return"user";if(t.role==="assistant"){if((n=t.content)!=null&&n.trim())return"response";if((r=t.thinkingContent)!=null&&r.trim())return"thinking"}return null}function O$(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear())return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),u=String(t.getDate()).padStart(2,"0"),c=String(t.getHours()).padStart(2,"0"),d=String(t.getMinutes()).padStart(2,"0");return`${a}/${l}/${u} ${c}:${d}`}function I$(e){var t;if(e.type==="message")return e.message.timestamp;if(e.type==="subagent")return(t=e.messages[0])==null?void 0:t.timestamp}function M$(e){var t,n;if(e.type==="message"){const r=e.message;if(r.role==="assistant"){const a=(t=r.content)==null?void 0:t.trim();return((n=r.thinkingContent)==null?void 0:n.trim())&&!a?"italic text-text-muted":""}if(r.role==="user")return"font-bold"}return""}function P$(e){var n,r;if(e.type!=="message")return i.jsx(N_,{className:"w-3.5 h-3.5"});const t=e.message;return t.role==="assistant"?(n=t.thinkingContent)!=null&&n.trim()&&!((r=t.content)!=null&&r.trim())?i.jsx(mT,{className:"w-3.5 h-3.5"}):i.jsx(N_,{className:"w-3.5 h-3.5"}):i.jsx(fT,{className:"w-3.5 h-3.5"})}function GS(e){var t;if(e.type==="message"){const n=e.message,r=n.content||"",a=r.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(n.messageKind==="workflow-started")try{return`Workflow: ${JSON.parse(r).workflowName}`}catch{return"Workflow started"}if(n.messageKind==="task-completed")return"Task completed";if(n.messageKind==="auto-prompt")return"Auto-prompt";if(n.messageKind==="correction")return"Correction";if(n.messageKind==="context-reset")return"Context reset";if(n.messageKind==="command")return"Command executed";if(n.role==="assistant")return a?a.slice(0,200):(t=n.thinkingContent)!=null&&t.trim()?n.thinkingContent.slice(0,200):"";const l=a.slice(0,200);return l.length<a.length?`${l}...`:l}return e.type==="subagent"?`Sub-agent: ${e.subAgentType}`:""}function B$({isOpen:e,onClose:t,displayItems:n,onNavigate:r}){const[a,l]=N.useState(""),[u,c]=N.useState(0),[d,h]=N.useState(L$),p=N.useRef(null),m=N.useRef(null),x=N.useRef(null),y=j=>{h(T=>{const D=new Set(T);return D.has(j)?D.delete(j):D.add(j),D$(D),D})},w=N.useMemo(()=>n.filter(j=>{var T,D;return!(j.type==="context-divider"||j.type==="message"&&(j.message.messageKind==="auto-prompt"||j.message.role==="assistant"&&!((T=j.message.content)!=null&&T.trim())&&!((D=j.message.thinkingContent)!=null&&D.trim())))}),[n]),C=N.useMemo(()=>w.filter(j=>{const T=R$(j);return!(T&&!d.has(T))}),[w,d]),_=N.useMemo(()=>a?w.filter(j=>{const T=GS(j);return ai(T,a)}):C,[C,a]),S=_.length-1;N.useEffect(()=>{if(e){l(""),c(0);const j=setTimeout(()=>{var T;return(T=p.current)==null?void 0:T.focus()},50);return()=>clearTimeout(j)}},[e]),N.useEffect(()=>{e&&m.current&&(m.current.scrollTop=m.current.scrollHeight)},[e]),N.useEffect(()=>{x.current&&x.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[u]);const v=j=>{Ok(j,S,c,()=>{const T=_[u];if(T){const D=n.indexOf(T);D>=0&&r(D),t()}},t)},b=j=>{const T=n.indexOf(j);T>=0&&r(T),t()},E=j=>n.indexOf(j);return e?di.createPortal(i.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),i.jsxs("div",{className:"relative w-full max-w-lg bg-bg-secondary border border-border rounded shadow-xl",children:[i.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[i.jsx(Wi,{}),i.jsx("input",{ref:p,type:"text",value:a,onChange:j=>{l(j.target.value),c(0)},onKeyDown:v,placeholder:"Search timeline...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx("button",{type:"button",onClick:t,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:i.jsx(js,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"flex gap-1.5 px-4 py-2 border-b border-border",children:A$.map(j=>{const T=d.has(j.key);return i.jsx("button",{type:"button",onClick:()=>y(j.key),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${T?"bg-accent-primary/20 text-accent-primary border border-accent-primary/40":"bg-bg-tertiary text-text-muted border border-border hover:text-text-secondary"}`,children:j.label},j.key)})}),i.jsx("div",{ref:m,className:"overflow-y-auto max-h-[60vh] p-2",children:_.length===0?i.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:C.length>0?"No matches":"No messages yet"}):_.map((j,T)=>{const D=E(j),L=P$(j),I=GS(j),P=M$(j),W=I$(j),H=j.type==="message"&&j.message.role==="user";return i.jsx("button",{ref:T===u?x:null,type:"button",onClick:()=>b(j),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${T===u?"bg-accent-primary/20 text-text-primary":H?"bg-accent-primary/5 text-text-secondary hover:bg-accent-primary/10 hover:text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[i.jsx("span",{className:"flex-shrink-0",children:L}),i.jsx("span",{className:`truncate flex-1 ${P}`,children:I})]}),W&&i.jsx("span",{className:"text-text-muted text-xs shrink-0",children:O$(W)})]})},`${D}-${j.type}`)})})]})]}),document.body):null}function $$({attachment:e,onRemove:t}){const n=o2(e.filename);return i.jsxs("div",{className:"relative inline-flex flex-col items-center p-2 bg-bg-tertiary rounded-lg border border-border",children:[i.jsx(ec,{onClick:()=>t(e.id),className:"absolute -top-2 -right-2",size:"sm",variant:"overlay","aria-label":`Remove ${e.filename}`}),a2(e.mimeType)?i.jsx("img",{src:e.data,alt:e.description||e.filename,className:"w-16 h-16 object-cover rounded-md bg-bg-secondary"}):i.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-md bg-bg-secondary text-xs font-bold text-text-muted",children:n}),i.jsx("div",{className:"mt-1 text-xs text-text-muted text-center max-w-16 truncate",title:e.filename,children:e.filename}),i.jsx("div",{className:"text-[10px] text-text-muted",children:Xa(e.size)})]})}function z$({history:e,selectedIndex:t,onSelect:n,onEscape:r,onNavigate:a}){const l=N.useRef(null),u=N.useRef(null);N.useEffect(()=>{u.current&&l.current&&u.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[t]);const c=h=>{switch(h.key){case"Enter":h.preventDefault(),e[t]&&n(e[t].content);break;case"Escape":h.preventDefault(),r();break;case"ArrowUp":h.preventDefault(),a("up");break;case"ArrowDown":h.preventDefault(),a("down");break}},d=h=>{n(h)};return i.jsx("div",{ref:l,role:"list",className:"mb-2 p-2 bg-bg-secondary border border-border rounded-lg overflow-y-auto max-h-64",onKeyDown:c,children:e.map((h,p)=>i.jsxs("div",{ref:p===t?u:null,role:"listitem",onClick:()=>d(h.content),className:`
308
+ `,children:n?"Reconnecting...":"Reconnect"})]})}const mn=Mn((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchCommands:async()=>{await Sk("/api/commands",e,!0)},fetchCommand:async n=>{try{const r=await Se(`/api/commands/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await Se(`/api/commands/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createCommand:async(n,r)=>{const a=await ui("POST","/api/commands",{...n,destination:r});return a.success&&await t().fetchCommands(),a},updateCommand:async(n,r)=>{const a=await ui("PUT",`/api/commands/${n}`,r);return a.success&&await t().fetchCommands(),a},deleteCommand:async n=>{try{const r=await Se(`/api/commands/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async(n,r)=>vd(`/api/commands/${n}/duplicate`,()=>t().fetchCommands(),r)}));function x$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function y$({onClick:e}){return i.jsx("button",{type:"button",onClick:e,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:i.jsx(eg,{})})}function u2({isOpen:e,onClose:t,initialEditId:n}){const r=mn(fe=>fe.defaults),a=mn(fe=>fe.userItems),l=mn(fe=>fe.projectItems),u=mn(fe=>fe.loading),c=mn(fe=>fe.fetchCommands),d=mn(fe=>fe.fetchCommand),h=mn(fe=>fe.fetchDefaultContent),p=mn(fe=>fe.createCommand),m=mn(fe=>fe.updateCommand),x=mn(fe=>fe.deleteCommand),[y,w]=N.useState(null),[C,_]=N.useState(null),{view:S,editingId:v,formError:b,saving:E,formData:j,setView:T,setEditingId:D,setFormError:L,setFormData:I,setSaving:P}=M1(),{requestDelete:W,clearConfirm:H,isConfirming:R}=Wl(),U=N.useRef(!1),V=mt(fe=>fe.defaults),G=mt(fe=>fe.userItems),Z=mt(fe=>fe.fetchAgents),$=[...V,...G].filter(fe=>!fe.subagent),O=N.useRef(c),M=N.useRef(Z),q=N.useRef(d),z=N.useRef(h),ee=N.useRef(n),Q=N.useRef(T),ne=N.useRef(D),K=N.useRef(L),B=N.useRef(H);N.useEffect(()=>{O.current=c,M.current=Z,q.current=d,z.current=h,ee.current=n,Q.current=T,ne.current=D,K.current=L,B.current=H}),N.useEffect(()=>{if(e)if(O.current(),M.current(),U.current||(B.current(),U.current=!0),ee.current){const fe=r.some(ce=>ce.id===ee.current);Q.current("edit"),ne.current(ee.current),K.current(""),fe?z.current(ee.current).then(ce=>{ce&&I({name:ce.metadata.name+" (copy)",id:`${ee.current}-copy-${Date.now()}`,prompt:ce.prompt,agentMode:ce.metadata.agentMode??"",isDefault:!0,destination:"user"})}):q.current(ee.current).then(ce=>{ce&&I({name:ce.metadata.name,id:ce.metadata.id,prompt:ce.prompt,agentMode:ce.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else Q.current("list"),ne.current(null);else U.current=!1},[e]);const te=async fe=>{w(fe);const ce=await h(fe);_((ce==null?void 0:ce.prompt)??null)},se=async fe=>{if(r.some(de=>de.id===fe)){const de=await h(fe);de&&(D(null),I({name:`${de.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:de.prompt,agentMode:de.metadata.agentMode??"",isDefault:!0,destination:"user"}),L(""),T("edit"))}else{const de=await d(fe);de&&(D(null),I({name:`${de.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:de.prompt,agentMode:de.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))}},xe=()=>{I({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),D(null),T("edit")},oe=async fe=>{const ce=await d(fe);ce&&(D(fe),I({name:ce.metadata.name,id:ce.metadata.id,prompt:ce.prompt,agentMode:ce.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))},Oe=async fe=>{await x(fe),H()},Me=async()=>{const fe=v??j.id;if(!fe||!j.name||!j.prompt){L("Name and message are required.");return}P(!0),L("");const ce={metadata:{id:fe,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},de=v?await m(v,ce):await p(ce,j.destination);if(P(!1),!de.success){L(de.error??"Failed to save command.");return}n?t():T("list")},ze=()=>{n?t():(T("list"),w(null),_(null))},$e=fe=>{I(ce=>({...ce,name:fe})),(!v||j.isDefault)&&I(ce=>({...ce,id:x$(fe)}))},je=()=>{w(null),_(null),T("list")},rt=()=>{y&&(w(null),T("edit"),D(y),h(y).then(fe=>{fe&&I({name:`${fe.metadata.name} (copy)`,id:`${y}-copy-${Date.now()}`,prompt:fe.prompt,agentMode:fe.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(y){const fe=r.find(ce=>ce.id===y);return i.jsx(wt,{isOpen:e,onClose:je,title:`Default: ${(fe==null?void 0:fe.name)??y}`,size:"xl",children:i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[i.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),i.jsx("span",{className:"font-mono",children:y})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),i.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:fe==null?void 0:fe.name})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),i.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(fe==null?void 0:fe.agentMode)||"None"})]})]}),i.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),i.jsx("textarea",{value:C??"",readOnly:!0,placeholder:"...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none opacity-60"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[i.jsx(Ze,{variant:"secondary",onClick:je,children:"Close"}),i.jsx(Ze,{variant:"primary",onClick:rt,children:"Duplicate & Customize"})]})]})})}if(S==="edit")return i.jsx(wt,{isOpen:e,onClose:ze,title:v?"Edit Command":"New Command",size:"xl",children:i.jsxs("div",{className:"flex flex-col h-full",children:[b&&i.jsx(Qa,{message:b}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(I1,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!j.isDefault,onNameChange:$e,onIdChange:fe=>I(ce=>({...ce,id:fe}))}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsxs("select",{value:j.agentMode,onChange:fe=>I(ce=>({...ce,agentMode:fe.target.value})),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[i.jsx("option",{value:"",children:"None (keep current mode)"}),$.map(fe=>i.jsx("option",{value:fe.id,children:fe.name},fe.id))]})]}),!v&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Save to:"}),i.jsxs("select",{value:j.destination,onChange:fe=>I(ce=>({...ce,destination:fe.target.value})),className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[i.jsx("option",{value:"user",children:"Global config"}),i.jsx("option",{value:"project",children:"Project (.openfox/)"})]})]})]}),i.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),i.jsx("textarea",{value:j.prompt,onChange:fe=>I(ce=>({...ce,prompt:fe.target.value})),placeholder:"The message that will be sent when this command is triggered...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[i.jsx(Ze,{variant:"secondary",onClick:ze,children:"Cancel"}),i.jsx(Ze,{variant:"primary",onClick:Me,disabled:E||!j.name||!j.prompt,children:E?"Saving...":"Save"})]})]})});const Qe=fe=>fe.map(ce=>i.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[i.jsx("div",{className:"min-w-0 flex-1 mr-3",children:i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("span",{className:"text-text-primary text-sm font-medium",children:ce.name})})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(qi,{onClick:()=>oe(ce.id)}),i.jsx(Ku,{onClick:()=>se(ce.id)}),R(ce.id,"delete")?i.jsx(ig,{onConfirm:()=>Oe(ce.id),onCancel:H}):i.jsx(ag,{onClick:()=>W(ce.id)})]})]},ce.id));return i.jsxs(wt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[i.jsx(O1,{description:"Commands are pre-defined messages you can send with a single click.",onNew:xe}),i.jsxs(og,{loading:u,hasItems:r.length>0||a.length>0||l.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[r.length>0&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),i.jsx("div",{className:"space-y-2",children:r.map(fe=>i.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[i.jsx("div",{className:"min-w-0 flex-1 mr-3",children:i.jsx("span",{className:"text-text-primary text-sm font-medium",children:fe.name})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(y$,{onClick:()=>te(fe.id)}),i.jsx(Ku,{onClick:()=>se(fe.id)})]})]},fe.id))})]}),a.length>0&&i.jsx(R1,{children:Qe(a)}),l.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),i.jsx("div",{className:"space-y-2",children:Qe(l)})]})]})]})}const Oi=150,bs=54,Iu=80,Lr=30,Ua=70,$S=100,Ii=50,Mu=50,zS=4,d2={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},h2=[{value:"step_result",label:"Step result is..."},{value:"metadata_all_match",label:"Metadata all match (key=value)"},{value:"metadata_all_in",label:"Metadata all in list"},{value:"always",label:"Always (fallback)"}],b$=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}];function ex(e,t){if(e.type==="agent"){const n=t.find(r=>r.id===e.agentId);return{name:(n==null?void 0:n.name)??(e.agentId||"Agent"),color:(n==null?void 0:n.color)||"#3b82f6"}}if(e.type==="sub_agent"){const n=t.find(r=>r.id===e.subAgentType);return{name:(n==null?void 0:n.name)??(e.subAgentType||"Sub-Agent"),color:(n==null?void 0:n.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function v$(e,t,n,r){const a=Mu+Ii+Oi+$S+Oi+Ii+Mu,l=a/2,u=Mu+Ii+Oi/2,c=Mu+Ii+Oi+$S+Oi/2,d=[],h=[],p=new Map,m=e.filter(V=>V.type==="agent"||V.type==="shell"),x=e.filter(V=>V.type==="sub_agent"),y=x.length>0,w=y?u:l,C=m.length>0?c:l,_=Ii+Lr/2;d.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:_,w:Iu,h:Lr}),p.set("$start",{cx:w,cy:_,w:Iu,h:Lr});const S=V=>{d.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:V,w:Iu,h:Lr}),p.set("$done",{cx:w,cy:V,w:Iu,h:Lr})};if(e.length===0){const V=_+Lr/2+Ua*2+Lr/2;return S(V),{nodes:d,edges:h,width:a,height:V+Lr/2+Ii,posMap:p}}const v=_+Lr/2+Ua,b=(V,G)=>{V.forEach((Z,X)=>{const $=v+X*(bs+Ua)+bs/2,{name:O,color:M}=ex(Z,r);d.push({id:Z.id,type:"step",label:O,color:M,cx:G,cy:$,w:Oi,h:bs}),p.set(Z.id,{cx:G,cy:$,w:Oi,h:bs})})};b(m,w),b(x,C);const E=m.length>0?v+(m.length-1)*(bs+Ua)+bs/2:_,j=y?v+(x.length-1)*(bs+Ua)+bs/2:_,T=Math.max(E,j)+bs/2+Ua+Lr/2;S(T);const D=[];t&&p.has(t)&&D.push({from:"$start",to:t,label:n,edgeKey:"start",direction:"down",backEdgeIndex:0});let L=0;for(const V of e)V.transitions.forEach((G,Z)=>{var z;if(!G.goto||!p.has(G.goto))return;const X=p.get(V.id),$=p.get(G.goto),O=G.when.type==="step_result"?`${G.when.result}`:G.when.type==="metadata_all_match"?`${G.when.key??"?"}=${G.when.value??"?"}`:G.when.type==="metadata_all_in"?`${G.when.key??"?"} in [${((z=G.when.values)==null?void 0:z.join(","))??"?"}]`:d2[G.when.type]??G.when.type,M=V.id===G.goto;let q;M?q="back":$.cy>X.cy+1?q="down":$.cy<X.cy-1?q="back":q="same",D.push({from:V.id,to:G.goto,label:O,edgeKey:`${V.id}:${Z}`,direction:q,backEdgeIndex:q==="back"?L++:0})});const I=new Map,P=new Map,W=new Map,H=new Map;for(const V of D)V.direction==="down"&&(I.set(V.from,(I.get(V.from)??0)+1),P.set(V.to,(P.get(V.to)??0)+1));const R=new Map,U=new Map;for(const V of D){if(V.direction!=="same")continue;const G=[V.from,V.to].sort().join("|");R.set(G,(R.get(G)??0)+1)}for(const V of D){if(V.direction==="back"||V.direction==="same"){let q=0;if(V.direction==="same"){const z=[V.from,V.to].sort().join("|");q=U.get(z)??0,U.set(z,q+1)}h.push({...V,fromPort:0,toPort:0,sameEdgeIndex:q});continue}const G=I.get(V.from)??1,Z=P.get(V.to)??1,X=W.get(V.from)??0,$=H.get(V.to)??0;W.set(V.from,X+1),H.set(V.to,$+1);const O=G===1?0:-.6+1.2*X/(G-1),M=Z===1?0:-.6+1.2*$/(Z-1);h.push({...V,fromPort:O,toPort:M,sameEdgeIndex:0})}return{nodes:d,edges:h,width:a,height:T+Lr/2+Ii,posMap:p}}function _$({steps:e,entryStep:t,selectedNodeId:n,selectedEdgeKey:r,startConditionLabel:a,agentTypes:l,isReadOnly:u,onSelectNode:c,onSelectEdge:d,onRemoveStep:h,onCreateTransition:p,onReconnectTo:m,onReconnectFrom:x,onDeleteTransition:y}){const w=N.useRef(null),C=N.useRef(!1),[_,S]=N.useState(null),[v,b]=N.useState(null),[E,j]=N.useState(null),{nodes:T,edges:D,width:L,height:I,posMap:P}=N.useMemo(()=>v$(e,t,a,l),[e,t,a,l]),W=N.useCallback(Q=>{var se;const ne=w.current;if(!ne)return{x:0,y:0};const K=ne.createSVGPoint();K.x=Q.clientX,K.y=Q.clientY;const B=(se=ne.getScreenCTM())==null?void 0:se.inverse();if(!B)return{x:0,y:0};const te=K.matrixTransform(B);return{x:te.x,y:te.y}},[]),H=N.useCallback(Q=>!Q||!v||Q==="$start"?!1:v.type==="reconnect-from"?Q!=="$done":!0,[v]),R=N.useCallback((Q,ne)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const K=W(Q);b({type:"new",fromNodeId:ne,mouseX:K.x,mouseY:K.y})},[W,u]),U=N.useCallback((Q,ne)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const K=W(Q);b({type:"reconnect-to",fromNodeId:ne.from,edgeKey:ne.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),V=N.useCallback((Q,ne)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const K=W(Q);b({type:"reconnect-from",fromNodeId:ne.from,fixedTargetId:ne.to,edgeKey:ne.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),G=N.useCallback(Q=>{if(!v)return;const ne=W(Q);b(K=>K?{...K,mouseX:ne.x,mouseY:ne.y}:null)},[v,W]),Z=N.useCallback(()=>{v&&(C.current=!0,E&&H(E)&&(v.type==="new"?p(v.fromNodeId,E):v.type==="reconnect-to"?m(v.edgeKey,E):v.type==="reconnect-from"&&x(v.edgeKey,E)),b(null),j(null))},[v,E,H,p,m,x]),X=N.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);N.useEffect(()=>{if(u)return;const Q=ne=>{ne.target instanceof HTMLInputElement||ne.target instanceof HTMLTextAreaElement||ne.target instanceof HTMLSelectElement||(ne.key==="Delete"||ne.key==="Backspace")&&r&&r!=="start"&&(ne.preventDefault(),y(r),d(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[u,r,y,d]);const $=Q=>{const ne=P.get(Q.from),K=P.get(Q.to);if(!ne||!K)return null;let B,te,se,xe="middle",oe,Oe;if(Q.direction==="down"){const Me=ne.cx+Q.fromPort*(ne.w/2-10),ze=ne.cy+ne.h/2,$e=K.cx+Q.toPort*(K.w/2-10),je=K.cy-K.h/2,rt=je-ze,Qe=$e-Me;B=`M ${Me} ${ze} C ${Me} ${ze+rt*.4}, ${$e-Qe*.2} ${je-rt*.1}, ${$e} ${je}`,te=Me+($e-Me)*.5,se=ze+rt*.6,oe={x:Me,y:ze},Oe={x:$e,y:je}}else if(Q.direction==="back"){const Me=Q.from===Q.to,ze=ne.cx>=L/2,$e=Q.backEdgeIndex*16,je=ze?L-20-$e:20+$e;if(Me){const rt=ne.cx>=L/2,Qe=30+Q.backEdgeIndex*14,fe=ne.cy-ne.h/2,ce=rt?ne.cx+ne.w/2:ne.cx-ne.w/2,de=rt?ce+Qe:ce-Qe,he=ne.cx+(rt?ne.w/4:-ne.w/4),De=fe-20-Q.backEdgeIndex*10;B=`M ${ce} ${ne.cy} C ${de} ${ne.cy}, ${de} ${De}, ${he} ${fe}`,te=de+10,se=De+4,xe="middle",oe={x:ce,y:ne.cy},Oe={x:he,y:fe}}else{const rt=ze?ne.cx+ne.w/2:ne.cx-ne.w/2,Qe=K.cx+(ze?K.w/4:-K.w/4),fe=Math.min(ne.cy,K.cy)-K.h/2-18-Q.backEdgeIndex*14;B=`M ${rt} ${ne.cy} L ${je} ${ne.cy} L ${je} ${fe} L ${Qe} ${fe} L ${Qe} ${K.cy-K.h/2}`,te=je,se=(ne.cy+fe)/2,xe=ze?"start":"end",oe={x:rt,y:ne.cy},Oe={x:Qe,y:K.cy-K.h/2}}}else{const Me=K.cx>ne.cx,ze=Q.sameEdgeIndex===0?-12:12,$e=Me?ne.cx+ne.w/2:ne.cx-ne.w/2,je=Me?K.cx-K.w/2:K.cx+K.w/2,rt=ne.cy+ze,Qe=K.cy+ze,fe=($e+je)/2;B=`M ${$e} ${rt} C ${fe} ${rt}, ${fe} ${Qe}, ${je} ${Qe}`,te=fe,se=(rt+Qe)/2-6,oe={x:$e,y:rt},Oe={x:je,y:Qe}}return{path:B,labelX:te,labelY:se,labelAnchor:xe,fromPt:oe,toPt:Oe}},O=(Q,ne)=>{const K=$(Q);if(!K)return null;const{path:B,labelX:te,labelY:se,labelAnchor:xe}=K,oe=r===Q.edgeKey,Oe=Q.label&&Q.label!=="otherwise";return i.jsxs("g",{children:[i.jsx("path",{d:B,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Me=>{Me.stopPropagation(),u||d(oe?null:Q.edgeKey)}}),i.jsx("path",{d:B,fill:"none",stroke:oe?"#58a6ff":"#484f58",strokeWidth:oe?2.2:1.2,markerEnd:oe?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Oe&&i.jsx("text",{x:te+(xe==="start"?5:xe==="end"?-5:0),y:se+3,textAnchor:xe,className:"text-[8px]",fill:oe?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Q.label})]},ne)},M=()=>{if(!r||v)return null;const Q=D.find(se=>se.edgeKey===r);if(!Q)return null;const ne=$(Q);if(!ne)return null;const{fromPt:K,toPt:B}=ne,te=6;return i.jsxs(i.Fragment,{children:[Q.edgeKey!=="start"&&i.jsx("circle",{cx:K.x,cy:K.y,r:te,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:se=>V(se,Q)}),i.jsx("circle",{cx:B.x,cy:B.y,r:te,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:se=>U(se,Q)})]})},q=()=>{if(!v)return null;let Q,ne,K,B;if(v.type==="reconnect-from"){const xe=P.get(v.fixedTargetId);if(!xe)return null;Q=v.mouseX,ne=v.mouseY,K=xe.cx,B=xe.cy-xe.h/2}else{const xe=P.get(v.fromNodeId);if(!xe)return null;Q=xe.cx,ne=xe.cy+xe.h/2,K=v.mouseX,B=v.mouseY}const te=B-ne,se=Math.abs(te)>10?`M ${Q} ${ne} C ${Q} ${ne+te*.4}, ${K} ${B-te*.4}, ${K} ${B}`:`M ${Q} ${ne} L ${K} ${B}`;return i.jsx("path",{d:se,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},z=Q=>{const ne=Q.cy+Q.h/2,K=(v==null?void 0:v.fromNodeId)===Q.id;return i.jsx("circle",{cx:Q.cx,cy:ne,r:zS,fill:K?"#58a6ff":"#1c2128",stroke:K?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5,className:"cursor-crosshair",onMouseDown:B=>R(B,Q.id)})},ee=Q=>{const ne=Q.cy-Q.h/2,K=v&&E===Q.id&&H(Q.id);return i.jsx("circle",{cx:Q.cx,cy:ne,r:zS,fill:K?"#3fb950":"#1c2128",stroke:K?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5})};return i.jsxs("svg",{ref:w,viewBox:`0 0 ${L} ${I}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:G,onMouseUp:Z,onClick:X,children:[i.jsxs("defs",{children:[i.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:i.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),i.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:i.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),D.map((Q,ne)=>O(Q,ne)),T.map(Q=>{const ne=n===Q.id,K=Q.cx-Q.w/2,B=Q.cy-Q.h/2,te=_===Q.id,se=v&&E===Q.id&&H(Q.id);if(Q.type==="terminal"){const oe=Q.id==="$start",Oe=oe?"#58a6ff":"#3fb950",Me=oe,ze=!oe;return i.jsxs("g",{onClick:$e=>{$e.stopPropagation(),oe&&!u&&d("start")},className:oe&&!u?"cursor-pointer":void 0,children:[se&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),oe&&r==="start"&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:B,width:Q.w,height:Q.h,rx:Q.h/2,fill:Oe,fillOpacity:.08,stroke:Oe,strokeOpacity:.4,strokeWidth:1.5}),i.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Oe,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),Me&&z(Q),ze&&ee(Q)]},Q.id)}const xe=Q.color??"#6b7280";return i.jsxs("g",{onClick:oe=>{oe.stopPropagation(),u||c(ne?null:Q.id)},onMouseEnter:()=>S(Q.id),onMouseLeave:()=>S(null),className:u?void 0:"cursor-pointer",children:[se&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ne&&i.jsx("rect",{x:K-3,y:B-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:B,width:Q.w,height:Q.h,rx:10,fill:xe,fillOpacity:.08,stroke:xe,strokeOpacity:.6,strokeWidth:ne?2:1.5}),i.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:Q.label}),!u&&z(Q),!u&&ee(Q),te&&!v&&!u&&i.jsxs("g",{onClick:oe=>{oe.stopPropagation(),h(Q.id)},className:"cursor-pointer",children:[i.jsx("circle",{cx:K+Q.w-2,cy:B+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),i.jsx("line",{x1:K+Q.w-5,y1:B-1,x2:K+Q.w+1,y2:B+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),i.jsx("line",{x1:K+Q.w+1,y1:B-1,x2:K+Q.w-5,y2:B+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),v&&T.map(Q=>H(Q.id)?i.jsx("rect",{x:Q.cx-Q.w/2-8,y:Q.cy-Q.h/2-8,width:Q.w+16,height:Q.h+16,fill:"transparent",rx:12,onMouseEnter:()=>j(Q.id),onMouseLeave:()=>j(null),onMouseUp:ne=>{ne.stopPropagation(),Z()}},`drop-${Q.id}`):null),q(),M()]})}const Pu="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",bl="block text-[11px] text-text-secondary mb-0.5";function S$({formName:e,formId:t,formDescription:n,formMaxIterations:r,formColor:a,isReadOnly:l,onNameChange:u,onDescriptionChange:c,onMaxIterationsChange:d,onColorChange:h}){return i.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[i.jsxs("div",{className:"min-w-[140px]",children:[i.jsx("label",{className:bl,children:"Name"}),i.jsx("input",{value:e,onChange:p=>u(p.target.value),placeholder:"Workflow name",className:`${Pu} ${l?"opacity-50":""}`,readOnly:l})]}),i.jsxs("div",{className:"min-w-[100px]",children:[i.jsx("label",{className:bl,children:"ID"}),i.jsx("input",{value:t,readOnly:!0,className:`${Pu} font-mono opacity-50`})]}),i.jsxs("div",{className:"flex-1 min-w-[140px]",children:[i.jsx("label",{className:bl,children:"Description"}),i.jsx("input",{value:n,onChange:p=>!l&&c(p.target.value),readOnly:l,placeholder:"What does this workflow do?",className:`${Pu} ${l?"opacity-50":""}`})]}),i.jsxs("div",{className:"w-20",children:[i.jsx("label",{className:bl,children:"Max Iter."}),i.jsx("input",{type:"number",value:r,onChange:p=>!l&&d(Number(p.target.value)),readOnly:l,className:`${Pu} font-mono ${l?"opacity-50":""}`})]}),i.jsxs("div",{children:[i.jsx("label",{className:bl,children:"Color"}),i.jsx("input",{type:"color",value:a,onChange:p=>!l&&h(p.target.value),disabled:l,className:`w-8 h-8 rounded border border-border bg-transparent ${l?"opacity-50":"cursor-pointer"}`})]})]})}function w$({name:e,id:t,color:n,description:r,isBuiltIn:a,actions:l}){return i.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:n}}),i.jsx("span",{className:"text-text-primary text-sm font-medium",children:e}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:t}),a&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),r&&i.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:r})]}),i.jsx("div",{className:"flex items-center gap-1 flex-shrink-0 ml-3",children:l})]})}function HS({title:e,items:t,renderActions:n}){return t.length===0?null:i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsx("div",{className:"space-y-2",children:t.map(r=>i.jsx(w$,{name:r.name,id:r.id,color:r.color??"#3b82f6",description:r.description,actions:n(r)},r.id))})]})}const Fa="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",ap="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",vs="block text-[11px] text-text-secondary mb-0.5";function op({variables:e,onInsert:t}){return e.length===0?null:i.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(n=>i.jsx("button",{type:"button",onClick:()=>t(n.name),title:n.description,className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-bg-primary border border-border text-text-secondary hover:text-accent-primary hover:border-accent-primary/40 transition-colors",children:`{{${n.name}}}`},n.name))})}function C$({step:e,isEntry:t,agentTypes:n,transitionCount:r,templateVariables:a,onUpdate:l,onRemove:u,onSetEntry:c}){const{color:d,name:h}=ex(e,n);return i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:d+"20",color:d},children:h}),t&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[!t&&i.jsx("button",{onClick:c,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),i.jsx("button",{onClick:u,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Type"}),i.jsx("select",{value:e.type,onChange:p=>{const m=p.target.value,x=m==="sub_agent"?"verification":"build";if(m==="agent"){const y=n.find(w=>!w.subagent);l({...e,type:m,phase:x,agentId:(y==null?void 0:y.id)??"builder",name:(y==null?void 0:y.name)??"Agent"})}else if(m==="sub_agent"){const y=n.find(w=>w.subagent);l({...e,type:m,phase:x,subAgentType:(y==null?void 0:y.id)??"",name:(y==null?void 0:y.name)??"Sub-Agent"})}else l({...e,type:m,phase:x,name:"Shell"})},className:ap,children:b$.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))})]}),e.type==="agent"&&i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Agent Type"}),i.jsx("select",{value:e.agentId??"builder",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,agentId:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:ap,children:n.filter(p=>!p.subagent).map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))})]}),e.type==="sub_agent"&&i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Sub-Agent Type"}),i.jsxs("select",{value:e.subAgentType??"",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,subAgentType:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:ap,children:[i.jsx("option",{value:"",children:"— select —"}),n.filter(p=>p.subagent).map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Prompt"}),i.jsx("textarea",{value:e.prompt??"",onChange:p=>l({...e,prompt:p.target.value||void 0}),rows:6,className:`${Fa} resize-y text-xs`,placeholder:"Injected on first entry..."}),i.jsx(op,{variables:a,onInsert:p=>l({...e,prompt:(e.prompt??"")+`{{${p}}}`})})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Nudge Prompt"}),i.jsx("textarea",{value:e.nudgePrompt??"",onChange:p=>l({...e,nudgePrompt:p.target.value||void 0}),rows:6,className:`${Fa} resize-y text-xs`,placeholder:"Injected on re-entry..."}),i.jsx(op,{variables:a,onInsert:p=>l({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${p}}}`})})]})]}),e.type==="shell"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Command"}),i.jsx("textarea",{value:e.command??"",onChange:p=>l({...e,command:p.target.value}),rows:3,className:`${Fa} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),i.jsx(op,{variables:a,onInsert:p=>l({...e,command:(e.command??"")+`{{${p}}}`})})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Timeout (ms)"}),i.jsx("input",{type:"number",value:e.timeout??6e4,onChange:p=>l({...e,timeout:Number(p.target.value)}),className:`${Fa} font-mono text-xs`})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Success Codes"}),i.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:p=>l({...e,successExitCodes:p.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${Fa} font-mono text-xs`})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:vs,children:"Sub-group"}),i.jsx("input",{value:e.subGroup??"",onChange:p=>l({...e,subGroup:p.target.value||void 0}),placeholder:"e.g. build, verify, review",className:Fa})]}),i.jsx("div",{className:"pt-1 border-t border-border/50",children:i.jsxs("p",{className:"text-text-muted text-[10px]",children:[r," outgoing transition",r!==1?"s":""," — drag from the bottom port to connect."]})})]})}const Va="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",US="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Mi="block text-[11px] text-text-secondary mb-0.5";function k$({fromLabel:e,toLabel:t,condition:n,subGroup:r,fromStep:a,agentTypes:l,transitionIndex:u,totalTransitions:c,onUpdateCondition:d,onUpdateSubGroup:h,onDelete:p,onMoveUp:m,onMoveDown:x}){var C;const y=a&&(a.type==="sub_agent"||a.type==="agent")?l.find(_=>_.id===(a.type==="sub_agent"?a.subAgentType:a.agentId)):void 0,w=(y==null?void 0:y.results)&&y.results.length>0;return i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:["#",u+1]}),c>1&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:m,disabled:u===0,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move up (higher priority)",children:i.jsx(yn,{className:"w-3 h-3",rotate:180})}),i.jsx("button",{onClick:x,disabled:u===c-1,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move down (lower priority)",children:i.jsx(yn,{className:"w-3 h-3"})})]})]}),i.jsx("button",{onClick:p,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[i.jsx("span",{className:"font-medium text-text-primary",children:e}),i.jsx(_1,{}),i.jsx("span",{className:"font-medium text-text-primary",children:t})]}),i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Condition"}),i.jsx("select",{value:n.type,onChange:_=>{d(_.target.value==="step_result"?{type:"step_result",result:"success"}:{type:_.target.value})},className:US,children:h2.map(_=>i.jsx("option",{value:_.value,children:_.label},_.value))})]}),n.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Result"}),w?i.jsx("select",{value:n.result??y.results[0],onChange:_=>{d({type:"step_result",result:_.target.value})},className:US,children:y.results.map(_=>i.jsx("option",{value:_,children:_},_))}):i.jsx("input",{type:"text",value:n.result??"success",onChange:_=>d({type:"step_result",result:_.target.value}),placeholder:"e.g. success, passed, failed",className:Va})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Metadata Key"}),i.jsx("input",{type:"text",value:n.key??"",onChange:_=>d({...n,key:_.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:Va})]}),i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Field"}),i.jsx("input",{type:"text",value:n.field??"",onChange:_=>d({...n,field:_.target.value}),placeholder:"e.g. status",className:Va})]}),n.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Value"}),i.jsx("input",{type:"text",value:n.value??"",onChange:_=>d({...n,value:_.target.value}),placeholder:"e.g. passed, resolved",className:Va})]}):i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((C=n.values)==null?void 0:C.join(", "))??"",onChange:_=>d({...n,values:_.target.value.split(",").map(S=>S.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:Va})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:Mi,children:"Sub-group"}),i.jsx("input",{type:"text",value:r??"",onChange:_=>h(_.target.value||void 0),placeholder:"e.g. build, verify",className:Va})]}),i.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function E$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function j$(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const vl="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",FS="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Ga="block text-[11px] text-text-secondary mb-0.5",VS=[];function f2({isOpen:e,onClose:t,initialEditId:n}){var vn,rn;const r=Ot(Ce=>Ce.defaults),a=Ot(Ce=>Ce.userItems),l=Ot(Ce=>Ce.loading),u=Ot(Ce=>Ce.templateVariables),c=Ot(Ce=>Ce.fetchWorkflows),d=Ot(Ce=>Ce.fetchWorkflow),h=Ot(Ce=>Ce.fetchDefaultContent),p=Ot(Ce=>Ce.fetchTemplateVariables),m=Ot(Ce=>Ce.createWorkflow),x=Ot(Ce=>Ce.updateWorkflow),y=Ot(Ce=>Ce.deleteWorkflow),{requestDelete:w,clearConfirm:C,isConfirming:_}=Wl(),[S,v]=N.useState("list"),[b,E]=N.useState(null),[j,T]=N.useState(!1),[D,L]=N.useState(null),[I,P]=N.useState(null),[W,H]=N.useState(""),[R,U]=N.useState(""),[V,G]=N.useState(""),[Z,X]=N.useState("1.0.0"),[$,O]=N.useState("#3b82f6"),[M,q]=N.useState(""),[z,ee]=N.useState(50),[Q,ne]=N.useState(VS),[K,B]=N.useState({type:"always"}),[te,se]=N.useState(""),[xe,oe]=N.useState(!1),Oe=mt(Ce=>Ce.defaults),Me=mt(Ce=>Ce.userItems),ze=mt(Ce=>Ce.projectItems),$e=N.useMemo(()=>[...Oe,...Me,...ze],[Oe,Me,ze]),je=mt(Ce=>Ce.fetchAgents),[rt]=N.useState(null);N.useEffect(()=>{e&&(c(),p(),je(),L(null),P(null),n?r.some(Ne=>Ne.id===n)?h(n).then(Ne=>{Ne&&Qe({...Ne,metadata:{...Ne.metadata,name:Ne.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):d(n).then(Ne=>{Ne&&Qe(Ne,{editingId:n,isReadOnly:!1})}):(v("list"),E(null),T(!1)))},[e,c,d,h,p,n]);const Qe=(Ce,Ne)=>{H(Ce.metadata.name),U(Ce.metadata.id),G(Ce.metadata.description),X(Ce.metadata.version),O(Ce.metadata.color??"#3b82f6"),q(Ce.entryStep),ee(Ce.settings.maxIterations),ne(Ce.steps),B(Ce.startCondition??{type:"always"}),se(""),(Ne==null?void 0:Ne.editingId)!==void 0&&E(Ne.editingId),(Ne==null?void 0:Ne.isReadOnly)!==void 0&&T(Ne.isReadOnly),(Ne==null?void 0:Ne.selectedNodeKey)!==void 0&&L(null),(Ne==null?void 0:Ne.selectedEdgeKey)!==void 0&&P(null),v("edit")},fe=async Ce=>{const Ne=await d(Ce);Ne&&Qe(Ne,{editingId:Ce,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},ce=async()=>{var ot;const Ce=b??R;if(!Ce||!W)return se("Name is required."),!1;if(Q.length===0)return se("Add at least one step."),!1;let Ne=M;if(!Ne||!Q.some(nt=>nt.id===Ne)){if(Ne=((ot=Q.find(nt=>nt.id))==null?void 0:ot.id)??"",!Ne)return se("All steps need an ID."),!1;q(Ne)}oe(!0),se("");const Fe={metadata:{id:Ce,name:W,description:V,version:Z||"1.0.0",color:$},entryStep:Ne,settings:{maxIterations:z},steps:Q,startCondition:K},Ye=b?await x(b,Fe):await m(Fe);return oe(!1),Ye.success?(b||E(Ce),!0):(se(Ye.error??"Failed to save."),!1)},de=async()=>{await ce()},he=async()=>{await ce()&&(n?t():v("list"))},De=()=>{n?t():v("list")},Ue=Ce=>{H(Ce),b||U(E$(Ce))},re=async Ce=>r.some(Fe=>Fe.id===Ce)?await h(Ce):await d(Ce),_e=async Ce=>{const Ne=await re(Ce);Ne&&Qe({...Ne,metadata:{...Ne.metadata,name:Ne.metadata.name+" (copy)",id:`${Ce}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},Le=()=>{E(null),H(""),U(""),G(""),X("1.0.0"),O("#3b82f6"),q(""),ee(50),ne(structuredClone(VS)),B({type:"always"}),se(""),L(null),P(null),T(!1),v("edit")},He=async Ce=>{await y(Ce),C()},qe=N.useCallback(Ce=>{L(Ce),P(null)},[]),Ke=N.useCallback(Ce=>{P(Ce),L(null)},[]),tt=D!==null?Number(D):-1,_t=tt>=0?Q[tt]??null:null,It=N.useCallback(Ce=>{ne(Ne=>Ne.map((Fe,Ye)=>Ye===tt?Ce:Fe))},[tt]),Yt=K.type==="step_result"?`${K.result}`:K.type==="metadata_all_match"?`${K.key??"?"}=${K.value??"?"}`:K.type==="metadata_all_in"?`${K.key??"?"} in [${((vn=K.values)==null?void 0:vn.join(","))??"?"}]`:d2[K.type]??K.type,dt=()=>{const Ce=Q.length,Ne=j$(Q),Fe=$e.find(Ye=>!Ye.subagent);ne([...Q,{id:Ne,name:(Fe==null?void 0:Fe.name)??"Agent",type:"agent",phase:"build",agentId:(Fe==null?void 0:Fe.id)??"builder",transitions:[]}]),M||q(Ne),qe(String(Ce))},kn=N.useCallback((Ce,Ne)=>{Ce==="$start"?(q(Ne),Ke("start")):ne(Fe=>{const Ye=Fe.find(nt=>nt.id===Ce),ot=Ye?Ye.transitions.length:0;return Ke(`${Ce}:${ot}`),Fe.map(nt=>nt.id===Ce?{...nt,transitions:[...nt.transitions,{when:{type:"always"},goto:Ne}]}:nt)})},[Ke]),jt=Ce=>{if(Ce==="start")return null;const Ne=Ce.lastIndexOf(":"),Fe=Ce.slice(0,Ne),Ye=parseInt(Ce.slice(Ne+1));return{stepId:Fe,transIdx:Ye}},Jt=N.useCallback((Ce,Ne)=>{const Fe=jt(Ce);Fe&&ne(Ye=>Ye.map(ot=>ot.id===Fe.stepId?{...ot,transitions:ot.transitions.map((nt,xt)=>xt===Fe.transIdx?Ne(nt):nt)}:ot))},[]),Br=N.useCallback((Ce,Ne)=>{if(Ce==="start"){q(Ne);return}Jt(Ce,Fe=>({...Fe,goto:Ne}))},[Jt]),ve=N.useCallback((Ce,Ne)=>{const Fe=jt(Ce);Fe&&(ne(Ye=>{const ot=Ye.find(xt=>xt.id===Fe.stepId);if(!ot)return Ye;const nt=ot.transitions[Fe.transIdx];return nt?Ye.map(xt=>xt.id===Fe.stepId?{...xt,transitions:xt.transitions.filter((sn,Zt)=>Zt!==Fe.transIdx)}:xt.id===Ne?{...xt,transitions:[...xt.transitions,nt]}:xt):Ye}),P(null))},[]),Ve=N.useCallback(Ce=>{if(Ce==="start"){q(""),P(null);return}const Ne=jt(Ce);Ne&&(ne(Fe=>Fe.map(Ye=>Ye.id===Ne.stepId?{...Ye,transitions:Ye.transitions.filter((ot,nt)=>nt!==Ne.transIdx)}:Ye)),P(null))},[]),ae=N.useCallback((Ce,Ne)=>{if(Ce==="start"){B(Ne);return}Jt(Ce,Fe=>({...Fe,when:Ne}))},[Jt]),me=N.useCallback((Ce,Ne)=>{Ce!=="start"&&Jt(Ce,Fe=>({...Fe,subGroup:Ne||void 0}))},[Jt]),Ie=Ce=>ex(Ce,$e).name,gt=()=>{if(!I)return null;if(I==="start"){const sn=Q.find(Zt=>Zt.id===M);return{type:"start",fromLabel:"Start",toLabel:sn?Ie(sn):"(none)",condition:K}}const Ce=I.lastIndexOf(":"),Ne=I.slice(0,Ce),Fe=parseInt(I.slice(Ce+1)),Ye=Q.find(sn=>sn.id===Ne);if(!Ye)return null;const ot=Ye.transitions[Fe];if(!ot)return null;const nt=Q.find(sn=>sn.id===ot.goto),xt=ot.goto==="$done"?"Done":nt?Ie(nt):ot.goto;return{type:"step",fromLabel:Ie(Ye),toLabel:xt,condition:ot.when,subGroup:ot.subGroup}};if(S==="edit"){const Ce=gt();return i.jsxs(wt,{isOpen:e,onClose:De,title:j?W:b?"Edit Workflow":"New Workflow",size:"full",children:[te&&i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:te}),i.jsx(S$,{formName:W,formId:R,formDescription:V,formMaxIterations:z,formColor:$,isReadOnly:j,onNameChange:Ue,onDescriptionChange:G,onMaxIterationsChange:ee,onColorChange:O}),i.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[i.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[i.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!j&&i.jsx("button",{onClick:dt,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),i.jsxs("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:[i.jsx(_$,{steps:Q,entryStep:M,selectedNodeId:(_t==null?void 0:_t.id)??null,selectedEdgeKey:I,startConditionLabel:Yt,agentTypes:$e,isReadOnly:j,onSelectNode:Ne=>{if(Ne===null){qe(null);return}const Fe=Q.findIndex(Ye=>Ye.id===Ne);qe(Fe>=0?String(Fe):null)},onSelectEdge:Ke,onRemoveStep:Ne=>{var Ye;const Fe=Q.findIndex(ot=>ot.id===Ne);if(ne(ot=>ot.filter(nt=>nt.id!==Ne)),tt===Fe&&qe(null),M===Ne){const ot=Q.filter(nt=>nt.id!==Ne);q(((Ye=ot[0])==null?void 0:Ye.id)??"")}},onCreateTransition:kn,onReconnectTo:Br,onReconnectFrom:ve,onDeleteTransition:Ve}),Q.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[i.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),i.jsx("button",{onClick:dt,className:"px-3 py-1.5 rounded bg-accent-primary/10 text-accent-primary text-xs hover:bg-accent-primary/20",children:"+ Add your first step"})]})]})]}),i.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[i.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:i.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),i.jsx("div",{className:"p-3 overflow-y-auto flex-1 min-h-0",children:j&&(Ce||_t)?i.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):Ce?Ce.type==="start"?i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),M&&i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[i.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),i.jsx(_1,{}),i.jsx("span",{className:"text-text-primary font-medium",children:Ce.toLabel})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Activation Condition"}),i.jsx("select",{value:K.type,onChange:Ne=>B(Ne.target.value==="step_result"?{type:"step_result",result:"success"}:Ne.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:Ne.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:Ne.target.value}),className:FS,children:h2.map(Ne=>i.jsx("option",{value:Ne.value,children:Ne.label},Ne.value))})]}),K.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Result"}),M&&(()=>{const Ne=Q.find(nt=>nt.id===M),Fe=Ne&&(Ne.type==="sub_agent"||Ne.type==="agent")?$e.find(nt=>nt.id===(Ne.type==="sub_agent"?Ne.subAgentType:Ne.agentId)):void 0,Ye=(Fe==null?void 0:Fe.results)&&Fe.results.length>0,ot=(Fe==null?void 0:Fe.results)??[];return Ye?i.jsx("select",{value:K.result??ot[0],onChange:nt=>B({type:"step_result",result:nt.target.value}),className:FS,children:ot.map(nt=>i.jsx("option",{value:nt,children:nt},nt))}):i.jsx("input",{type:"text",value:K.result??"success",onChange:nt=>B({type:"step_result",result:nt.target.value}),placeholder:"e.g. success, passed, failed",className:vl})})()]}),(K.type==="metadata_all_match"||K.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Metadata Key"}),i.jsx("input",{type:"text",value:K.key??"",onChange:Ne=>B({...K,key:Ne.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:vl})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Field"}),i.jsx("input",{type:"text",value:K.field??"",onChange:Ne=>B({...K,field:Ne.target.value}),placeholder:"e.g. status",className:vl})]}),K.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Value"}),i.jsx("input",{type:"text",value:K.value??"",onChange:Ne=>B({...K,value:Ne.target.value}),placeholder:"e.g. passed, resolved",className:vl})]}):i.jsxs("div",{children:[i.jsx("label",{className:Ga,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((rn=K.values)==null?void 0:rn.join(", "))??"",onChange:Ne=>B({...K,values:Ne.target.value.split(",").map(Fe=>Fe.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:vl})]})]}),i.jsx("p",{className:"text-text-muted text-[10px]",children:"Workflow only proceeds when this condition is met. Drag the target handle to change entry step."})]}):(()=>{const Ne=jt(I),Fe=Ne==null?void 0:Ne.stepId,Ye=(Ne==null?void 0:Ne.transIdx)??0,ot=Fe?Q.find(xt=>xt.id===Fe):void 0,nt=(ot==null?void 0:ot.transitions.length)??0;return i.jsx(k$,{fromLabel:Ce.fromLabel,toLabel:Ce.toLabel,condition:Ce.condition,subGroup:"subGroup"in Ce?Ce.subGroup:void 0,fromStep:Ce.type==="step"?Q.find(xt=>xt.id===Ce.fromLabel):void 0,agentTypes:$e,transitionIndex:Ye,totalTransitions:nt,onUpdateCondition:xt=>ae(I,xt),onUpdateSubGroup:xt=>me(I,xt),onDelete:()=>Ve(I),onMoveUp:()=>{ne(xt=>{const sn=xt.find(qt=>qt.id===Fe);if(!sn||Ye===0)return xt;const Zt=[...sn.transitions];return[Zt[Ye-1],Zt[Ye]]=[Zt[Ye],Zt[Ye-1]],xt.map(qt=>qt.id===Fe?{...qt,transitions:Zt}:qt)}),P(`${Fe}:${Ye-1}`)},onMoveDown:()=>{ne(xt=>{const sn=xt.find(qt=>qt.id===Fe);if(!sn||Ye===sn.transitions.length-1)return xt;const Zt=[...sn.transitions];return[Zt[Ye],Zt[Ye+1]]=[Zt[Ye+1],Zt[Ye]],xt.map(qt=>qt.id===Fe?{...qt,transitions:Zt}:qt)}),P(`${Fe}:${Ye+1}`)}})})():_t?i.jsx(C$,{step:_t,isEntry:_t.id===M,agentTypes:$e,transitionCount:_t.transitions.length,templateVariables:u,onUpdate:It,onRemove:()=>{var Ne;if(_t&&(ne(Q.filter((Fe,Ye)=>Ye!==tt)),qe(null),M===_t.id)){const Fe=Q.filter((Ye,ot)=>ot!==tt);q(((Ne=Fe[0])==null?void 0:Ne.id)??"")}},onSetEntry:()=>q(_t.id)}):i.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",i.jsx("br",{}),"Drag from a port to connect."]})})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border",children:[i.jsx(Ze,{variant:"secondary",onClick:De,children:"Close"}),j?i.jsx(Ze,{variant:"primary",onClick:()=>{H(W+" (copy)"),U(`${b}-copy-${Date.now()}`),E(null),T(!1)},children:"Duplicate & Customize"}):i.jsxs(i.Fragment,{children:[i.jsx(Ze,{variant:"primary",onClick:de,children:"Save"}),i.jsx(Ze,{variant:"primary",onClick:he,children:"Save & Close"})]})]})]})}return i.jsx(wt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:i.jsx(D1,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:Le,loading:l,hasItems:r.length>0||a.length>0,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(HS,{title:"Built-in",items:r,renderActions:Ce=>i.jsx(i.Fragment,{children:i.jsx(qi,{onClick:()=>_e(Ce.id),children:i.jsx(eg,{})})})}),i.jsx(HS,{title:"Custom",items:a,renderActions:Ce=>i.jsxs(i.Fragment,{children:[i.jsx(qi,{onClick:()=>fe(Ce.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Ku,{onClick:()=>_e(Ce.id)}),_(Ce.id,"delete")?i.jsx(ig,{onConfirm:()=>He(Ce.id),onCancel:C}):i.jsx(ag,{onClick:()=>w(Ce.id)})]})})]})})})}function N$(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function T$({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:r,onSelectWorkflow:a,onCloseCompleteAction:l,textareaContent:u,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:h}){const[,p]=Ln(),m=mn(z=>z.fetchCommands),x=Ot(z=>z.fetchWorkflows),y=mt(z=>z.fetchAgents),w=mn(z=>z.defaults),C=mn(z=>z.userItems),_=mn(z=>z.projectItems),S=Ot(z=>z.defaults),v=Ot(z=>z.userItems),b=Ot(z=>z.projectItems),E=mt(z=>z.defaults),j=mt(z=>z.userItems),T=mt(z=>z.projectItems),D=Re(z=>{var ee;return(ee=z.currentSession)==null?void 0:ee.mode}),L=Re(z=>{var ee;return((ee=z.currentSession)==null?void 0:ee.dangerLevel)??"normal"}),I=Re(z=>z.switchMode),P=Re(z=>z.switchDangerLevel),W=Re(z=>{var ee;return(ee=z.currentSession)==null?void 0:ee.projectId}),H=N.useRef(void 0),[R,U]=N.useState(""),[V,G]=N.useState(0),Z=N.useRef(null),X=N.useRef(!1);N.useEffect(()=>{e&&(X.current=!0)},[e]),N.useEffect(()=>{if(e){m(),x(),y(),U(""),G(0);const z=setTimeout(()=>{var ee;return(ee=Z.current)==null?void 0:ee.focus()},50);return()=>clearTimeout(z)}},[e,m,x,y]),N.useEffect(()=>{var z;!e&&X.current&&(n==null||n(),(z=H.current)==null||z.call(H),H.current=void 0)},[e,n]);const O=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const z=W??N$(window.location.pathname);z&&p(`/p/${z}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{H.current=l,t()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{t(),c==null||c()}},{id:"toggle-autoscroll",name:h?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{t(),d==null||d(!h)}},...Kr(Kr(E,j),T).filter(z=>!z.subagent&&z.id!==D).map(z=>({id:z.id,name:z.name,prefix:"Agent > Switch to",action:()=>I(z.id)})),...Kr(Kr(w,C),_).map(z=>({id:z.id,name:z.name,prefix:"Command > Launch",action:()=>r(z.id,u)})),...Kr(Kr(S,v),b).map(z=>({id:z.id,name:z.name,prefix:"Workflow > Run",action:()=>a(z.id)})),...["normal","dangerous"].filter(z=>z!==L).map(z=>({id:z,name:z.charAt(0).toUpperCase()+z.slice(1),prefix:"Mode > Switch to",action:()=>P(z)}))].filter(z=>ai(`${z.prefix} ${z.name}`,R)),M=O.length-1,q=z=>{Ok(z,M,G,()=>{var ee;(ee=O[V])==null||ee.action(),t()},t)};return e?di.createPortal(i.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),i.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[i.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[i.jsx("input",{ref:Z,type:"text",value:R,onChange:z=>{U(z.target.value),G(0)},onKeyDown:q,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx(sg,{onClick:t,className:"shrink-0","aria-label":"Close"})]}),i.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:O.length===0?i.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:w.length+C.length+S.length+v.length>0?"No matches":"No agents, commands, or workflows yet"}):O.map((z,ee)=>i.jsxs("button",{type:"button",onClick:()=>{z.action(),t()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${ee===V?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:[i.jsxs("span",{className:"text-text-muted font-normal",children:[z.prefix," "]}),i.jsx("span",{children:z.name})]},z.id))})]})]}),document.body):null}const m2="openfox-message-search-filters",A$=[{key:"user",label:"User prompts"},{key:"thinking",label:"Thinking"},{key:"response",label:"Responses"}];function L$(){try{const e=localStorage.getItem(m2);if(e){const t=JSON.parse(e);return new Set(t)}}catch{}return new Set(["user","thinking","response"])}function D$(e){localStorage.setItem(m2,JSON.stringify([...e]))}function R$(e){var n,r;if(e.type!=="message")return null;const t=e.message;if(t.role==="user")return"user";if(t.role==="assistant"){if((n=t.content)!=null&&n.trim())return"response";if((r=t.thinkingContent)!=null&&r.trim())return"thinking"}return null}function O$(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear())return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),u=String(t.getDate()).padStart(2,"0"),c=String(t.getHours()).padStart(2,"0"),d=String(t.getMinutes()).padStart(2,"0");return`${a}/${l}/${u} ${c}:${d}`}function I$(e){var t;if(e.type==="message")return e.message.timestamp;if(e.type==="subagent")return(t=e.messages[0])==null?void 0:t.timestamp}function M$(e){var t,n;if(e.type==="message"){const r=e.message;if(r.role==="assistant"){const a=(t=r.content)==null?void 0:t.trim();return((n=r.thinkingContent)==null?void 0:n.trim())&&!a?"italic text-text-muted":""}if(r.role==="user")return"font-bold"}return""}function P$(e){var n,r;if(e.type!=="message")return i.jsx(N_,{className:"w-3.5 h-3.5"});const t=e.message;return t.role==="assistant"?(n=t.thinkingContent)!=null&&n.trim()&&!((r=t.content)!=null&&r.trim())?i.jsx(mT,{className:"w-3.5 h-3.5"}):i.jsx(N_,{className:"w-3.5 h-3.5"}):i.jsx(fT,{className:"w-3.5 h-3.5"})}function GS(e){var t;if(e.type==="message"){const n=e.message,r=n.content||"",a=r.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(n.messageKind==="workflow-started")try{return`Workflow: ${JSON.parse(r).workflowName}`}catch{return"Workflow started"}if(n.messageKind==="task-completed")return"Task completed";if(n.messageKind==="auto-prompt")return"Auto-prompt";if(n.messageKind==="correction")return"Correction";if(n.messageKind==="context-reset")return"Context reset";if(n.messageKind==="command")return"Command executed";if(n.role==="assistant")return a?a.slice(0,200):(t=n.thinkingContent)!=null&&t.trim()?n.thinkingContent.slice(0,200):"";const l=a.slice(0,200);return l.length<a.length?`${l}...`:l}return e.type==="subagent"?`Sub-agent: ${e.subAgentType}`:""}function B$({isOpen:e,onClose:t,displayItems:n,onNavigate:r}){const[a,l]=N.useState(""),[u,c]=N.useState(0),[d,h]=N.useState(L$),p=N.useRef(null),m=N.useRef(null),x=N.useRef(null),y=j=>{h(T=>{const D=new Set(T);return D.has(j)?D.delete(j):D.add(j),D$(D),D})},w=N.useMemo(()=>n.filter(j=>{var T,D;return!(j.type==="context-divider"||j.type==="message"&&(j.message.messageKind==="auto-prompt"||j.message.role==="assistant"&&!((T=j.message.content)!=null&&T.trim())&&!((D=j.message.thinkingContent)!=null&&D.trim())))}),[n]),C=N.useMemo(()=>w.filter(j=>{const T=R$(j);return!(T&&!d.has(T))}),[w,d]),_=N.useMemo(()=>a?w.filter(j=>{const T=GS(j);return ai(T,a)}):C,[C,a]),S=_.length-1;N.useEffect(()=>{if(e){l(""),c(0);const j=setTimeout(()=>{var T;return(T=p.current)==null?void 0:T.focus()},50);return()=>clearTimeout(j)}},[e]),N.useEffect(()=>{e&&m.current&&(m.current.scrollTop=m.current.scrollHeight)},[e]),N.useEffect(()=>{x.current&&x.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[u]);const v=j=>{Ok(j,S,c,()=>{const T=_[u];if(T){const D=n.indexOf(T);D>=0&&r(D),t()}},t)},b=j=>{const T=n.indexOf(j);T>=0&&r(T),t()},E=j=>n.indexOf(j);return e?di.createPortal(i.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),i.jsxs("div",{className:"relative w-full max-w-lg bg-bg-secondary border border-border rounded shadow-xl",children:[i.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[i.jsx(Wi,{}),i.jsx("input",{ref:p,type:"text",value:a,onChange:j=>{l(j.target.value),c(0)},onKeyDown:v,placeholder:"Search timeline...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx("button",{type:"button",onClick:t,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:i.jsx(js,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"flex gap-1.5 px-4 py-2 border-b border-border",children:A$.map(j=>{const T=d.has(j.key);return i.jsx("button",{type:"button",onClick:()=>y(j.key),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${T?"bg-accent-primary/20 text-accent-primary border border-accent-primary/40":"bg-bg-tertiary text-text-muted border border-border hover:text-text-secondary"}`,children:j.label},j.key)})}),i.jsx("div",{ref:m,className:"overflow-y-auto max-h-[60vh] p-2",children:_.length===0?i.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:C.length>0?"No matches":"No messages yet"}):_.map((j,T)=>{const D=E(j),L=P$(j),I=GS(j),P=M$(j),W=I$(j),H=j.type==="message"&&j.message.role==="user";return i.jsx("button",{ref:T===u?x:null,type:"button",onClick:()=>b(j),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${T===u?"bg-accent-primary/20 text-text-primary":H?"bg-accent-primary/5 text-text-secondary hover:bg-accent-primary/10 hover:text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[i.jsx("span",{className:"flex-shrink-0",children:L}),i.jsx("span",{className:`truncate flex-1 ${P}`,children:I})]}),W&&i.jsx("span",{className:"text-text-muted text-xs shrink-0",children:O$(W)})]})},`${D}-${j.type}`)})})]})]}),document.body):null}function $$({attachment:e,onRemove:t}){const n=o2(e.filename);return i.jsxs("div",{className:"relative inline-flex flex-col items-center p-2 bg-bg-tertiary rounded-lg border border-border",children:[i.jsx(ec,{onClick:()=>t(e.id),className:"absolute -top-2 -right-2",size:"sm",variant:"overlay","aria-label":`Remove ${e.filename}`}),a2(e.mimeType)?i.jsx("img",{src:e.data,alt:e.description||e.filename,className:"w-16 h-16 object-cover rounded-md bg-bg-secondary"}):i.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-md bg-bg-secondary text-xs font-bold text-text-muted",children:n}),i.jsx("div",{className:"mt-1 text-xs text-text-muted text-center max-w-16 truncate",title:e.filename,children:e.filename}),i.jsx("div",{className:"text-[10px] text-text-muted",children:Xa(e.size)})]})}function z$({history:e,selectedIndex:t,onSelect:n,onEscape:r,onNavigate:a}){const l=N.useRef(null),u=N.useRef(null);N.useEffect(()=>{u.current&&l.current&&u.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[t]);const c=h=>{switch(h.key){case"Enter":h.preventDefault(),e[t]&&n(e[t].content);break;case"Escape":h.preventDefault(),r();break;case"ArrowUp":h.preventDefault(),a("up");break;case"ArrowDown":h.preventDefault(),a("down");break}},d=h=>{n(h)};return i.jsx("div",{ref:l,role:"list",className:"mb-2 p-2 bg-bg-secondary border border-border rounded-lg overflow-y-auto max-h-64",onKeyDown:c,children:e.map((h,p)=>i.jsxs("div",{ref:p===t?u:null,role:"listitem",onClick:()=>d(h.content),className:`
309
309
  p-2 rounded cursor-pointer transition-colors
310
310
  ${p===t?"bg-accent-primary/20 border border-accent-primary":"hover:bg-bg-tertiary"}
311
- `,children:[i.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[h.formattedTimestamp,h.sessionName&&i.jsxs(i.Fragment,{children:[" | ",i.jsx("span",{className:"text-accent-primary font-medium",children:h.sessionName})]})]}),i.jsx("div",{className:"text-sm text-text-primary mt-1",children:h.trimmedContent})]},h.id))})}function H$(){const e=FN(),t=e?"bg-amber-400":"bg-accent-primary";return i.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"flex gap-0.5",children:[i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"0ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"300ms"}})]}),i.jsx("span",{className:"text-text-secondary",children:e?"Running... (abort in progress)":"Running"})]}),!e&&i.jsx("span",{className:"text-text-muted",children:"esc to interrupt"})]})}const U$={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function F$(e,t={}){const n={...U$,...t};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=X$(a),u=`data:${e.type};base64,${l}`,c=await p2(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await V$(e,n)}async function V$(e,t){const n=await W$(e),r=await p2(n),{width:a,height:l}=G$(r.width,r.height,t.maxWidth,t.maxHeight),u=q$();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(r,0,0,a,l);let d=t.quality,h="";for(let m=0;m<10&&(h=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),!(WS(h)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=WS(h);return{dataUrl:h,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function G$(e,t,n,r){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>r?{width:Math.round(r*a),height:r}:{width:e,height:t}}function W$(e){return new Promise((t,n)=>{const r=Y$(),a=new r;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function p2(e){return new Promise((t,n)=>{const r=K$(),a=new r;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function q$(){var t;const e=tx();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function K$(){const e=tx();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function Y$(){const e=tx();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function tx(){return globalThis}function X$(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++){const a=t[r];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function WS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}const qS=50*1024*1024,KS=1024*1024,Q$=["image/png","image/jpeg","image/gif"];function J$(e){return e==="application/pdf"}function Z$(e){return Q$.includes(e.type)}async function e7(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}async function YS(e,t,n){try{if(Zg(e.type)){if(e.size>KS){n(`Text file too large (${Xa(e.size)}). Maximum is ${Xa(KS)}.`);return}const r=await e.text(),a={id:$u(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}else if(Wu(e.type)||J$(e.type)){if(e.size>qS){const r=Wu(e.type)?"Image":"PDF";n(`${r} file too large (${Xa(e.size)}). Maximum is ${Xa(qS)}.`);return}if(Wu(e.type)&&Z$(e)){const r=await F$(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),a={id:$u(),filename:e.name||"unnamed-file",mimeType:r.mimeType,size:r.size,data:r.dataUrl};t(a)}else{const r=await e7(e),a={id:$u(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}}else n(`Unsupported file type: ${e.type}. Supported types: images (PNG, JPG, GIF, WebP, BMP, SVG), PDF, text files, JSON, XML, YAML, and other common text-based formats.`)}catch(r){const a=r instanceof Error?r.message??"Failed to process file":"Failed to process file";n(a)}}function g2(e){const t=Re(l=>l.sendMessage),n=Re(l=>l.launchWorkflow),r=N.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=N.useCallback((l,u,c,d)=>{e(!0),n(l,u,c,d)},[e,n]);return{sendMessage:r,launchWorkflow:a}}function t7({children:e}){return di.createPortal(e,document.body)}function n7(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function r7({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,h]=N.useState(!1),[p,m]=N.useState("commands"),[x,y]=N.useState(""),[w,C]=N.useState(0),[_,S]=N.useState(null),[v,b]=N.useState(null),E=N.useRef(null),j=N.useRef(null),T=mn(ee=>ee.defaults),D=mn(ee=>ee.userItems),L=mn(ee=>ee.projectItems),I=mn(ee=>ee.fetchCommands),P=Ot(ee=>ee.defaults),W=Ot(ee=>ee.userItems),H=Ot(ee=>ee.projectItems),R=Ot(ee=>ee.fetchWorkflows),U=Kr(Kr(T,D),L),V=Kr(Kr(P,W),H);N.useEffect(()=>{d&&(p==="commands"?I():p==="workflows"&&R())},[d,p,I,R]),N.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ee;return(ee=E.current)==null?void 0:ee.focus()}))},[d,p]),N.useEffect(()=>{if(!d)return;const ee=Q=>{var ne;(ne=j.current)!=null&&ne.contains(Q.target)||h(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[d]);const G=ee=>{switch(ee.key){case"ArrowDown":ee.preventDefault(),C(Q=>{const K=(p==="commands"?U:V).filter(B=>{const te=x.toLowerCase();return!te||B.name.toLowerCase().includes(te)});return Math.min(Q+1,K.length-1)});break;case"ArrowUp":ee.preventDefault(),C(Q=>Math.max(Q-1,0));break;case"Enter":ee.preventDefault();break;case"Escape":ee.preventDefault(),h(!1);break}},Z=ee=>{y(ee),C(0)},X=U.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),$=V.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),O=async ee=>{const Q=await mn.getState().fetchCommand(ee);Q&&e(Q.prompt,Q.metadata.agentMode,u,c),h(!1)},M=ee=>{t(ee),h(!1)},q=(ee,Q)=>{Q.stopPropagation(),h(!1),S(ee)},z=(ee,Q)=>{Q.stopPropagation(),h(!1),b(ee)};return i.jsxs("div",{ref:j,className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>h(!d),className:"px-1.5 py-2 rounded-r bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors border-l border-border/50",title:"More options",children:i.jsx(k1,{className:"w-4 h-4"})}),d&&i.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[i.jsxs("div",{className:"flex border-b border-border",children:[i.jsx("button",{type:"button",onClick:()=>{m("commands"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),i.jsx("button",{type:"button",onClick:()=>{m("workflows"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),i.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&i.jsx("div",{className:"p-2 border-b border-border",children:i.jsx("input",{ref:E,value:x,onChange:ee=>Z(ee.target.value),onKeyDown:G,placeholder:p==="commands"?"Search commands...":"Search workflows...",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),i.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:p==="commands"?X.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:U.length===0?"No commands yet":"No matches"}):X.map((ee,Q)=>i.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsx("button",{type:"button",onClick:()=>O(ee.id),className:"flex-1 text-left",children:i.jsx("div",{className:"text-sm text-text-primary font-medium",children:ee.name})}),i.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:ne=>q(ee.id,ne)})]},ee.id)):p==="workflows"?$.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:V.length===0?"No workflows yet":"No matches"}):$.map((ee,Q)=>{const ne=n7(ee),K=ee.color??"#3b82f6";return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsxs("button",{type:"button",onClick:()=>M(ee.id),className:"flex-1 text-left flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:K}}),i.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:ee.name}),ne!==null&&i.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:ne?"#22c55e":"#6b7280"},title:ne?"Entry condition met":"Entry condition not met"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[ee.subGroups&&ee.subGroups.length>0&&i.jsx(s7,{subGroups:ee.subGroups,onSelect:B=>{h(!1),n(ee.id,B)}}),i.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:B=>z(ee.id,B)})]})]},ee.id)}):i.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>{l(),h(!1)},className:"flex items-center gap-2 px-4 py-2 rounded bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary transition-colors",children:[i.jsx(ZN,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm font-medium",children:"Attach file"})]}),i.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),p!=="attach"&&i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{h(!1),p==="commands"?r():a()},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),i.jsx(u2,{isOpen:!!_,onClose:()=>S(null),initialEditId:_}),i.jsx(f2,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function s7({subGroups:e,onSelect:t}){const[n,r]=N.useState(!1),[a,l]=N.useState({top:0,right:0}),u=N.useRef(null),c=N.useRef(null);qd(c,()=>r(!1),n);const d=h=>{if(h.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}r(!n)};return i.jsxs(i.Fragment,{children:[i.jsx("button",{ref:u,type:"button",onClick:d,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&i.jsx(t7,{children:i.jsx("div",{ref:c,onMouseDown:h=>h.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(h=>i.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),t(h)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:h},h))})})]})}function i7({messages:e,onCancel:t}){return e.length===0?null:i.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>i.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[i.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),i.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),i.jsx(ec,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function a7({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:r,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d}){const h=e.allowedTools.filter(p=>!(r!=null&&r.has(p)));return i.jsxs(H1,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),i.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&i.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[h.slice(0,5).map(p=>i.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:p},p)),h.length>5&&i.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",h.length-5," more"]})]})]})}function XS({title:e,agents:t,subagents:n,isBuiltIn:r,alwaysAllowedNames:a,onView:l,onDuplicate:u,onEdit:c,onDelete:d,onCancelDelete:h,isConfirmingDelete:p}){if(t.length===0&&n.length===0)return null;const m=x=>i.jsx(a7,{agent:x,isBuiltIn:r,isConfirmingDelete:(p==null?void 0:p(x.id))??!1,alwaysAllowedNames:a,onView:()=>l(x.id),onEdit:r?void 0:()=>c==null?void 0:c(x.id),onDuplicate:()=>u(x.id),onDelete:r?void 0:()=>d==null?void 0:d(x.id),onCancelDelete:r?void 0:()=>h==null?void 0:h(x.id)},x.id);return i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsxs("div",{className:"space-y-2",children:[t.map(m),n.length>0&&i.jsxs("div",{className:"mt-3",children:[i.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),i.jsx("div",{className:"space-y-2",children:n.map(m)})]})]})]})}function o7(e){const t=new Map;for(const n of e){const r=n.indexOf(":");if(r===-1)t.set(n,new Set);else{const a=n.slice(0,r),u=n.slice(r+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function lp(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function l7({formName:e,formId:t,formDescription:n,formSubagent:r,formTools:a,formColor:l,formPrompt:u,formError:c,saving:d,isReadOnly:h,availableTools:p,onNameChange:m,onIdChange:x,onDescriptionChange:y,onSubagentChange:w,onToolsChange:C,onColorChange:_,onPromptChange:S,onSave:v,onCancel:b,onDuplicate:E}){const j=o7(a),T=p.filter(I=>!(r&&I.topLevelOnly)),D=(I,P)=>{const W=new Map(j),H=W.get(I)||new Set,R=new Set(H);R.has(P)?R.delete(P):R.add(P),R.size===0?W.set(I,new Set):W.set(I,R),C(lp(W))},L=I=>{const P=new Map(j);P.has(I)?P.delete(I):P.set(I,new Set),C(lp(P))};return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3",children:[c&&i.jsx(Qa,{message:c}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(kr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:h}),i.jsx(kr,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(kr,{label:"Description",value:n,onChange:y,placeholder:"What this agent does",readOnly:h}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),i.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[i.jsx("button",{onClick:()=>!h&&w(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${h?"pointer-events-none opacity-60":""}`,children:"Agent"}),i.jsx("button",{onClick:()=>!h&&w(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),i.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),i.jsx("input",{type:"color",value:l,onChange:I=>!h&&_(I.target.value),disabled:h,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),i.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:T.map(I=>{const P=j.has(I.name),W=I.actions.length>0,H=j.get(I.name)||new Set;return W?h?i.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[i.jsx("span",{children:I.name}),i.jsx("span",{className:"text-[10px]",children:"*"})]},I.name):i.jsx(Zl,{trigger:i.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${P?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[i.jsx("span",{children:I.name}),W&&i.jsx("span",{className:`text-[10px] ${P&&H.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...I.actions.map(R=>({label:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${I.name}-${R}`,children:[i.jsx("input",{type:"checkbox",id:`${I.name}-${R}`,checked:H.has(R),onChange:()=>D(I.name,R),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),i.jsx("span",{children:R})]}),closeOnClick:!1})),{label:P?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(P)L(I.name);else{const R=new Map(j);R.set(I.name,new Set(I.actions)),C(lp(R))}}}]},I.name):i.jsx("button",{onClick:()=>!h&&L(I.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${P?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none":"cursor-pointer"}`,children:i.jsx("span",{children:I.name})},I.name)})})]})]}),i.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),i.jsx("textarea",{value:u,onChange:I=>!h&&S(I.target.value),readOnly:h,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${h?"opacity-60":""}`})]}),i.jsx(kT,{onCancel:b,onSave:v,saving:d,saveDisabled:!e||!u||h}),h&&i.jsx("div",{className:"flex justify-end mt-2",children:i.jsx("button",{onClick:E,className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})})]})}function c7(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function u7({isOpen:e,onClose:t,initialEditId:n}){const r=mt(de=>de.defaults),a=mt(de=>de.userItems),l=mt(de=>de.loading),u=mt(de=>de.fetchAgents),c=mt(de=>de.fetchAgent),d=mt(de=>de.fetchDefaultContent),h=mt(de=>de.createAgent),p=mt(de=>de.updateAgent),m=mt(de=>de.deleteAgent),[x,y]=N.useState("list"),[w,C]=N.useState(null),[_,S]=N.useState(!1),[v,b]=N.useState(""),[E,j]=N.useState(""),[T,D]=N.useState(""),[L,I]=N.useState(!0),[P,W]=N.useState([]),[H,R]=N.useState("#6b7280"),[U,V]=N.useState(""),[G,Z]=N.useState(""),[X,$]=N.useState(!1),[O,M]=N.useState([]),[q,z]=N.useState(new Set),{requestDelete:ee,clearConfirm:Q,isConfirming:ne}=Wl(),K=de=>{b(de.metadata.name),j(de.metadata.id),D(de.metadata.description),I(de.metadata.subagent),W(de.metadata.allowedTools),R(de.metadata.color??"#6b7280"),V(de.prompt),Z("")},B=(de,he,De)=>{b(de.metadata.name+" (copy)"),j(`${he}-copy-${Date.now()}`),D(de.metadata.description),I(de.metadata.subagent),W(de.metadata.allowedTools),R(de.metadata.color??"#6b7280"),V(de.prompt),Z(""),C(null),S(!1),y("edit")},te=(de,he)=>{K(de),C(he),S(!0),y("edit")};N.useEffect(()=>{e&&(u(),Se("/api/tools").then(de=>de.json()).then(de=>{const he=de.tools||[];z(new Set(he.filter(De=>De.alwaysAllowed).map(De=>De.name))),M(he.filter(De=>!De.alwaysAllowed))}).catch(()=>{M([]),z(new Set)}),n?r.some(he=>he.id===n)?d(n).then(he=>{he&&B(he,n)}):c(n).then(he=>{he&&(K(he),C(n),S(!1),y("edit"))}):(y("list"),C(null),S(!1)))},[e,u,c,d,n]);const se=async de=>{if(r.some(De=>De.id===de)){const De=await d(de);if(!De)return;te(De,de)}else{const De=await c(de);if(!De)return;te(De,de)}},xe=async de=>{const he=await d(de);he&&B(he,de)},oe=()=>{C(null),b(""),j(""),D(""),I(!0),W(["read_file"]),R("#6b7280"),V(""),Z(""),S(!1),y("edit")},Oe=async de=>{const he=await c(de);he&&(K(he),C(de),S(!1),y("edit"))},Me=async de=>{await m(de)},ze=async()=>{const de=w??E;if(!de||!v||!U){Z("Name and prompt are required.");return}$(!0),Z("");const he={metadata:{id:de,name:v,description:T,subagent:L,allowedTools:P.filter(Ue=>!q.has(Ue)),color:H},prompt:U},De=w?await p(w,he):await h(he);if($(!1),!De.success){Z(De.error??"Failed to save agent.");return}n?t():y("list")},$e=()=>{n?t():(y("list"),S(!1))},je=de=>{b(de),w||j(c7(de))},rt=r.filter(de=>de.subagent),Qe=r.filter(de=>!de.subagent),fe=a.filter(de=>de.subagent),ce=a.filter(de=>!de.subagent);return x==="edit"?i.jsx(wt,{isOpen:e,onClose:$e,title:_?`${v}`:w?"Edit Agent":"New Agent",size:"xl",children:i.jsx(l7,{formName:v,formId:E,formDescription:T,formSubagent:L,formTools:P,formColor:H,formPrompt:U,formError:G,saving:X,isReadOnly:_,availableTools:O,onNameChange:je,onIdChange:j,onDescriptionChange:D,onSubagentChange:de=>{I(de),de&&W(he=>he.filter(De=>{var Ue;return!((Ue=O.find(re=>re.name===De))!=null&&Ue.topLevelOnly)}))},onToolsChange:W,onColorChange:R,onPromptChange:V,onSave:ze,onCancel:$e,onDuplicate:()=>{b(v+" (copy)"),j(`${w}-copy-${Date.now()}`),C(null),S(!1)}})}):i.jsx(wt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:i.jsx(D1,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:oe,loading:l,hasItems:r.length>0||a.length>0,children:i.jsxs("div",{className:"space-y-4",children:[r.length>0&&i.jsx(XS,{title:"Built-in",agents:Qe,subagents:rt,isBuiltIn:!0,alwaysAllowedNames:q,onView:se,onDuplicate:xe}),a.length>0&&i.jsx(XS,{title:"Custom",agents:ce,subagents:fe,isBuiltIn:!1,alwaysAllowedNames:q,isConfirmingDelete:de=>ne(de,"delete"),onView:se,onDuplicate:xe,onEdit:Oe,onDelete:de=>{ne(de,"delete")?(Me(de),Q()):ee(de)},onCancelDelete:Q})]})})})}function d7(){const e=Re(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=Re(v=>v.switchMode),n=mt(v=>v.defaults),r=mt(v=>v.userItems),a=mt(v=>v.fetchAgents),l=[...n,...r],[u,c]=N.useState(!1),[d,h]=N.useState(!1),[p,m]=N.useState(null),x=N.useRef(null);N.useEffect(()=>{a()},[a]),qd(x,()=>c(!1));const y=Gl();if(!e)return null;const w=l.filter(v=>!v.subagent),C=w.find(v=>v.id===e),_=(C==null?void 0:C.name)??e,S=Hl(l,e);return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[i.jsx("span",{className:"text-sm font-medium",style:{color:S},children:_}),i.jsx(yn,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&i.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((v,b)=>{const E=v.id===e,j=Hl(l,v.id),T=y.agentSwitching[b],D=T?qu(T):null;return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[i.jsxs("button",{type:"button",onClick:()=>{E||t(v.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"font-medium truncate",style:{color:j},children:v.name}),E&&i.jsx(Pr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),D&&i.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:D})]},v.id)}),i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{c(!1),h(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),i.jsx(u7,{isOpen:d,onClose:()=>{h(!1),m(null)},initialEditId:p})]})}function h7(){const e=Re(r=>r.currentSession),t=Re(r=>r.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return i.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[i.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),i.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function QS({value:e,onChange:t}){return i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",i.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),i.jsx("input",{type:"text",value:e??"",onChange:n=>t(n.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]})}const f7=[8080,11434,8e3,1234];function Yp(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function x2(e){return{name:e.name,url:e.url,backend:e.backend,apiKey:e.apiKey,isLocal:e.isLocal,thinkingField:e.thinkingField,authAdapter:e.authAdapter,transportAdapter:e.transportAdapter,models:e.models}}function m7({model:e,modelConfigs:t,autoConfigState:n,testResults:r,onUpdateConfig:a,onRunAutoConfig:l,onTestParams:u,onShowRaw:c}){var d,h,p,m,x,y,w,C,_,S,v,b,E,j,T,D,L,I,P,W,H,R,U,V,G,Z,X,$,O,M,q,z,ee,Q,ne,K,B,te,se,xe,oe,Oe,Me,ze,$e;return i.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>l(e.id),disabled:n.progress[e.id]==="probing",className:"px-4 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:n.progress[e.id]==="probing"?"Probing...":"Auto-config"}),n.progress[e.id]==="done"&&i.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&i.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),i.jsxs("div",{className:"flex gap-3 items-end",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),i.jsx("input",{type:"number",value:((d=t[e.id])==null?void 0:d.contextWindow)??e.contextWindow,onChange:je=>a(e.id,{contextWindow:parseInt(je.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[i.jsx("input",{type:"checkbox",checked:((h=t[e.id])==null?void 0:h.supportsVision)??!1,onChange:je=>a(e.id,{supportsVision:je.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"thinking"),disabled:(p=r[e.id+"-thinking"])==null?void 0:p.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(m=r[e.id+"-thinking"])!=null&&m.loading?"Testing...":"Test thinking"}),((x=r[e.id+"-thinking"])==null?void 0:x.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((y=r[e.id+"-thinking"])==null?void 0:y.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(w=r[e.id+"-thinking"])==null?void 0:w.error,children:"Fail"}),((C=r[e.id+"-thinking"])==null?void 0:C.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"non-thinking"),disabled:(_=r[e.id+"-non-thinking"])==null?void 0:_.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(S=r[e.id+"-non-thinking"])!=null&&S.loading?"Testing...":"Test non-thinking"}),((v=r[e.id+"-non-thinking"])==null?void 0:v.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((b=r[e.id+"-non-thinking"])==null?void 0:b.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(E=r[e.id+"-non-thinking"])==null?void 0:E.error,children:"Fail"}),((j=r[e.id+"-non-thinking"])==null?void 0:j.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),i.jsxs("details",{className:"group",children:[i.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[i.jsx(yn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),i.jsxs("div",{className:"mt-3 space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((T=t[e.id])==null?void 0:T.thinkingEnabled)??!1,onChange:je=>a(e.id,{thinkingEnabled:je.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((D=t[e.id])==null?void 0:D.thinkingEnabled)&&i.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),(L=e.reasoningEfforts)!=null&&L.length?i.jsx("select",{"aria-label":"Reasoning effort",value:((I=t[e.id])==null?void 0:I.thinkingLevel)??Yp(e.reasoningEfforts),onChange:je=>a(e.id,{thinkingLevel:je.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary",children:e.reasoningEfforts.map(je=>i.jsx("option",{value:je,children:je},je))}):i.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((P=t[e.id])==null?void 0:P.thinkingLevel)??"",onChange:je=>a(e.id,{thinkingLevel:je.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsx(QS,{value:(W=t[e.id])==null?void 0:W.thinkingQueryParams,onChange:je=>a(e.id,{thinkingQueryParams:je})})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((H=t[e.id])==null?void 0:H.nonThinkingEnabled)??!1,onChange:je=>a(e.id,{nonThinkingEnabled:je.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((R=t[e.id])==null?void 0:R.nonThinkingEnabled)&&i.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:i.jsx(QS,{value:(U=t[e.id])==null?void 0:U.nonThinkingQueryParams,onChange:je=>a(e.id,{nonThinkingQueryParams:je})})})]}),i.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),i.jsx("input",{type:"number",step:"0.1",value:((V=t[e.id])==null?void 0:V.temperature)??"",onChange:je=>a(e.id,{temperature:je.target.value?parseFloat(je.target.value):void 0}),placeholder:((Z=(G=t[e.id])==null?void 0:G.defaultTemperature)==null?void 0:Z.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((X=t[e.id])==null?void 0:X.defaultTemperature)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",($=t[e.id])==null?void 0:$.defaultTemperature]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),i.jsx("input",{type:"number",step:"0.05",value:((O=t[e.id])==null?void 0:O.topP)??"",onChange:je=>a(e.id,{topP:je.target.value?parseFloat(je.target.value):void 0}),placeholder:((q=(M=t[e.id])==null?void 0:M.defaultTopP)==null?void 0:q.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((z=t[e.id])==null?void 0:z.defaultTopP)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(ee=t[e.id])==null?void 0:ee.defaultTopP]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),i.jsx("input",{type:"number",value:((Q=t[e.id])==null?void 0:Q.topK)??"",onChange:je=>a(e.id,{topK:je.target.value?parseInt(je.target.value):void 0}),placeholder:((K=(ne=t[e.id])==null?void 0:ne.defaultTopK)==null?void 0:K.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((B=t[e.id])==null?void 0:B.defaultTopK)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(te=t[e.id])==null?void 0:te.defaultTopK]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),i.jsx("input",{type:"number",value:((se=t[e.id])==null?void 0:se.maxTokens)??"",onChange:je=>a(e.id,{maxTokens:je.target.value?parseInt(je.target.value):void 0}),placeholder:((oe=(xe=t[e.id])==null?void 0:xe.defaultMaxTokens)==null?void 0:oe.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((Oe=t[e.id])==null?void 0:Oe.defaultMaxTokens)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Me=t[e.id])==null?void 0:Me.defaultMaxTokens]})]})]})]}),i.jsx("div",{className:"pt-3 border-t border-border",children:i.jsx(p7,{value:(ze=t[e.id])==null?void 0:ze.compactionThreshold,maxTokens:(($e=t[e.id])==null?void 0:$e.contextWindow)??e.contextWindow,onChange:je=>a(e.id,{compactionThreshold:je})})})]})]})}function p7({value:e,maxTokens:t,onChange:n}){const l=Math.min(95,Math.floor((t-5e3)/t*100)),u=Math.min(l,Math.ceil(15e3/t*100)),c=Math.min(e??.85,l/100),[d,h]=N.useState(Math.round(c*100));N.useEffect(()=>{const m=Math.min(e??.85,l/100);h(Math.round(m*100))},[e,l]);const p=Math.floor(t*(d/100));return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-3 mb-1",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Auto-compaction threshold"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"font-mono text-xs text-text-primary",children:[d,"% · ",so(p)]}),i.jsx("button",{type:"button",onClick:()=>{n(void 0),h(Math.round(.85*100))},disabled:e===void 0,className:"text-xs text-accent-primary hover:underline disabled:text-text-muted disabled:no-underline",children:"Default"})]})]}),i.jsx("input",{"aria-label":"Auto-compaction threshold",type:"range",min:u,max:l,step:"1",value:d,onChange:m=>h(Number(m.target.value)),onMouseUp:()=>n(d/100),onTouchEnd:()=>n(d/100),onBlur:()=>n(d/100),onKeyUp:()=>n(d/100),className:"w-full"}),i.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Minimum ",so(15e3)," tokens · maximum ",l,"% · default 85%"]})]})}function y2({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:a,editModelId:l}){const[u,c]=N.useState(r),[d,h]=N.useState(""),[p,m]=N.useState(""),[x,y]=N.useState("unknown"),[w,C]=N.useState(""),[_,S]=N.useState(!1),[v,b]=N.useState(),[E,j]=N.useState(),[T,D]=N.useState(!1),[L,I]=N.useState(null),[P,W]=N.useState([]),[H,R]=N.useState(null),[U,V]=N.useState(!1),[G,Z]=N.useState(""),[X,$]=N.useState({}),[O,M]=N.useState({loading:!1,progress:{}}),[q,z]=N.useState({}),[ee,Q]=N.useState(null),[ne,K]=N.useState(new Set),[B,te]=N.useState(""),[se,xe]=N.useState(null),[oe,Oe]=N.useState("disconnected"),[Me,ze]=N.useState(!1),[$e,je]=N.useState(null),[rt,Qe]=N.useState([]),[fe,ce]=N.useState(!1),[de,he]=N.useState(!1),De=N.useRef(null),Ue=N.useRef(!1),re=N.useRef(null);N.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var ve;return(ve=re.current)==null?void 0:ve.focus()})},[u,e]),N.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current)},[]),N.useEffect(()=>{e&&Se("/api/provider-presets").then(async ve=>ve.ok?await ve.json():{presets:[]}).then(ve=>Qe(ve.presets)).catch(()=>Qe([]))},[e]);function _e(ve,Ve){$(ae=>({...ae,[ve]:{...ae[ve],...Ve}}))}function Le(ve){K(Ve=>new Set(Ve).add(ve.id)),$(Ve=>({...Ve,[ve.id]:{contextWindow:ve.contextWindow,...Ve[ve.id]}}))}function He(ve){if(!ve.trim())return P;const Ve=ve.toLowerCase().split(/\s+/).filter(Boolean);return P.filter(ae=>Ve.every(me=>ae.id.toLowerCase().includes(me)))}N.useEffect(()=>{var ve,Ve;if(e)if(c(r),h((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),y((a==null?void 0:a.backend)??"unknown"),C((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),b(a==null?void 0:a.authAdapter),j(a==null?void 0:a.transportAdapter),I(null),Z((a==null?void 0:a.thinkingField)??""),z({}),Q(null),xe(null),Oe("disconnected"),je(null),ce(!1),he(!1),(ve=a==null?void 0:a.models)!=null&&ve.length){const ae={},me=new Set;for(const Ie of a.models)ae[Ie.id]={contextWindow:Ie.contextWindow,supportsVision:Ie.supportsVision,thinkingEnabled:Ie.thinkingEnabled,thinkingLevel:Ie.thinkingLevel??Yp(Ie.reasoningEfforts),nonThinkingEnabled:Ie.nonThinkingEnabled,thinkingQueryParams:Ie.thinkingQueryParams,nonThinkingQueryParams:Ie.nonThinkingQueryParams,defaultTemperature:Ie.defaultTemperature,defaultTopP:Ie.defaultTopP,defaultTopK:Ie.defaultTopK,defaultMaxTokens:Ie.defaultMaxTokens,temperature:Ie.temperature,topP:Ie.topP,topK:Ie.topK,maxTokens:Ie.maxTokens,compactionThreshold:Ie.compactionThreshold},Ie.selected&&me.add(Ie.id);if(me.size===0)for(const Ie of a.models)me.add(Ie.id);K(me),$(ae),W(a.models),R(l??((Ve=a.models[0])==null?void 0:Ve.id)??null)}else W([]),$({}),R(null),K(new Set)},[e,r,a==null?void 0:a.id,l]),N.useEffect(()=>{const ve=!!v;u===2&&p&&P.length===0&&!T&&!L&&(!ve||oe==="connected")&&Kt(p)},[u,oe]),N.useEffect(()=>{!e||!v||!(a!=null&&a.id)||Ke(a.id)},[e,E,a==null?void 0:a.id]),N.useEffect(()=>{if(!$e)return;const ve=(a==null?void 0:a.id)??se;if(!ve)return;let Ve=!1;const ae=async()=>{const Ie=await Ke(ve);Ve||Ie!=="connected"||(je(null),ce(!1),he(!1),await Kt(p))};ae();const me=window.setInterval(()=>void ae(),2e3);return()=>{Ve=!0,window.clearInterval(me)}},[$e,se,a==null?void 0:a.id]);async function qe(){if(a!=null&&a.id)return a.id;if(se)return se;const ve=await Se("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d||"Provider",url:p,backend:x,authAdapter:v,transportAdapter:E,isLocal:!1,models:[]})});if(!ve.ok)throw new Error("Unable to create provider");const Ve=await ve.json();return xe(Ve.provider.id),Ve.provider.id}async function Ke(ve){const Ve=await Se(`/api/provider-auth/${ve}/status`);if(!Ve.ok)return"error";const ae=await Ve.json(),me=ae.state==="connected"?"connected":ae.state==="pending"?"pending":ae.state==="error"?"error":"disconnected";return Oe(me),me}async function tt(){ze(!0),Oe("pending");try{const ve=await qe(),Ve=await Se(`/api/provider-auth/${ve}/login`,{method:"POST"});if(!Ve.ok)throw new Error("Unable to start provider sign-in");const ae=await Ve.json();je(ae)}catch{Oe("error")}finally{ze(!1)}}async function _t(){var ve;$e!=null&&$e.userCode&&(await((ve=navigator.clipboard)==null?void 0:ve.writeText($e.userCode)),De.current!==null&&window.clearTimeout(De.current),he(!1),requestAnimationFrame(()=>he(!0)),De.current=window.setTimeout(()=>{he(!1),De.current=null},1500))}function It(){$e&&(window.open($e.directUrl??$e.verificationUrl,"_blank","noopener,noreferrer"),ce(!0))}async function Kt(ve){var Ve,ae;D(!0),I(null),W([]);try{const me=new URLSearchParams({url:ve});w&&me.set("apiKey",w),x&&me.set("backend",x);const Ie=E?await Se(`/api/providers/${await qe()}/models`):await Se(`/api/providers/models?${me.toString()}`);if(Ie.ok){const gt=await Ie.json();if((Ve=gt.models)!=null&&Ve.length){W(gt.models),R(((ae=gt.models[0])==null?void 0:ae.id)??null);const vn={};for(const rn of gt.models)vn[rn.id]={contextWindow:rn.contextWindow,thinkingEnabled:!0,thinkingLevel:Yp(rn.reasoningEfforts),defaultTemperature:rn.defaultTemperature,defaultTopP:rn.defaultTopP,defaultTopK:rn.defaultTopK,defaultMaxTokens:rn.defaultMaxTokens};$(vn),gt.models.length===1&&(K(new Set([gt.models[0].id])),R(gt.models[0].id),dt(gt.models[0].id))}}else{const gt=await Ie.json();I(gt.error??`Failed to fetch models from ${ve}`)}}catch(me){I(`Failed to fetch models from ${ve}: ${me instanceof Error?me.message:"Unknown error"}`)}D(!1)}async function dt(ve){M(Ve=>({loading:!0,progress:{...Ve.progress,[ve]:"probing"}}));try{const Ve=await Se("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,apiKey:w||void 0,backend:x||"unknown",models:[{id:ve}]})});if(!Ve.ok){const me=await Ve.json();throw new Error(me.error??"Auto-config failed")}const ae=await Ve.json();for(const me of ae.models){const Ie={};me.contextSource!=="default"&&(Ie.contextWindow=me.contextWindow,Ie.supportsVision=me.supportsVision),me.thinkingConfig&&(Ie.thinkingEnabled=!0,Ie.thinkingQueryParams=JSON.stringify(me.thinkingConfig)),me.nonThinkingConfig&&(Ie.nonThinkingEnabled=!0,Ie.nonThinkingQueryParams=JSON.stringify(me.nonThinkingConfig)),_e(me.id,Ie),M(gt=>({...gt,progress:{...gt.progress,[me.id]:"done"}}))}}catch(Ve){console.error("Auto-config error:",Ve),M(ae=>({...ae,progress:{...ae.progress,[ve]:"error"}}))}finally{M(Ve=>({...Ve,loading:!1}))}}async function kn(ve,Ve){const ae=ve+"-"+Ve;z(me=>({...me,[ae]:{loading:!0}}));try{const me=X[ve],Ie=await Se("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,providerId:(a==null?void 0:a.id)??se??void 0,transportAdapter:E,model:ve,apiKey:w||void 0,backend:x||"unknown",thinkingField:G||void 0,mode:Ve,modelConfig:{temperature:me==null?void 0:me.temperature,topP:me==null?void 0:me.topP,topK:me==null?void 0:me.topK,maxTokens:me==null?void 0:me.maxTokens,supportsVision:me==null?void 0:me.supportsVision,thinkingEnabled:me==null?void 0:me.thinkingEnabled,thinkingLevel:me==null?void 0:me.thinkingLevel,nonThinkingEnabled:me==null?void 0:me.nonThinkingEnabled,thinkingQueryParams:me==null?void 0:me.thinkingQueryParams,nonThinkingQueryParams:me==null?void 0:me.nonThinkingQueryParams}})}),gt=await Ie.json();Ie.ok?z(vn=>({...vn,[ae]:{loading:!1,result:JSON.stringify(gt,null,2),message:gt.message}})):z(vn=>({...vn,[ae]:{loading:!1,error:gt.error??"Test failed"}}))}catch(me){z(Ie=>({...Ie,[ae]:{loading:!1,error:me instanceof Error?me.message:"Request failed"}}))}}function jt(){W([]),$({}),M({loading:!1,progress:{}}),z({}),Q(null),K(new Set),te("")}function Jt(){se&&!Ue.current&&Se(`/api/providers/${se}`,{method:"DELETE"}).catch(ve=>{console.warn("Failed to clean up draft provider",ve)}),t()}function Br(){const ve=d||"Provider",Ve=(a==null?void 0:a.id)??se??`temp-${Date.now()}`;n({id:Ve,name:ve,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:_,thinkingField:G||void 0,authAdapter:v,transportAdapter:E,models:P.map(ae=>{var me,Ie,gt,vn,rn,Ce,Ne,Fe,Ye,ot,nt,xt,sn,Zt,qt,an;return{id:ae.id,name:ae.name,apiModelId:ae.apiModelId,requestBody:ae.requestBody,reasoningEfforts:ae.reasoningEfforts,contextWindow:((me=X[ae.id])==null?void 0:me.contextWindow)??ae.contextWindow,selected:ne.has(ae.id)||void 0,supportsVision:(Ie=X[ae.id])==null?void 0:Ie.supportsVision,thinkingEnabled:(gt=X[ae.id])==null?void 0:gt.thinkingEnabled,thinkingLevel:(vn=X[ae.id])==null?void 0:vn.thinkingLevel,nonThinkingEnabled:(rn=X[ae.id])==null?void 0:rn.nonThinkingEnabled,thinkingQueryParams:(Ce=X[ae.id])==null?void 0:Ce.thinkingQueryParams,nonThinkingQueryParams:(Ne=X[ae.id])==null?void 0:Ne.nonThinkingQueryParams,temperature:(Fe=X[ae.id])==null?void 0:Fe.temperature,topP:(Ye=X[ae.id])==null?void 0:Ye.topP,topK:(ot=X[ae.id])==null?void 0:ot.topK,maxTokens:(nt=X[ae.id])==null?void 0:nt.maxTokens,defaultMaxTokens:(xt=X[ae.id])==null?void 0:xt.defaultMaxTokens,defaultTemperature:(sn=X[ae.id])==null?void 0:sn.defaultTemperature,defaultTopP:(Zt=X[ae.id])==null?void 0:Zt.defaultTopP,defaultTopK:(qt=X[ae.id])==null?void 0:qt.defaultTopK,compactionThreshold:(an=X[ae.id])==null?void 0:an.compactionThreshold}})}),Ue.current=!0,t()}return e?i.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",children:[i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),i.jsx("button",{onClick:Jt,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2].map(ve=>i.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${ve<u?"bg-accent-success":ve===u?"bg-accent-primary":"bg-border"}`},ve))}),u===1&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),i.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[rt.map(ve=>i.jsx("button",{type:"button",onClick:()=>{h(ve.defaults.name??ve.name),m(ve.defaults.url),y(ve.defaults.backend),S(!1),C(""),b(ve.authAdapter),j(ve.transportAdapter),I(null),jt()},className:`p-2 rounded border text-center text-sm transition-colors ${E&&E===ve.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ve.name},ve.id)),i.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),b(void 0),j(void 0),I(null),jt()},className:`p-2 rounded border text-center text-sm transition-colors ${x==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),f7.map(ve=>{const Ve={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},ae={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return i.jsx("button",{type:"button",onClick:()=>{h(me=>me||(ae[ve]??"")),m(me=>me||`http://localhost:${ve}`),y(Ve[ve]??""),S(!0),b(void 0),j(void 0),I(null),jt()},className:`p-2 rounded border text-center text-sm transition-colors ${x===Ve[ve]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ae[ve]??`localhost:${ve}`},ve)})]})]}),!v&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),i.jsx("input",{ref:re,type:"text",value:p,"data-testid":"provider-modal-url",onChange:ve=>{m(ve.target.value),I(null),W([]),$({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),i.jsx("input",{type:"text",autoComplete:"off",value:d,onChange:ve=>h(ve.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!v&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:ve=>C(ve.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!v&&i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:_,onChange:ve=>S(ve.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),i.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[!!v&&i.jsxs("div",{className:"rounded-lg border border-border bg-bg-primary p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-xs text-text-muted",children:"Connect this provider before choosing available models."})]}),oe==="connected"?i.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):i.jsx("button",{type:"button",onClick:()=>void tt(),disabled:Me||oe==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:Me||oe==="pending"?"Connecting...":oe==="error"?"Retry":"Connect"})]}),$e&&i.jsx("div",{className:"mt-4 border-t border-border pt-4",children:$e.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted",children:"Use this code to complete authorization:"}),i.jsx("button",{type:"button",onClick:()=>void _t(),className:"mt-3 w-full rounded-lg border border-accent-primary/40 px-4 py-4 font-mono text-2xl font-semibold tracking-[0.2em] text-accent-primary",children:$e.userCode??"Continue"}),i.jsxs("div",{className:"mt-3 flex gap-2",children:[i.jsx("button",{type:"button",onClick:()=>void _t(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:de?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:It,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:fe?"Reopen authorization":"Open authorization"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted mb-3",children:$e.instructions}),i.jsx("button",{type:"button",onClick:It,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:fe?"Reopen authorization":"Open authorization"})]})})]}),T&&i.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[i.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),L&&i.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[i.jsx("p",{children:L}),i.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),i.jsxs("div",{className:"flex gap-2 mt-2",children:[i.jsx("button",{onClick:()=>Kt(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),i.jsx("button",{onClick:()=>{jt(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),P.length>0&&x&&(!v||oe==="connected")&&i.jsxs(i.Fragment,{children:[ne.size>0&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",ne.size,")"]}),i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),i.jsx("div",{className:"space-y-2",children:P.filter(ve=>ne.has(ve.id)).map(ve=>{var Ve;return i.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[i.jsxs("div",{onClick:()=>R(H===ve.id?null:ve.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:ve.name??ve.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((Ve=X[ve.id])==null?void 0:Ve.contextWindow)??ve.contextWindow).toLocaleString()," ctx"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[O.progress[ve.id]==="probing"?i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):O.progress[ve.id]==="done"?i.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):O.progress[ve.id]==="error"?i.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):v?null:i.jsx("button",{onClick:ae=>{ae.stopPropagation(),dt(ve.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),P.length>1&&i.jsx("button",{onClick:ae=>{ae.stopPropagation();const me=new Set(ne);me.delete(ve.id),K(me),H===ve.id&&R(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),i.jsx(yn,{className:`w-4 h-4 text-text-muted transition-transform ${H===ve.id?"rotate-180":""}`})]})]}),H===ve.id&&i.jsx(m7,{model:ve,modelConfigs:X,autoConfigState:O,testResults:q,onUpdateConfig:_e,onRunAutoConfig:dt,onTestParams:kn,onShowRaw:Q})]},ve.id)})})]}),P.length>1&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),ne.size===0&&i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"This provider has many models available. Select the ones you want to use below."}),i.jsxs("div",{className:"relative mb-2",children:[i.jsx("input",{type:"text",value:B,onChange:ve=>te(ve.target.value),placeholder:"Search models...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),B&&i.jsx("button",{onClick:()=>te(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",He(B).length," of ",P.length," models"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{const ve=new Set(ne),Ve=He(B);for(const ae of Ve)ve.add(ae.id);if(K(ve),$(ae=>{const me={...ae};for(const Ie of Ve)me[Ie.id]={contextWindow:Ie.contextWindow,...me[Ie.id]};return me}),!v)for(const ae of Ve)O.progress[ae.id]!=="probing"&&O.progress[ae.id]!=="done"&&dt(ae.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),i.jsx("button",{onClick:()=>{const ve=new Set(ne),Ve=He(B);for(const ae of Ve)ve.delete(ae.id);K(ve)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),i.jsxs("div",{className:"space-y-1 max-h-48 overflow-y-auto border border-border rounded-lg bg-bg-primary",children:[He(B).map(ve=>{var ae;const Ve=ne.has(ve.id);return i.jsxs("div",{role:"checkbox","aria-checked":Ve,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${Ve?"bg-accent-primary/5":""}`,onClick:()=>{if(Ve){const me=new Set(ne);me.delete(ve.id),K(me)}else Le(ve),v||dt(ve.id)},onKeyDown:me=>{(me.key==="Enter"||me.key===" ")&&(me.preventDefault(),me.currentTarget.click())},children:[i.jsx("input",{type:"checkbox",checked:Ve,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),i.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:ve.name??ve.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((ae=X[ve.id])==null?void 0:ae.contextWindow)??ve.contextWindow).toLocaleString()," ctx"]}),O.progress[ve.id]==="probing"&&i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),O.progress[ve.id]==="done"&&i.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),O.progress[ve.id]==="error"&&i.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},ve.id)}),He(B).length===0&&i.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",B,"”"]})]})]})]})]}),i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[i.jsx("div",{children:u>1&&i.jsx("button",{onClick:()=>{u===2&&jt(),c(u-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:Jt,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u===1?i.jsx("button",{onClick:()=>c(2),disabled:!p,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:"Next — Test & Configure"}):i.jsx("button",{onClick:Br,disabled:O.loading,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:O.loading?"Configuring...":"Save Provider"})]})]})]}),U&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ve=>{ve.target===ve.currentTarget&&V(!1)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),i.jsx("button",{onClick:()=>V(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),i.jsx("input",{type:"text",defaultValue:'{"chat_template_kwargs":{"enable_thinking":false}}',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),i.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",i.jsx("span",{className:"text-text-muted",children:"(override)"})]}),i.jsx("input",{type:"text",value:G,onChange:ve=>Z(ve.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),i.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]})]}),i.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:i.jsx("button",{onClick:()=>V(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})})]})}),ee&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ve=>{ve.target===ve.currentTarget&&Q(null)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[80vh] shadow-2xl flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border shrink-0",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),i.jsx("button",{onClick:()=>Q(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:ee})]})})]}):null}function g7(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function x7(e,t){const n=t.toLowerCase(),r=(e.name??"").toLowerCase(),a=e.id.toLowerCase(),l=a.replace(/-/g," ");return r.includes(n)||a.includes(n)||l.includes(n)}function JS({activeProvider:e,shortModelName:t}){return i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-accent-primary",children:e?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"hidden sm:inline",children:[e.name," • "]}),t]}):t}),i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${e!=null&&e.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:e!=null&&e.isLocal?"local":"api"})]})}function y7({providerId:e,modelConfig:t,isActive:n,isDefault:r,disabled:a,hasSession:l,settingDefault:u,highlighted:c,onModelClick:d,onSetDefault:h,onEditModel:p}){var m;return i.jsxs("div",{className:`flex items-center px-4 py-1.5 text-sm transition-colors group ${c?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${a?"opacity-50 cursor-wait":""} ${n?"text-accent-primary":"text-text-secondary"}`,children:[i.jsx("button",{type:"button",onClick:()=>d(e,t.id),disabled:a,className:"flex-1 truncate text-left",children:t.name??((m=t.id.split("/").pop())==null?void 0:m.replace(/-/g," "))??t.id}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0 ml-2",children:[i.jsx("span",{className:"text-xs text-text-muted",children:g7(t.contextWindow)}),l&&i.jsx("button",{type:"button",onClick:x=>h(x,e,t.id),disabled:u,className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors disabled:opacity-40",title:r?"Default model":"Set as default model",children:r?i.jsx(N1,{className:"w-3.5 h-3.5 text-accent-warning"}):i.jsx(T1,{className:"w-3.5 h-3.5 text-text-muted hover:text-accent-warning"})}),i.jsx("button",{type:"button",onClick:x=>{x.stopPropagation(),p(e,t)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:i.jsx(w1,{className:"w-3 h-3 text-text-muted"})}),n&&i.jsx("span",{className:"text-accent-success flex-shrink-0",title:"Session model",children:i.jsx(Pr,{className:"w-3.5 h-3.5"})})]})]})}function b7(){var Ve;const[,e]=Ln(),t=Re(ae=>ae.currentSession),n=Re(ae=>ae.setSessionProvider),[r,a]=N.useState(!1),[l,u]=N.useState([]),[c,d]=N.useState(null),h=N.useRef(null),[p,m]=N.useState(null),[x,y]=N.useState(!1),[w,C]=N.useState({}),[_,S]=N.useState(null),[v,b]=N.useState(null),[E,j]=N.useState(!1),T=N.useRef(null),[D,L]=N.useState(!1),I=N.useRef(new Set),[P,W]=N.useState(-1),H=N.useRef(null),R=Qt(ae=>ae.providers),U=Qt(ae=>ae.activeProviderId),V=Qt(ae=>ae.defaultModelSelection),G=Qt(ae=>ae.activating),Z=Qt(ae=>ae.activateProvider),X=Qt(ae=>ae.refreshModel),$=Qt(ae=>ae.refreshProviderModels),O=Qt(ae=>ae.setDefaultModel),M=Qt(ae=>ae.fetchConfig),q=Gl();Dl(q.modelSelector,()=>a(ae=>!ae));const z=(t==null?void 0:t.providerId)??null,ee=(t==null?void 0:t.providerModel)??null,Q=(V==null?void 0:V.split("/")[0])??null,ne=(V==null?void 0:V.split("/").slice(1).join("/"))??null,K=z??Q,B=ee??ne,te=B?((Ve=B.split("/").pop())==null?void 0:Ve.replace(/-/g," "))??B:"No model",[se,xe]=N.useState(!1),[oe,Oe]=N.useState(""),Me=N.useRef(null);N.useEffect(()=>{function ae(me){h.current&&!h.current.contains(me.target)&&(a(!1),u([]),I.current=new Set)}return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[]),N.useEffect(()=>()=>{T.current!==null&&window.clearTimeout(T.current)},[]),N.useEffect(()=>{r||(Oe(""),W(-1))},[r]),N.useEffect(()=>{var ae;r&&((ae=Me.current)==null||ae.focus())},[r]),N.useEffect(()=>{P>=0&&H.current&&H.current.scrollIntoView({block:"nearest"})},[P]),N.useEffect(()=>{if(r){const ae=R.map(me=>me.id);u(ae),R.filter(me=>!!me.authAdapter).forEach(me=>void De(me.id)),ae.forEach(me=>{I.current.has(me)||(I.current.add(me),Qe(me))})}},[r,R]),N.useEffect(()=>{if(!v)return;let ae=!1;const me=async()=>{const gt=await De(v.providerId);ae||gt==="connected"&&(b(null),j(!1),L(!1),await M(),I.current.delete(v.providerId),await Qe(v.providerId))};me();const Ie=window.setInterval(()=>void me(),2e3);return()=>{ae=!0,window.clearInterval(Ie)}},[v]);const ze=R.find(ae=>ae.id===K),$e=(ze==null?void 0:ze.status)==="disconnected",je=(ae,me)=>t?t.providerId===ae&&t.providerModel===me:!1,rt=(ae,me)=>V?V===`${ae}/${me}`:!1,Qe=async ae=>{d(ae);try{await $(ae)}catch{}finally{d(null)}},fe=ae=>{l.includes(ae.id)?u(l.filter(me=>me!==ae.id)):(u([...l,ae.id]),Qe(ae.id))},ce=async ae=>{if(ae.id===U){fe(ae);return}t?(n(ae.id,void 0),a(!1),u([])):await Z(ae.id)&&(a(!1),u([]))},de=ae=>{fe(ae)},he=async(ae,me)=>{ae.stopPropagation(),I.current.delete(me),await Qe(me)},De=async ae=>{const me=await Se(`/api/provider-auth/${ae}/status`);if(!me.ok)return"error";const Ie=await me.json();return C(gt=>({...gt,[ae]:Ie.state})),Ie.state},Ue=async(ae,me)=>{ae.stopPropagation(),S(me),C(Ie=>({...Ie,[me]:"pending"})),j(!1),L(!1);try{const Ie=await Se(`/api/provider-auth/${me}/login`,{method:"POST"});if(!Ie.ok)throw new Error("Unable to start provider sign-in");const gt=await Ie.json();b({providerId:me,...gt})}catch{C(Ie=>({...Ie,[me]:"error"}))}finally{S(null)}},re=async()=>{var ae;v!=null&&v.userCode&&(await((ae=navigator.clipboard)==null?void 0:ae.writeText(v.userCode)),T.current!==null&&window.clearTimeout(T.current),j(!1),requestAnimationFrame(()=>j(!0)),T.current=window.setTimeout(()=>{j(!1),T.current=null},1500))},_e=()=>{v&&(window.open(v.directUrl??v.verificationUrl,"_blank","noopener,noreferrer"),L(!0))},Le=()=>{b(null),j(!1),L(!1)},He=async(ae,me)=>{ae.stopPropagation(),S(me);try{if(!(await Se(`/api/provider-auth/${me}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");C(gt=>({...gt,[me]:"disconnected"})),await M()}finally{S(null)}},qe=(ae,me)=>{m({providerId:ae,model:me}),y(!0)},Ke=p?R.find(ae=>ae.id===p.providerId):void 0,tt=()=>{m(null),y(!1)},_t=async ae=>{try{if(!(await Se(`/api/providers/${ae.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(x2(ae))})).ok)throw new Error("Failed to update provider");await Qt.getState().fetchConfig()}catch{}m(null),y(!1)},It=async(ae,me)=>{if(t){Re.setState(gt=>({currentSession:gt.currentSession?{...gt.currentSession,providerId:ae,providerModel:me}:null})),n(ae,me),u([]),a(!1),Ul();return}await Z(ae)&&(u([]),a(!1),Ul())},Kt=async(ae,me,Ie)=>{ae.stopPropagation(),xe(!0);try{await O(me,Ie)}catch{}finally{xe(!1)}};function dt(ae){return ae.models.some(Ie=>Ie.selected)?ae.models.filter(Ie=>Ie.selected):ae.models}const kn=N.useMemo(()=>oe.trim()?R.map(ae=>({provider:ae,models:dt(ae).filter(me=>x7(me,oe))})).filter(ae=>ae.models.length>0):R.map(ae=>({provider:ae,models:dt(ae)})),[R,oe]),jt=N.useMemo(()=>kn.flatMap(ae=>ae.models.map(me=>({providerId:ae.provider.id,modelConfig:me}))),[kn]),Jt=jt.length+1,Br=P===jt.length;N.useEffect(()=>{Jt===1?W(-1):P>=Jt?W(Jt-1):P<0&&oe.trim()&&W(0)},[Jt,P,oe]);const ve=ae=>{switch(ae.key){case"Escape":a(!1);break;case"ArrowDown":ae.preventDefault(),Jt>0&&W(me=>me<Jt-1?me+1:0);break;case"ArrowUp":ae.preventDefault(),Jt>0&&W(me=>me>0?me-1:Jt-1);break;case"Home":ae.preventDefault(),W(0);break;case"End":ae.preventDefault(),W(Jt-1);break;case"Enter":if(ae.preventDefault(),P===jt.length)e("/onboarding"),a(!1);else if(P>=0&&P<jt.length){const me=jt[P];me&&It(me.providerId,me.modelConfig.id)}break}};return R.length===0?i.jsxs("button",{type:"button",onClick:()=>X(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:$e?"LLM server is offline. Click to retry.":te??"Click to refresh model",children:[$e?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):i.jsx(JS,{activeProvider:ze,shortModelName:te}),i.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):i.jsxs("div",{className:"relative",ref:h,children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[$e?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):i.jsx(JS,{activeProvider:ze,shortModelName:te}),i.jsx(yn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:r?180:0})]}),r&&i.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[i.jsxs("div",{className:"flex items-center gap-1 px-3 py-2 border-b border-border flex-shrink-0",children:[i.jsx(Wi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("input",{ref:Me,type:"text",value:oe,onInput:ae=>{Oe(ae.currentTarget.value),W(-1)},onKeyDown:ve,placeholder:"Search models...",className:"bg-transparent border-none outline-none text-sm text-text-primary w-full placeholder:text-text-muted"})]}),i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:i.jsxs("div",{children:[kn.map(ae=>{const me=oe.trim().length>0||l.includes(ae.provider.id);return i.jsxs("div",{children:[i.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${ae.provider.id===K?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${G?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[i.jsxs("div",{onClick:()=>!G&&ce(ae.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[i.jsx("span",{className:`text-sm font-medium truncate ${ae.provider.id===K?"text-accent-primary":"text-text-primary"}`,children:ae.provider.name}),i.jsx("span",{className:"text-xs text-text-muted truncate",children:ae.provider.backend!=="unknown"&&f1(ae.provider.backend)})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!ae.provider.authAdapter&&(w[ae.provider.id]==="connected"||ae.provider.credentialRef?i.jsx("button",{type:"button",onClick:Ie=>He(Ie,ae.provider.id),disabled:_===ae.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-success/40 text-accent-success hover:bg-accent-success/10 disabled:opacity-50",title:"Disconnect provider account",children:"Connected"}):i.jsx("button",{type:"button",onClick:Ie=>Ue(Ie,ae.provider.id),disabled:_===ae.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-primary/40 text-accent-primary hover:bg-accent-primary/10 disabled:opacity-50",title:"Connect provider account",children:_===ae.provider.id?"Starting…":w[ae.provider.id]==="error"||w[ae.provider.id]==="expired"?"Retry":"Connect"})),ae.provider.id===K?i.jsx("span",{className:"text-accent-success",title:"Active provider",children:i.jsx(Pr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-4"}),i.jsx("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),he(Ie,ae.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:i.jsx(Sd,{className:`w-4 h-4 ${c===ae.provider.id?"animate-spin":""} ${ae.provider.id===U?"text-accent-primary":"text-text-muted"}`})}),i.jsx("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),de(ae.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:i.jsx(yn,{className:`w-4 h-4 transition-transform ${me?"rotate-180":""} ${ae.provider.id===U?"text-accent-primary":"text-text-muted"}`})})]})]}),me&&i.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===ae.provider.id?i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):ae.models.length>0?ae.models.map(Ie=>{const vn=jt.findIndex(rn=>rn.providerId===ae.provider.id&&rn.modelConfig.id===Ie.id)===P;return i.jsx("div",{ref:vn?H:void 0,children:i.jsx(y7,{providerId:ae.provider.id,modelConfig:Ie,isActive:je(ae.provider.id,Ie.id),isDefault:rt(ae.provider.id,Ie.id),disabled:c==="activating",hasSession:!!t,settingDefault:se,highlighted:vn,onModelClick:It,onSetDefault:Kt,onEditModel:qe})},`${ae.provider.id}/${Ie.id}`)}):i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},ae.provider.id)}),kn.length===0&&oe.trim()&&i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No models match your search"})]})}),i.jsx("div",{className:`border-t border-border px-3 py-2 ${Br?"bg-bg-tertiary":""} flex-shrink-0`,children:i.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),v&&i.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/70 px-4",role:"dialog","aria-modal":"true","aria-labelledby":"provider-device-title",onMouseDown:ae=>{ae.target===ae.currentTarget&&Le()},children:i.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border bg-bg-secondary p-6 shadow-2xl",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h2",{id:"provider-device-title",className:"text-lg font-semibold text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-sm text-text-muted",children:"Follow the provider instructions to complete authorization."})]}),i.jsx("button",{type:"button",onClick:Le,className:"rounded px-2 py-1 text-xl leading-none text-text-muted hover:bg-bg-tertiary hover:text-text-primary","aria-label":"Close",children:"×"})]}),v.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:re,className:"mt-6 w-full select-all rounded-lg border border-accent-primary/40 bg-bg-primary px-4 py-5 font-mono text-3xl font-semibold tracking-[0.2em] text-accent-primary hover:bg-bg-tertiary",title:"Copy code",children:v.userCode??"Continue"}),i.jsx("div",{className:"mt-3 text-center text-xs text-text-muted",children:E?"Copied to clipboard":"Click the code to copy it"}),i.jsxs("div",{className:"mt-6 flex gap-3",children:[i.jsx("button",{type:"button",onClick:re,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:E?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:_e,className:"flex-1 rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:D?"Reopen authorization":"Open authorization"})]}),i.jsx("p",{className:"mt-4 text-center text-xs text-text-muted",children:D?"If the browser blocked or closed the tab, reopen authorization.":"OpenFox stays open while you complete authorization in the other tab."})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"mt-6 text-sm text-text-secondary leading-relaxed bg-bg-primary p-4 rounded-lg border border-border",children:v.instructions}),i.jsx("div",{className:"mt-6 flex gap-3",children:i.jsx("button",{type:"button",onClick:_e,className:"w-full rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:D?"Reopen authorization":"Open authorization"})})]})]})}),p&&x&&i.jsx(y2,{isOpen:!0,onClose:tt,onSave:_t,initialStep:2,editProvider:{id:p.providerId,name:(Ke==null?void 0:Ke.name)??"",url:(Ke==null?void 0:Ke.url)??"",backend:(Ke==null?void 0:Ke.backend)??"unknown",apiKey:Ke==null?void 0:Ke.apiKey,isLocal:Ke==null?void 0:Ke.isLocal,thinkingField:Ke==null?void 0:Ke.thinkingField,authAdapter:Ke==null?void 0:Ke.authAdapter,transportAdapter:Ke==null?void 0:Ke.transportAdapter,models:Ke==null?void 0:Ke.models},editModelId:p.model.id})]})}function v7(){const e=Al(E=>E.servers),t=Al(E=>E.fetchServers),n=Re(E=>E.currentSession),r=n==null?void 0:n.id,[a,l]=N.useState(!1),[u,c]=N.useState(null),[d,h]=N.useState(new Set),[p,m]=N.useState(new Set),x=N.useRef(null),y=N.useCallback(async()=>{if(r)try{const E=await Se(`/api/sessions/${r}/mcp/overrides`);if(E.ok){const j=await E.json();m(new Set(j.disabledServers??[]))}}catch{}},[r]),w=N.useCallback(async()=>{await t(),await y()},[t,y]);N.useEffect(()=>{const E=()=>w();return window.addEventListener("mcp-servers-changed",E),()=>window.removeEventListener("mcp-servers-changed",E)},[w]),N.useEffect(()=>{y()},[y]),N.useEffect(()=>{a&&y()},[a,y]),qd(x,()=>l(!1));const C=E=>p.has(E.name),_=e.filter(E=>E.status==="connected"&&!C(E)),S=_.length,v=_.reduce((E,j)=>E+j.estimatedTokens,0),b=async(E,j)=>{if(r){c(null),h(T=>new Set(T).add(E));try{const T=new Set(p);j?T.add(E):T.delete(E);const D=await Se(`/api/sessions/${r}/mcp/overrides`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledServers:Array.from(T)})});if(!D.ok){const L=await D.json().catch(()=>({}));throw new Error(L.error??"Toggle failed")}m(T),await t()}catch(T){c(T instanceof Error?T.message:String(T))}finally{h(T=>{const D=new Set(T);return D.delete(E),D})}}};return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>l(!a),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:S>0?`${S} MCP server(s) active`:"No MCP server active",children:[i.jsx("span",{className:"text-sm text-accent-primary whitespace-nowrap",children:S>0?`● ${S} MCP (${ud(v)})`:"MCP"}),i.jsx(yn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:a?180:0})]}),a&&i.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:e.length===0?i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No MCP servers configured"}):e.map(E=>{const j=C(E),T=d.has(E.name);return i.jsx("div",{children:i.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-bg-tertiary",children:[i.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[i.jsx("span",{className:`text-sm ${Vg(j?"disabled":E.status)}`,children:Gg(j?"disabled":E.status)}),i.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:E.name})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[i.jsxs("span",{children:[E.tools.length," tools"]}),E.estimatedTokens>0&&i.jsxs("span",{children:[ud(E.estimatedTokens)," tokens"]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[T&&i.jsx("span",{className:"text-xs text-text-muted animate-pulse",children:"..."}),i.jsx(Yr,{enabled:!j,onClick:()=>b(E.name,!j)})]})]})},E.name)})}),i.jsx("div",{className:"border-t border-border px-3 py-2 flex-shrink-0",children:u?i.jsx("div",{className:"text-xs text-accent-error",children:u}):i.jsxs("span",{className:"text-xs text-text-muted",children:[e.length," server(s) configured"]})})]})]})}function _7(e,t){const n=e.slice(0,t),r=n.lastIndexOf("@");if(r===-1)return null;const a=n.slice(r+1);return a.includes(" ")||a.includes(`
311
+ `,children:[i.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[h.formattedTimestamp,h.sessionName&&i.jsxs(i.Fragment,{children:[" | ",i.jsx("span",{className:"text-accent-primary font-medium",children:h.sessionName})]})]}),i.jsx("div",{className:"text-sm text-text-primary mt-1",children:h.trimmedContent})]},h.id))})}function H$(){const e=FN(),t=e?"bg-amber-400":"bg-accent-primary";return i.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"flex gap-0.5",children:[i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"0ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"300ms"}})]}),i.jsx("span",{className:"text-text-secondary",children:e?"Running... (abort in progress)":"Running"})]}),!e&&i.jsx("span",{className:"text-text-muted",children:"esc to interrupt"})]})}const U$={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function F$(e,t={}){const n={...U$,...t};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=X$(a),u=`data:${e.type};base64,${l}`,c=await p2(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await V$(e,n)}async function V$(e,t){const n=await W$(e),r=await p2(n),{width:a,height:l}=G$(r.width,r.height,t.maxWidth,t.maxHeight),u=q$();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(r,0,0,a,l);let d=t.quality,h="";for(let m=0;m<10&&(h=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),!(WS(h)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=WS(h);return{dataUrl:h,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function G$(e,t,n,r){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>r?{width:Math.round(r*a),height:r}:{width:e,height:t}}function W$(e){return new Promise((t,n)=>{const r=Y$(),a=new r;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function p2(e){return new Promise((t,n)=>{const r=K$(),a=new r;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function q$(){var t;const e=tx();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function K$(){const e=tx();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function Y$(){const e=tx();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function tx(){return globalThis}function X$(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++){const a=t[r];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function WS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}const qS=50*1024*1024,KS=1024*1024,Q$=["image/png","image/jpeg","image/gif"];function J$(e){return e==="application/pdf"}function Z$(e){return Q$.includes(e.type)}async function e7(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}async function YS(e,t,n){try{if(Zg(e.type)){if(e.size>KS){n(`Text file too large (${Xa(e.size)}). Maximum is ${Xa(KS)}.`);return}const r=await e.text(),a={id:$u(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}else if(Wu(e.type)||J$(e.type)){if(e.size>qS){const r=Wu(e.type)?"Image":"PDF";n(`${r} file too large (${Xa(e.size)}). Maximum is ${Xa(qS)}.`);return}if(Wu(e.type)&&Z$(e)){const r=await F$(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),a={id:$u(),filename:e.name||"unnamed-file",mimeType:r.mimeType,size:r.size,data:r.dataUrl};t(a)}else{const r=await e7(e),a={id:$u(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}}else n(`Unsupported file type: ${e.type}. Supported types: images (PNG, JPG, GIF, WebP, BMP, SVG), PDF, text files, JSON, XML, YAML, and other common text-based formats.`)}catch(r){const a=r instanceof Error?r.message??"Failed to process file":"Failed to process file";n(a)}}function g2(e){const t=Re(l=>l.sendMessage),n=Re(l=>l.launchWorkflow),r=N.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=N.useCallback((l,u,c,d)=>{e(!0),n(l,u,c,d)},[e,n]);return{sendMessage:r,launchWorkflow:a}}function t7({children:e}){return di.createPortal(e,document.body)}function n7(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function r7({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,h]=N.useState(!1),[p,m]=N.useState("commands"),[x,y]=N.useState(""),[w,C]=N.useState(0),[_,S]=N.useState(null),[v,b]=N.useState(null),E=N.useRef(null),j=N.useRef(null),T=mn(ee=>ee.defaults),D=mn(ee=>ee.userItems),L=mn(ee=>ee.projectItems),I=mn(ee=>ee.fetchCommands),P=Ot(ee=>ee.defaults),W=Ot(ee=>ee.userItems),H=Ot(ee=>ee.projectItems),R=Ot(ee=>ee.fetchWorkflows),U=Kr(Kr(T,D),L),V=Kr(Kr(P,W),H);N.useEffect(()=>{d&&(p==="commands"?I():p==="workflows"&&R())},[d,p,I,R]),N.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ee;return(ee=E.current)==null?void 0:ee.focus()}))},[d,p]),N.useEffect(()=>{if(!d)return;const ee=Q=>{var ne;(ne=j.current)!=null&&ne.contains(Q.target)||h(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[d]);const G=ee=>{switch(ee.key){case"ArrowDown":ee.preventDefault(),C(Q=>{const K=(p==="commands"?U:V).filter(B=>{const te=x.toLowerCase();return!te||B.name.toLowerCase().includes(te)});return Math.min(Q+1,K.length-1)});break;case"ArrowUp":ee.preventDefault(),C(Q=>Math.max(Q-1,0));break;case"Enter":ee.preventDefault();break;case"Escape":ee.preventDefault(),h(!1);break}},Z=ee=>{y(ee),C(0)},X=U.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),$=V.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),O=async ee=>{const Q=await mn.getState().fetchCommand(ee);Q&&e(Q.prompt,Q.metadata.agentMode,u,c),h(!1)},M=ee=>{t(ee),h(!1)},q=(ee,Q)=>{Q.stopPropagation(),h(!1),S(ee)},z=(ee,Q)=>{Q.stopPropagation(),h(!1),b(ee)};return i.jsxs("div",{ref:j,className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>h(!d),className:"px-1.5 py-2 rounded-r bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors border-l border-border/50",title:"More options",children:i.jsx(k1,{className:"w-4 h-4"})}),d&&i.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[i.jsxs("div",{className:"flex border-b border-border",children:[i.jsx("button",{type:"button",onClick:()=>{m("commands"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),i.jsx("button",{type:"button",onClick:()=>{m("workflows"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),i.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&i.jsx("div",{className:"p-2 border-b border-border",children:i.jsx("input",{ref:E,value:x,onChange:ee=>Z(ee.target.value),onKeyDown:G,placeholder:p==="commands"?"Search commands...":"Search workflows...",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),i.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:p==="commands"?X.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:U.length===0?"No commands yet":"No matches"}):X.map((ee,Q)=>i.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsx("button",{type:"button",onClick:()=>O(ee.id),className:"flex-1 text-left",children:i.jsx("div",{className:"text-sm text-text-primary font-medium",children:ee.name})}),i.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:ne=>q(ee.id,ne)})]},ee.id)):p==="workflows"?$.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:V.length===0?"No workflows yet":"No matches"}):$.map((ee,Q)=>{const ne=n7(ee),K=ee.color??"#3b82f6";return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsxs("button",{type:"button",onClick:()=>M(ee.id),className:"flex-1 text-left flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:K}}),i.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:ee.name}),ne!==null&&i.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:ne?"#22c55e":"#6b7280"},title:ne?"Entry condition met":"Entry condition not met"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[ee.subGroups&&ee.subGroups.length>0&&i.jsx(s7,{subGroups:ee.subGroups,onSelect:B=>{h(!1),n(ee.id,B)}}),i.jsx(qi,{className:"opacity-0 group-hover:opacity-100",onClick:B=>z(ee.id,B)})]})]},ee.id)}):i.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>{l(),h(!1)},className:"flex items-center gap-2 px-4 py-2 rounded bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary transition-colors",children:[i.jsx(ZN,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm font-medium",children:"Attach file"})]}),i.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),p!=="attach"&&i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{h(!1),p==="commands"?r():a()},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),i.jsx(u2,{isOpen:!!_,onClose:()=>S(null),initialEditId:_}),i.jsx(f2,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function s7({subGroups:e,onSelect:t}){const[n,r]=N.useState(!1),[a,l]=N.useState({top:0,right:0}),u=N.useRef(null),c=N.useRef(null);qd(c,()=>r(!1),n);const d=h=>{if(h.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}r(!n)};return i.jsxs(i.Fragment,{children:[i.jsx("button",{ref:u,type:"button",onClick:d,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&i.jsx(t7,{children:i.jsx("div",{ref:c,onMouseDown:h=>h.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(h=>i.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),t(h)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:h},h))})})]})}function i7({messages:e,onCancel:t}){return e.length===0?null:i.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>i.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[i.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),i.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),i.jsx(ec,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function a7({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:r,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d}){const h=e.allowedTools.filter(p=>!(r!=null&&r.has(p)));return i.jsxs(H1,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),i.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&i.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[h.slice(0,5).map(p=>i.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:p},p)),h.length>5&&i.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",h.length-5," more"]})]})]})}function XS({title:e,agents:t,subagents:n,isBuiltIn:r,alwaysAllowedNames:a,onView:l,onDuplicate:u,onEdit:c,onDelete:d,onCancelDelete:h,isConfirmingDelete:p}){if(t.length===0&&n.length===0)return null;const m=x=>i.jsx(a7,{agent:x,isBuiltIn:r,isConfirmingDelete:(p==null?void 0:p(x.id))??!1,alwaysAllowedNames:a,onView:()=>l(x.id),onEdit:r?void 0:()=>c==null?void 0:c(x.id),onDuplicate:()=>u(x.id),onDelete:r?void 0:()=>d==null?void 0:d(x.id),onCancelDelete:r?void 0:()=>h==null?void 0:h(x.id)},x.id);return i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsxs("div",{className:"space-y-2",children:[t.map(m),n.length>0&&i.jsxs("div",{className:"mt-3",children:[i.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),i.jsx("div",{className:"space-y-2",children:n.map(m)})]})]})]})}function o7(e){const t=new Map;for(const n of e){const r=n.indexOf(":");if(r===-1)t.set(n,new Set);else{const a=n.slice(0,r),u=n.slice(r+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function lp(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function l7({formName:e,formId:t,formDescription:n,formSubagent:r,formTools:a,formColor:l,formPrompt:u,formError:c,saving:d,isReadOnly:h,availableTools:p,onNameChange:m,onIdChange:x,onDescriptionChange:y,onSubagentChange:w,onToolsChange:C,onColorChange:_,onPromptChange:S,onSave:v,onCancel:b,onDuplicate:E}){const j=o7(a),T=p.filter(I=>!(r&&I.topLevelOnly)),D=(I,P)=>{const W=new Map(j),H=W.get(I)||new Set,R=new Set(H);R.has(P)?R.delete(P):R.add(P),R.size===0?W.set(I,new Set):W.set(I,R),C(lp(W))},L=I=>{const P=new Map(j);P.has(I)?P.delete(I):P.set(I,new Set),C(lp(P))};return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3",children:[c&&i.jsx(Qa,{message:c}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(kr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:h}),i.jsx(kr,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(kr,{label:"Description",value:n,onChange:y,placeholder:"What this agent does",readOnly:h}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),i.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[i.jsx("button",{onClick:()=>!h&&w(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${h?"pointer-events-none opacity-60":""}`,children:"Agent"}),i.jsx("button",{onClick:()=>!h&&w(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),i.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),i.jsx("input",{type:"color",value:l,onChange:I=>!h&&_(I.target.value),disabled:h,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),i.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:T.map(I=>{const P=j.has(I.name),W=I.actions.length>0,H=j.get(I.name)||new Set;return W?h?i.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[i.jsx("span",{children:I.name}),i.jsx("span",{className:"text-[10px]",children:"*"})]},I.name):i.jsx(Zl,{trigger:i.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${P?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[i.jsx("span",{children:I.name}),W&&i.jsx("span",{className:`text-[10px] ${P&&H.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...I.actions.map(R=>({label:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${I.name}-${R}`,children:[i.jsx("input",{type:"checkbox",id:`${I.name}-${R}`,checked:H.has(R),onChange:()=>D(I.name,R),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),i.jsx("span",{children:R})]}),closeOnClick:!1})),{label:P?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(P)L(I.name);else{const R=new Map(j);R.set(I.name,new Set(I.actions)),C(lp(R))}}}]},I.name):i.jsx("button",{onClick:()=>!h&&L(I.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${P?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none":"cursor-pointer"}`,children:i.jsx("span",{children:I.name})},I.name)})})]})]}),i.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),i.jsx("textarea",{value:u,onChange:I=>!h&&S(I.target.value),readOnly:h,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${h?"opacity-60":""}`})]}),i.jsx(kT,{onCancel:b,onSave:v,saving:d,saveDisabled:!e||!u||h}),h&&i.jsx("div",{className:"flex justify-end mt-2",children:i.jsx("button",{onClick:E,className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})})]})}function c7(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function u7({isOpen:e,onClose:t,initialEditId:n}){const r=mt(de=>de.defaults),a=mt(de=>de.userItems),l=mt(de=>de.loading),u=mt(de=>de.fetchAgents),c=mt(de=>de.fetchAgent),d=mt(de=>de.fetchDefaultContent),h=mt(de=>de.createAgent),p=mt(de=>de.updateAgent),m=mt(de=>de.deleteAgent),[x,y]=N.useState("list"),[w,C]=N.useState(null),[_,S]=N.useState(!1),[v,b]=N.useState(""),[E,j]=N.useState(""),[T,D]=N.useState(""),[L,I]=N.useState(!0),[P,W]=N.useState([]),[H,R]=N.useState("#6b7280"),[U,V]=N.useState(""),[G,Z]=N.useState(""),[X,$]=N.useState(!1),[O,M]=N.useState([]),[q,z]=N.useState(new Set),{requestDelete:ee,clearConfirm:Q,isConfirming:ne}=Wl(),K=de=>{b(de.metadata.name),j(de.metadata.id),D(de.metadata.description),I(de.metadata.subagent),W(de.metadata.allowedTools),R(de.metadata.color??"#6b7280"),V(de.prompt),Z("")},B=(de,he,De)=>{b(de.metadata.name+" (copy)"),j(`${he}-copy-${Date.now()}`),D(de.metadata.description),I(de.metadata.subagent),W(de.metadata.allowedTools),R(de.metadata.color??"#6b7280"),V(de.prompt),Z(""),C(null),S(!1),y("edit")},te=(de,he)=>{K(de),C(he),S(!0),y("edit")};N.useEffect(()=>{e&&(u(),Se("/api/tools").then(de=>de.json()).then(de=>{const he=de.tools||[];z(new Set(he.filter(De=>De.alwaysAllowed).map(De=>De.name))),M(he.filter(De=>!De.alwaysAllowed))}).catch(()=>{M([]),z(new Set)}),n?r.some(he=>he.id===n)?d(n).then(he=>{he&&B(he,n)}):c(n).then(he=>{he&&(K(he),C(n),S(!1),y("edit"))}):(y("list"),C(null),S(!1)))},[e,u,c,d,n]);const se=async de=>{if(r.some(De=>De.id===de)){const De=await d(de);if(!De)return;te(De,de)}else{const De=await c(de);if(!De)return;te(De,de)}},xe=async de=>{const he=await d(de);he&&B(he,de)},oe=()=>{C(null),b(""),j(""),D(""),I(!0),W(["read_file"]),R("#6b7280"),V(""),Z(""),S(!1),y("edit")},Oe=async de=>{const he=await c(de);he&&(K(he),C(de),S(!1),y("edit"))},Me=async de=>{await m(de)},ze=async()=>{const de=w??E;if(!de||!v||!U){Z("Name and prompt are required.");return}$(!0),Z("");const he={metadata:{id:de,name:v,description:T,subagent:L,allowedTools:P.filter(Ue=>!q.has(Ue)),color:H},prompt:U},De=w?await p(w,he):await h(he);if($(!1),!De.success){Z(De.error??"Failed to save agent.");return}n?t():y("list")},$e=()=>{n?t():(y("list"),S(!1))},je=de=>{b(de),w||j(c7(de))},rt=r.filter(de=>de.subagent),Qe=r.filter(de=>!de.subagent),fe=a.filter(de=>de.subagent),ce=a.filter(de=>!de.subagent);return x==="edit"?i.jsx(wt,{isOpen:e,onClose:$e,title:_?`${v}`:w?"Edit Agent":"New Agent",size:"xl",children:i.jsx(l7,{formName:v,formId:E,formDescription:T,formSubagent:L,formTools:P,formColor:H,formPrompt:U,formError:G,saving:X,isReadOnly:_,availableTools:O,onNameChange:je,onIdChange:j,onDescriptionChange:D,onSubagentChange:de=>{I(de),de&&W(he=>he.filter(De=>{var Ue;return!((Ue=O.find(re=>re.name===De))!=null&&Ue.topLevelOnly)}))},onToolsChange:W,onColorChange:R,onPromptChange:V,onSave:ze,onCancel:$e,onDuplicate:()=>{b(v+" (copy)"),j(`${w}-copy-${Date.now()}`),C(null),S(!1)}})}):i.jsx(wt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:i.jsx(D1,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:oe,loading:l,hasItems:r.length>0||a.length>0,children:i.jsxs("div",{className:"space-y-4",children:[r.length>0&&i.jsx(XS,{title:"Built-in",agents:Qe,subagents:rt,isBuiltIn:!0,alwaysAllowedNames:q,onView:se,onDuplicate:xe}),a.length>0&&i.jsx(XS,{title:"Custom",agents:ce,subagents:fe,isBuiltIn:!1,alwaysAllowedNames:q,isConfirmingDelete:de=>ne(de,"delete"),onView:se,onDuplicate:xe,onEdit:Oe,onDelete:de=>{ne(de,"delete")?(Me(de),Q()):ee(de)},onCancelDelete:Q})]})})})}function d7(){const e=Re(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=Re(v=>v.switchMode),n=mt(v=>v.defaults),r=mt(v=>v.userItems),a=mt(v=>v.fetchAgents),l=[...n,...r],[u,c]=N.useState(!1),[d,h]=N.useState(!1),[p,m]=N.useState(null),x=N.useRef(null);N.useEffect(()=>{a()},[a]),qd(x,()=>c(!1));const y=Gl();if(!e)return null;const w=l.filter(v=>!v.subagent),C=w.find(v=>v.id===e),_=(C==null?void 0:C.name)??e,S=Hl(l,e);return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[i.jsx("span",{className:"text-sm font-medium",style:{color:S},children:_}),i.jsx(yn,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&i.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((v,b)=>{const E=v.id===e,j=Hl(l,v.id),T=y.agentSwitching[b],D=T?qu(T):null;return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[i.jsxs("button",{type:"button",onClick:()=>{E||t(v.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"font-medium truncate",style:{color:j},children:v.name}),E&&i.jsx(Pr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),D&&i.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:D})]},v.id)}),i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{c(!1),h(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),i.jsx(u7,{isOpen:d,onClose:()=>{h(!1),m(null)},initialEditId:p})]})}function h7(){const e=Re(r=>r.currentSession),t=Re(r=>r.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return i.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[i.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),i.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function QS({value:e,onChange:t}){return i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",i.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),i.jsx("input",{type:"text",value:e??"",onChange:n=>t(n.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]})}const f7=[8080,11434,8e3,1234];function Yp(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function x2(e){return{name:e.name,url:e.url,backend:e.backend,apiKey:e.apiKey,isLocal:e.isLocal,thinkingField:e.thinkingField,authAdapter:e.authAdapter,transportAdapter:e.transportAdapter,models:e.models}}function m7({model:e,modelConfigs:t,autoConfigState:n,testResults:r,onUpdateConfig:a,onRunAutoConfig:l,onTestParams:u,onShowRaw:c}){var d,h,p,m,x,y,w,C,_,S,v,b,E,j,T,D,L,I,P,W,H,R,U,V,G,Z,X,$,O,M,q,z,ee,Q,ne,K,B,te,se,xe,oe,Oe,Me,ze,$e;return i.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>l(e.id),disabled:n.progress[e.id]==="probing",className:"px-4 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:n.progress[e.id]==="probing"?"Probing...":"Auto-config"}),n.progress[e.id]==="done"&&i.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&i.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),i.jsxs("div",{className:"flex gap-3 items-end",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),i.jsx("input",{type:"number",value:((d=t[e.id])==null?void 0:d.contextWindow)??e.contextWindow,onChange:je=>a(e.id,{contextWindow:parseInt(je.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[i.jsx("input",{type:"checkbox",checked:((h=t[e.id])==null?void 0:h.supportsVision)??!1,onChange:je=>a(e.id,{supportsVision:je.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"thinking"),disabled:(p=r[e.id+"-thinking"])==null?void 0:p.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(m=r[e.id+"-thinking"])!=null&&m.loading?"Testing...":"Test thinking"}),((x=r[e.id+"-thinking"])==null?void 0:x.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((y=r[e.id+"-thinking"])==null?void 0:y.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(w=r[e.id+"-thinking"])==null?void 0:w.error,children:"Fail"}),((C=r[e.id+"-thinking"])==null?void 0:C.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"non-thinking"),disabled:(_=r[e.id+"-non-thinking"])==null?void 0:_.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(S=r[e.id+"-non-thinking"])!=null&&S.loading?"Testing...":"Test non-thinking"}),((v=r[e.id+"-non-thinking"])==null?void 0:v.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((b=r[e.id+"-non-thinking"])==null?void 0:b.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(E=r[e.id+"-non-thinking"])==null?void 0:E.error,children:"Fail"}),((j=r[e.id+"-non-thinking"])==null?void 0:j.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),i.jsxs("details",{className:"group",children:[i.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[i.jsx(yn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),i.jsxs("div",{className:"mt-3 space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((T=t[e.id])==null?void 0:T.thinkingEnabled)??!1,onChange:je=>a(e.id,{thinkingEnabled:je.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((D=t[e.id])==null?void 0:D.thinkingEnabled)&&i.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),(L=e.reasoningEfforts)!=null&&L.length?i.jsx("select",{"aria-label":"Reasoning effort",value:((I=t[e.id])==null?void 0:I.thinkingLevel)??Yp(e.reasoningEfforts),onChange:je=>a(e.id,{thinkingLevel:je.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary",children:e.reasoningEfforts.map(je=>i.jsx("option",{value:je,children:je},je))}):i.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((P=t[e.id])==null?void 0:P.thinkingLevel)??"",onChange:je=>a(e.id,{thinkingLevel:je.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsx(QS,{value:(W=t[e.id])==null?void 0:W.thinkingQueryParams,onChange:je=>a(e.id,{thinkingQueryParams:je})})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((H=t[e.id])==null?void 0:H.nonThinkingEnabled)??!1,onChange:je=>a(e.id,{nonThinkingEnabled:je.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((R=t[e.id])==null?void 0:R.nonThinkingEnabled)&&i.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:i.jsx(QS,{value:(U=t[e.id])==null?void 0:U.nonThinkingQueryParams,onChange:je=>a(e.id,{nonThinkingQueryParams:je})})})]}),i.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),i.jsx("input",{type:"number",step:"0.1",value:((V=t[e.id])==null?void 0:V.temperature)??"",onChange:je=>a(e.id,{temperature:je.target.value?parseFloat(je.target.value):void 0}),placeholder:((Z=(G=t[e.id])==null?void 0:G.defaultTemperature)==null?void 0:Z.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((X=t[e.id])==null?void 0:X.defaultTemperature)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",($=t[e.id])==null?void 0:$.defaultTemperature]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),i.jsx("input",{type:"number",step:"0.05",value:((O=t[e.id])==null?void 0:O.topP)??"",onChange:je=>a(e.id,{topP:je.target.value?parseFloat(je.target.value):void 0}),placeholder:((q=(M=t[e.id])==null?void 0:M.defaultTopP)==null?void 0:q.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((z=t[e.id])==null?void 0:z.defaultTopP)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(ee=t[e.id])==null?void 0:ee.defaultTopP]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),i.jsx("input",{type:"number",value:((Q=t[e.id])==null?void 0:Q.topK)??"",onChange:je=>a(e.id,{topK:je.target.value?parseInt(je.target.value):void 0}),placeholder:((K=(ne=t[e.id])==null?void 0:ne.defaultTopK)==null?void 0:K.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((B=t[e.id])==null?void 0:B.defaultTopK)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(te=t[e.id])==null?void 0:te.defaultTopK]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),i.jsx("input",{type:"number",value:((se=t[e.id])==null?void 0:se.maxTokens)??"",onChange:je=>a(e.id,{maxTokens:je.target.value?parseInt(je.target.value):void 0}),placeholder:((oe=(xe=t[e.id])==null?void 0:xe.defaultMaxTokens)==null?void 0:oe.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((Oe=t[e.id])==null?void 0:Oe.defaultMaxTokens)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Me=t[e.id])==null?void 0:Me.defaultMaxTokens]})]})]})]}),i.jsx("div",{className:"pt-3 border-t border-border",children:i.jsx(p7,{value:(ze=t[e.id])==null?void 0:ze.compactionThreshold,maxTokens:(($e=t[e.id])==null?void 0:$e.contextWindow)??e.contextWindow,onChange:je=>a(e.id,{compactionThreshold:je})})})]})]})}function p7({value:e,maxTokens:t,onChange:n}){const l=Math.min(95,Math.floor((t-5e3)/t*100)),u=Math.min(l,Math.ceil(15e3/t*100)),c=Math.min(e??.85,l/100),[d,h]=N.useState(Math.round(c*100));N.useEffect(()=>{const m=Math.min(e??.85,l/100);h(Math.round(m*100))},[e,l]);const p=Math.floor(t*(d/100));return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-3 mb-1",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Auto-compaction threshold"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"font-mono text-xs text-text-primary",children:[d,"% · ",so(p)]}),i.jsx("button",{type:"button",onClick:()=>{n(void 0),h(Math.round(.85*100))},disabled:e===void 0,className:"text-xs text-accent-primary hover:underline disabled:text-text-muted disabled:no-underline",children:"Default"})]})]}),i.jsx("input",{"aria-label":"Auto-compaction threshold",type:"range",min:u,max:l,step:"1",value:d,onChange:m=>h(Number(m.target.value)),onMouseUp:()=>n(d/100),onTouchEnd:()=>n(d/100),onBlur:()=>n(d/100),onKeyUp:()=>n(d/100),className:"w-full"}),i.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Minimum ",so(15e3)," tokens · maximum ",l,"% · default 85%"]})]})}function y2({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:a,editModelId:l}){const[u,c]=N.useState(r),[d,h]=N.useState(""),[p,m]=N.useState(""),[x,y]=N.useState("unknown"),[w,C]=N.useState(""),[_,S]=N.useState(!1),[v,b]=N.useState(),[E,j]=N.useState(),[T,D]=N.useState(!1),[L,I]=N.useState(null),[P,W]=N.useState([]),[H,R]=N.useState(null),[U,V]=N.useState(!1),[G,Z]=N.useState(""),[X,$]=N.useState({}),[O,M]=N.useState({loading:!1,progress:{}}),[q,z]=N.useState({}),[ee,Q]=N.useState(null),[ne,K]=N.useState(new Set),[B,te]=N.useState(""),[se,xe]=N.useState(null),[oe,Oe]=N.useState("disconnected"),[Me,ze]=N.useState(!1),[$e,je]=N.useState(null),[rt,Qe]=N.useState([]),[fe,ce]=N.useState(!1),[de,he]=N.useState(!1),De=N.useRef(null),Ue=N.useRef(!1),re=N.useRef(null);N.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var ve;return(ve=re.current)==null?void 0:ve.focus()})},[u,e]),N.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current)},[]),N.useEffect(()=>{e&&Se("/api/provider-presets").then(async ve=>ve.ok?await ve.json():{presets:[]}).then(ve=>Qe(ve.presets)).catch(()=>Qe([]))},[e]);function _e(ve,Ve){$(ae=>({...ae,[ve]:{...ae[ve],...Ve}}))}function Le(ve){K(Ve=>new Set(Ve).add(ve.id)),$(Ve=>({...Ve,[ve.id]:{contextWindow:ve.contextWindow,...Ve[ve.id]}}))}function He(ve){if(!ve.trim())return P;const Ve=ve.toLowerCase().split(/\s+/).filter(Boolean);return P.filter(ae=>Ve.every(me=>ae.id.toLowerCase().includes(me)))}N.useEffect(()=>{var ve,Ve;if(e)if(c(r),h((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),y((a==null?void 0:a.backend)??"unknown"),C((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),b(a==null?void 0:a.authAdapter),j(a==null?void 0:a.transportAdapter),I(null),Z((a==null?void 0:a.thinkingField)??""),z({}),Q(null),xe(null),Oe("disconnected"),je(null),ce(!1),he(!1),(ve=a==null?void 0:a.models)!=null&&ve.length){const ae={},me=new Set;for(const Ie of a.models)ae[Ie.id]={contextWindow:Ie.contextWindow,supportsVision:Ie.supportsVision,thinkingEnabled:Ie.thinkingEnabled,thinkingLevel:Ie.thinkingLevel??Yp(Ie.reasoningEfforts),nonThinkingEnabled:Ie.nonThinkingEnabled,thinkingQueryParams:Ie.thinkingQueryParams,nonThinkingQueryParams:Ie.nonThinkingQueryParams,defaultTemperature:Ie.defaultTemperature,defaultTopP:Ie.defaultTopP,defaultTopK:Ie.defaultTopK,defaultMaxTokens:Ie.defaultMaxTokens,temperature:Ie.temperature,topP:Ie.topP,topK:Ie.topK,maxTokens:Ie.maxTokens,compactionThreshold:Ie.compactionThreshold},Ie.selected&&me.add(Ie.id);if(me.size===0)for(const Ie of a.models)me.add(Ie.id);K(me),$(ae),W(a.models),R(l??((Ve=a.models[0])==null?void 0:Ve.id)??null)}else W([]),$({}),R(null),K(new Set)},[e,r,a==null?void 0:a.id,l]),N.useEffect(()=>{const ve=!!v;u===2&&p&&P.length===0&&!T&&!L&&(!ve||oe==="connected")&&Yt(p)},[u,oe]),N.useEffect(()=>{!e||!v||!(a!=null&&a.id)||Ke(a.id)},[e,E,a==null?void 0:a.id]),N.useEffect(()=>{if(!$e)return;const ve=(a==null?void 0:a.id)??se;if(!ve)return;let Ve=!1;const ae=async()=>{const Ie=await Ke(ve);Ve||Ie!=="connected"||(je(null),ce(!1),he(!1),await Yt(p))};ae();const me=window.setInterval(()=>void ae(),2e3);return()=>{Ve=!0,window.clearInterval(me)}},[$e,se,a==null?void 0:a.id]);async function qe(){if(a!=null&&a.id)return a.id;if(se)return se;const ve=await Se("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d||"Provider",url:p,backend:x,authAdapter:v,transportAdapter:E,isLocal:!1,models:[]})});if(!ve.ok)throw new Error("Unable to create provider");const Ve=await ve.json();return xe(Ve.provider.id),Ve.provider.id}async function Ke(ve){const Ve=await Se(`/api/provider-auth/${ve}/status`);if(!Ve.ok)return"error";const ae=await Ve.json(),me=ae.state==="connected"?"connected":ae.state==="pending"?"pending":ae.state==="error"?"error":"disconnected";return Oe(me),me}async function tt(){ze(!0),Oe("pending");try{const ve=await qe(),Ve=await Se(`/api/provider-auth/${ve}/login`,{method:"POST"});if(!Ve.ok)throw new Error("Unable to start provider sign-in");const ae=await Ve.json();je(ae)}catch{Oe("error")}finally{ze(!1)}}async function _t(){var ve;$e!=null&&$e.userCode&&(await((ve=navigator.clipboard)==null?void 0:ve.writeText($e.userCode)),De.current!==null&&window.clearTimeout(De.current),he(!1),requestAnimationFrame(()=>he(!0)),De.current=window.setTimeout(()=>{he(!1),De.current=null},1500))}function It(){$e&&(window.open($e.directUrl??$e.verificationUrl,"_blank","noopener,noreferrer"),ce(!0))}async function Yt(ve){var Ve,ae;D(!0),I(null),W([]);try{const me=new URLSearchParams({url:ve});w&&me.set("apiKey",w),x&&me.set("backend",x);const Ie=E?await Se(`/api/providers/${await qe()}/models`):await Se(`/api/providers/models?${me.toString()}`);if(Ie.ok){const gt=await Ie.json();if((Ve=gt.models)!=null&&Ve.length){W(gt.models),R(((ae=gt.models[0])==null?void 0:ae.id)??null);const vn={};for(const rn of gt.models)vn[rn.id]={contextWindow:rn.contextWindow,thinkingEnabled:!0,thinkingLevel:Yp(rn.reasoningEfforts),defaultTemperature:rn.defaultTemperature,defaultTopP:rn.defaultTopP,defaultTopK:rn.defaultTopK,defaultMaxTokens:rn.defaultMaxTokens};$(vn),gt.models.length===1&&(K(new Set([gt.models[0].id])),R(gt.models[0].id),dt(gt.models[0].id))}}else{const gt=await Ie.json();I(gt.error??`Failed to fetch models from ${ve}`)}}catch(me){I(`Failed to fetch models from ${ve}: ${me instanceof Error?me.message:"Unknown error"}`)}D(!1)}async function dt(ve){M(Ve=>({loading:!0,progress:{...Ve.progress,[ve]:"probing"}}));try{const Ve=await Se("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,apiKey:w||void 0,backend:x||"unknown",models:[{id:ve}]})});if(!Ve.ok){const me=await Ve.json();throw new Error(me.error??"Auto-config failed")}const ae=await Ve.json();for(const me of ae.models){const Ie={};me.contextSource!=="default"&&(Ie.contextWindow=me.contextWindow,Ie.supportsVision=me.supportsVision),me.thinkingConfig&&(Ie.thinkingEnabled=!0,Ie.thinkingQueryParams=JSON.stringify(me.thinkingConfig)),me.nonThinkingConfig&&(Ie.nonThinkingEnabled=!0,Ie.nonThinkingQueryParams=JSON.stringify(me.nonThinkingConfig)),_e(me.id,Ie),M(gt=>({...gt,progress:{...gt.progress,[me.id]:"done"}}))}}catch(Ve){console.error("Auto-config error:",Ve),M(ae=>({...ae,progress:{...ae.progress,[ve]:"error"}}))}finally{M(Ve=>({...Ve,loading:!1}))}}async function kn(ve,Ve){const ae=ve+"-"+Ve;z(me=>({...me,[ae]:{loading:!0}}));try{const me=X[ve],Ie=await Se("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,providerId:(a==null?void 0:a.id)??se??void 0,transportAdapter:E,model:ve,apiKey:w||void 0,backend:x||"unknown",thinkingField:G||void 0,mode:Ve,modelConfig:{temperature:me==null?void 0:me.temperature,topP:me==null?void 0:me.topP,topK:me==null?void 0:me.topK,maxTokens:me==null?void 0:me.maxTokens,supportsVision:me==null?void 0:me.supportsVision,thinkingEnabled:me==null?void 0:me.thinkingEnabled,thinkingLevel:me==null?void 0:me.thinkingLevel,nonThinkingEnabled:me==null?void 0:me.nonThinkingEnabled,thinkingQueryParams:me==null?void 0:me.thinkingQueryParams,nonThinkingQueryParams:me==null?void 0:me.nonThinkingQueryParams}})}),gt=await Ie.json();Ie.ok?z(vn=>({...vn,[ae]:{loading:!1,result:JSON.stringify(gt,null,2),message:gt.message}})):z(vn=>({...vn,[ae]:{loading:!1,error:gt.error??"Test failed"}}))}catch(me){z(Ie=>({...Ie,[ae]:{loading:!1,error:me instanceof Error?me.message:"Request failed"}}))}}function jt(){W([]),$({}),M({loading:!1,progress:{}}),z({}),Q(null),K(new Set),te("")}function Jt(){se&&!Ue.current&&Se(`/api/providers/${se}`,{method:"DELETE"}).catch(ve=>{console.warn("Failed to clean up draft provider",ve)}),t()}function Br(){const ve=d||"Provider",Ve=(a==null?void 0:a.id)??se??`temp-${Date.now()}`;n({id:Ve,name:ve,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:_,thinkingField:G||void 0,authAdapter:v,transportAdapter:E,models:P.map(ae=>{var me,Ie,gt,vn,rn,Ce,Ne,Fe,Ye,ot,nt,xt,sn,Zt,qt,an;return{id:ae.id,name:ae.name,apiModelId:ae.apiModelId,requestBody:ae.requestBody,reasoningEfforts:ae.reasoningEfforts,contextWindow:((me=X[ae.id])==null?void 0:me.contextWindow)??ae.contextWindow,selected:ne.has(ae.id)||void 0,supportsVision:(Ie=X[ae.id])==null?void 0:Ie.supportsVision,thinkingEnabled:(gt=X[ae.id])==null?void 0:gt.thinkingEnabled,thinkingLevel:(vn=X[ae.id])==null?void 0:vn.thinkingLevel,nonThinkingEnabled:(rn=X[ae.id])==null?void 0:rn.nonThinkingEnabled,thinkingQueryParams:(Ce=X[ae.id])==null?void 0:Ce.thinkingQueryParams,nonThinkingQueryParams:(Ne=X[ae.id])==null?void 0:Ne.nonThinkingQueryParams,temperature:(Fe=X[ae.id])==null?void 0:Fe.temperature,topP:(Ye=X[ae.id])==null?void 0:Ye.topP,topK:(ot=X[ae.id])==null?void 0:ot.topK,maxTokens:(nt=X[ae.id])==null?void 0:nt.maxTokens,defaultMaxTokens:(xt=X[ae.id])==null?void 0:xt.defaultMaxTokens,defaultTemperature:(sn=X[ae.id])==null?void 0:sn.defaultTemperature,defaultTopP:(Zt=X[ae.id])==null?void 0:Zt.defaultTopP,defaultTopK:(qt=X[ae.id])==null?void 0:qt.defaultTopK,compactionThreshold:(an=X[ae.id])==null?void 0:an.compactionThreshold}})}),Ue.current=!0,t()}return e?i.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",children:[i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),i.jsx("button",{onClick:Jt,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2].map(ve=>i.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${ve<u?"bg-accent-success":ve===u?"bg-accent-primary":"bg-border"}`},ve))}),u===1&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),i.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[rt.map(ve=>i.jsx("button",{type:"button",onClick:()=>{h(ve.defaults.name??ve.name),m(ve.defaults.url),y(ve.defaults.backend),S(!1),C(""),b(ve.authAdapter),j(ve.transportAdapter),I(null),jt()},className:`p-2 rounded border text-center text-sm transition-colors ${E&&E===ve.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ve.name},ve.id)),i.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),b(void 0),j(void 0),I(null),jt()},className:`p-2 rounded border text-center text-sm transition-colors ${x==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),f7.map(ve=>{const Ve={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},ae={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return i.jsx("button",{type:"button",onClick:()=>{h(me=>me||(ae[ve]??"")),m(me=>me||`http://localhost:${ve}`),y(Ve[ve]??""),S(!0),b(void 0),j(void 0),I(null),jt()},className:`p-2 rounded border text-center text-sm transition-colors ${x===Ve[ve]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ae[ve]??`localhost:${ve}`},ve)})]})]}),!v&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),i.jsx("input",{ref:re,type:"text",value:p,"data-testid":"provider-modal-url",onChange:ve=>{m(ve.target.value),I(null),W([]),$({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),i.jsx("input",{type:"text",autoComplete:"off",value:d,onChange:ve=>h(ve.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!v&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:ve=>C(ve.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!v&&i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:_,onChange:ve=>S(ve.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),i.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[!!v&&i.jsxs("div",{className:"rounded-lg border border-border bg-bg-primary p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-xs text-text-muted",children:"Connect this provider before choosing available models."})]}),oe==="connected"?i.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):i.jsx("button",{type:"button",onClick:()=>void tt(),disabled:Me||oe==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:Me||oe==="pending"?"Connecting...":oe==="error"?"Retry":"Connect"})]}),$e&&i.jsx("div",{className:"mt-4 border-t border-border pt-4",children:$e.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted",children:"Use this code to complete authorization:"}),i.jsx("button",{type:"button",onClick:()=>void _t(),className:"mt-3 w-full rounded-lg border border-accent-primary/40 px-4 py-4 font-mono text-2xl font-semibold tracking-[0.2em] text-accent-primary",children:$e.userCode??"Continue"}),i.jsxs("div",{className:"mt-3 flex gap-2",children:[i.jsx("button",{type:"button",onClick:()=>void _t(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:de?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:It,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:fe?"Reopen authorization":"Open authorization"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted mb-3",children:$e.instructions}),i.jsx("button",{type:"button",onClick:It,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:fe?"Reopen authorization":"Open authorization"})]})})]}),T&&i.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[i.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),L&&i.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[i.jsx("p",{children:L}),i.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),i.jsxs("div",{className:"flex gap-2 mt-2",children:[i.jsx("button",{onClick:()=>Yt(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),i.jsx("button",{onClick:()=>{jt(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),P.length>0&&x&&(!v||oe==="connected")&&i.jsxs(i.Fragment,{children:[ne.size>0&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",ne.size,")"]}),i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),i.jsx("div",{className:"space-y-2",children:P.filter(ve=>ne.has(ve.id)).map(ve=>{var Ve;return i.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[i.jsxs("div",{onClick:()=>R(H===ve.id?null:ve.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:ve.name??ve.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((Ve=X[ve.id])==null?void 0:Ve.contextWindow)??ve.contextWindow).toLocaleString()," ctx"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[O.progress[ve.id]==="probing"?i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):O.progress[ve.id]==="done"?i.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):O.progress[ve.id]==="error"?i.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):v?null:i.jsx("button",{onClick:ae=>{ae.stopPropagation(),dt(ve.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),P.length>1&&i.jsx("button",{onClick:ae=>{ae.stopPropagation();const me=new Set(ne);me.delete(ve.id),K(me),H===ve.id&&R(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),i.jsx(yn,{className:`w-4 h-4 text-text-muted transition-transform ${H===ve.id?"rotate-180":""}`})]})]}),H===ve.id&&i.jsx(m7,{model:ve,modelConfigs:X,autoConfigState:O,testResults:q,onUpdateConfig:_e,onRunAutoConfig:dt,onTestParams:kn,onShowRaw:Q})]},ve.id)})})]}),P.length>1&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),ne.size===0&&i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"This provider has many models available. Select the ones you want to use below."}),i.jsxs("div",{className:"relative mb-2",children:[i.jsx("input",{type:"text",value:B,onChange:ve=>te(ve.target.value),placeholder:"Search models...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),B&&i.jsx("button",{onClick:()=>te(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",He(B).length," of ",P.length," models"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{const ve=new Set(ne),Ve=He(B);for(const ae of Ve)ve.add(ae.id);if(K(ve),$(ae=>{const me={...ae};for(const Ie of Ve)me[Ie.id]={contextWindow:Ie.contextWindow,...me[Ie.id]};return me}),!v)for(const ae of Ve)O.progress[ae.id]!=="probing"&&O.progress[ae.id]!=="done"&&dt(ae.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),i.jsx("button",{onClick:()=>{const ve=new Set(ne),Ve=He(B);for(const ae of Ve)ve.delete(ae.id);K(ve)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),i.jsxs("div",{className:"space-y-1 max-h-48 overflow-y-auto border border-border rounded-lg bg-bg-primary",children:[He(B).map(ve=>{var ae;const Ve=ne.has(ve.id);return i.jsxs("div",{role:"checkbox","aria-checked":Ve,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${Ve?"bg-accent-primary/5":""}`,onClick:()=>{if(Ve){const me=new Set(ne);me.delete(ve.id),K(me)}else Le(ve),v||dt(ve.id)},onKeyDown:me=>{(me.key==="Enter"||me.key===" ")&&(me.preventDefault(),me.currentTarget.click())},children:[i.jsx("input",{type:"checkbox",checked:Ve,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),i.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:ve.name??ve.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((ae=X[ve.id])==null?void 0:ae.contextWindow)??ve.contextWindow).toLocaleString()," ctx"]}),O.progress[ve.id]==="probing"&&i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),O.progress[ve.id]==="done"&&i.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),O.progress[ve.id]==="error"&&i.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},ve.id)}),He(B).length===0&&i.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",B,"”"]})]})]})]})]}),i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[i.jsx("div",{children:u>1&&i.jsx("button",{onClick:()=>{u===2&&jt(),c(u-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:Jt,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u===1?i.jsx("button",{onClick:()=>c(2),disabled:!p,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:"Next — Test & Configure"}):i.jsx("button",{onClick:Br,disabled:O.loading,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:O.loading?"Configuring...":"Save Provider"})]})]})]}),U&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ve=>{ve.target===ve.currentTarget&&V(!1)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),i.jsx("button",{onClick:()=>V(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),i.jsx("input",{type:"text",defaultValue:'{"chat_template_kwargs":{"enable_thinking":false}}',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),i.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",i.jsx("span",{className:"text-text-muted",children:"(override)"})]}),i.jsx("input",{type:"text",value:G,onChange:ve=>Z(ve.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),i.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]})]}),i.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:i.jsx("button",{onClick:()=>V(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})})]})}),ee&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ve=>{ve.target===ve.currentTarget&&Q(null)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[80vh] shadow-2xl flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border shrink-0",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),i.jsx("button",{onClick:()=>Q(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:ee})]})})]}):null}function g7(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function x7(e,t){const n=t.toLowerCase(),r=(e.name??"").toLowerCase(),a=e.id.toLowerCase(),l=a.replace(/-/g," ");return r.includes(n)||a.includes(n)||l.includes(n)}function JS({activeProvider:e,shortModelName:t}){return i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-accent-primary",children:e?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"hidden sm:inline",children:[e.name," • "]}),t]}):t}),i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${e!=null&&e.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:e!=null&&e.isLocal?"local":"api"})]})}function y7({providerId:e,modelConfig:t,isActive:n,isDefault:r,disabled:a,hasSession:l,settingDefault:u,highlighted:c,onModelClick:d,onSetDefault:h,onEditModel:p}){var m;return i.jsxs("div",{className:`flex items-center px-4 py-1.5 text-sm transition-colors group ${c?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${a?"opacity-50 cursor-wait":""} ${n?"text-accent-primary":"text-text-secondary"}`,children:[i.jsx("button",{type:"button",onClick:()=>d(e,t.id),disabled:a,className:"flex-1 truncate text-left",children:t.name??((m=t.id.split("/").pop())==null?void 0:m.replace(/-/g," "))??t.id}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0 ml-2",children:[i.jsx("span",{className:"text-xs text-text-muted",children:g7(t.contextWindow)}),l&&i.jsx("button",{type:"button",onClick:x=>h(x,e,t.id),disabled:u,className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors disabled:opacity-40",title:r?"Default model":"Set as default model",children:r?i.jsx(N1,{className:"w-3.5 h-3.5 text-accent-warning"}):i.jsx(T1,{className:"w-3.5 h-3.5 text-text-muted hover:text-accent-warning"})}),i.jsx("button",{type:"button",onClick:x=>{x.stopPropagation(),p(e,t)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:i.jsx(w1,{className:"w-3 h-3 text-text-muted"})}),n&&i.jsx("span",{className:"text-accent-success flex-shrink-0",title:"Session model",children:i.jsx(Pr,{className:"w-3.5 h-3.5"})})]})]})}function b7(){var Ve;const[,e]=Ln(),t=Re(ae=>ae.currentSession),n=Re(ae=>ae.setSessionProvider),[r,a]=N.useState(!1),[l,u]=N.useState([]),[c,d]=N.useState(null),h=N.useRef(null),[p,m]=N.useState(null),[x,y]=N.useState(!1),[w,C]=N.useState({}),[_,S]=N.useState(null),[v,b]=N.useState(null),[E,j]=N.useState(!1),T=N.useRef(null),[D,L]=N.useState(!1),I=N.useRef(new Set),[P,W]=N.useState(-1),H=N.useRef(null),R=Kt(ae=>ae.providers),U=Kt(ae=>ae.activeProviderId),V=Kt(ae=>ae.defaultModelSelection),G=Kt(ae=>ae.activating),Z=Kt(ae=>ae.activateProvider),X=Kt(ae=>ae.refreshModel),$=Kt(ae=>ae.refreshProviderModels),O=Kt(ae=>ae.setDefaultModel),M=Kt(ae=>ae.fetchConfig),q=Gl();Dl(q.modelSelector,()=>a(ae=>!ae));const z=(t==null?void 0:t.providerId)??null,ee=(t==null?void 0:t.providerModel)??null,Q=(V==null?void 0:V.split("/")[0])??null,ne=(V==null?void 0:V.split("/").slice(1).join("/"))??null,K=z??Q,B=ee??ne,te=B?((Ve=B.split("/").pop())==null?void 0:Ve.replace(/-/g," "))??B:"No model",[se,xe]=N.useState(!1),[oe,Oe]=N.useState(""),Me=N.useRef(null);N.useEffect(()=>{function ae(me){h.current&&!h.current.contains(me.target)&&(a(!1),u([]),I.current=new Set)}return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[]),N.useEffect(()=>()=>{T.current!==null&&window.clearTimeout(T.current)},[]),N.useEffect(()=>{r||(Oe(""),W(-1))},[r]),N.useEffect(()=>{var ae;r&&((ae=Me.current)==null||ae.focus())},[r]),N.useEffect(()=>{P>=0&&H.current&&H.current.scrollIntoView({block:"nearest"})},[P]),N.useEffect(()=>{if(r){const ae=R.map(me=>me.id);u(ae),R.filter(me=>!!me.authAdapter).forEach(me=>void De(me.id)),ae.forEach(me=>{I.current.has(me)||(I.current.add(me),Qe(me))})}},[r,R]),N.useEffect(()=>{if(!v)return;let ae=!1;const me=async()=>{const gt=await De(v.providerId);ae||gt==="connected"&&(b(null),j(!1),L(!1),await M(),I.current.delete(v.providerId),await Qe(v.providerId))};me();const Ie=window.setInterval(()=>void me(),2e3);return()=>{ae=!0,window.clearInterval(Ie)}},[v]);const ze=R.find(ae=>ae.id===K),$e=(ze==null?void 0:ze.status)==="disconnected",je=(ae,me)=>t?t.providerId===ae&&t.providerModel===me:!1,rt=(ae,me)=>V?V===`${ae}/${me}`:!1,Qe=async ae=>{d(ae);try{await $(ae)}catch{}finally{d(null)}},fe=ae=>{l.includes(ae.id)?u(l.filter(me=>me!==ae.id)):(u([...l,ae.id]),Qe(ae.id))},ce=async ae=>{if(ae.id===U){fe(ae);return}t?(n(ae.id,void 0),a(!1),u([])):await Z(ae.id)&&(a(!1),u([]))},de=ae=>{fe(ae)},he=async(ae,me)=>{ae.stopPropagation(),I.current.delete(me),await Qe(me)},De=async ae=>{const me=await Se(`/api/provider-auth/${ae}/status`);if(!me.ok)return"error";const Ie=await me.json();return C(gt=>({...gt,[ae]:Ie.state})),Ie.state},Ue=async(ae,me)=>{ae.stopPropagation(),S(me),C(Ie=>({...Ie,[me]:"pending"})),j(!1),L(!1);try{const Ie=await Se(`/api/provider-auth/${me}/login`,{method:"POST"});if(!Ie.ok)throw new Error("Unable to start provider sign-in");const gt=await Ie.json();b({providerId:me,...gt})}catch{C(Ie=>({...Ie,[me]:"error"}))}finally{S(null)}},re=async()=>{var ae;v!=null&&v.userCode&&(await((ae=navigator.clipboard)==null?void 0:ae.writeText(v.userCode)),T.current!==null&&window.clearTimeout(T.current),j(!1),requestAnimationFrame(()=>j(!0)),T.current=window.setTimeout(()=>{j(!1),T.current=null},1500))},_e=()=>{v&&(window.open(v.directUrl??v.verificationUrl,"_blank","noopener,noreferrer"),L(!0))},Le=()=>{b(null),j(!1),L(!1)},He=async(ae,me)=>{ae.stopPropagation(),S(me);try{if(!(await Se(`/api/provider-auth/${me}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");C(gt=>({...gt,[me]:"disconnected"})),await M()}finally{S(null)}},qe=(ae,me)=>{m({providerId:ae,model:me}),y(!0)},Ke=p?R.find(ae=>ae.id===p.providerId):void 0,tt=()=>{m(null),y(!1)},_t=async ae=>{try{if(!(await Se(`/api/providers/${ae.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(x2(ae))})).ok)throw new Error("Failed to update provider");await Kt.getState().fetchConfig()}catch{}m(null),y(!1)},It=async(ae,me)=>{if(t){Re.setState(gt=>({currentSession:gt.currentSession?{...gt.currentSession,providerId:ae,providerModel:me}:null})),n(ae,me),u([]),a(!1),Ul();return}await Z(ae)&&(u([]),a(!1),Ul())},Yt=async(ae,me,Ie)=>{ae.stopPropagation(),xe(!0);try{await O(me,Ie)}catch{}finally{xe(!1)}};function dt(ae){return ae.models.some(Ie=>Ie.selected)?ae.models.filter(Ie=>Ie.selected):ae.models}const kn=N.useMemo(()=>oe.trim()?R.map(ae=>({provider:ae,models:dt(ae).filter(me=>x7(me,oe))})).filter(ae=>ae.models.length>0):R.map(ae=>({provider:ae,models:dt(ae)})),[R,oe]),jt=N.useMemo(()=>kn.flatMap(ae=>ae.models.map(me=>({providerId:ae.provider.id,modelConfig:me}))),[kn]),Jt=jt.length+1,Br=P===jt.length;N.useEffect(()=>{Jt===1?W(-1):P>=Jt?W(Jt-1):P<0&&oe.trim()&&W(0)},[Jt,P,oe]);const ve=ae=>{switch(ae.key){case"Escape":a(!1);break;case"ArrowDown":ae.preventDefault(),Jt>0&&W(me=>me<Jt-1?me+1:0);break;case"ArrowUp":ae.preventDefault(),Jt>0&&W(me=>me>0?me-1:Jt-1);break;case"Home":ae.preventDefault(),W(0);break;case"End":ae.preventDefault(),W(Jt-1);break;case"Enter":if(ae.preventDefault(),P===jt.length)e("/onboarding"),a(!1);else if(P>=0&&P<jt.length){const me=jt[P];me&&It(me.providerId,me.modelConfig.id)}break}};return R.length===0?i.jsxs("button",{type:"button",onClick:()=>X(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:$e?"LLM server is offline. Click to retry.":te??"Click to refresh model",children:[$e?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):i.jsx(JS,{activeProvider:ze,shortModelName:te}),i.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):i.jsxs("div",{className:"relative",ref:h,children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[$e?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):i.jsx(JS,{activeProvider:ze,shortModelName:te}),i.jsx(yn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:r?180:0})]}),r&&i.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[i.jsxs("div",{className:"flex items-center gap-1 px-3 py-2 border-b border-border flex-shrink-0",children:[i.jsx(Wi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("input",{ref:Me,type:"text",value:oe,onInput:ae=>{Oe(ae.currentTarget.value),W(-1)},onKeyDown:ve,placeholder:"Search models...",className:"bg-transparent border-none outline-none text-sm text-text-primary w-full placeholder:text-text-muted"})]}),i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:i.jsxs("div",{children:[kn.map(ae=>{const me=oe.trim().length>0||l.includes(ae.provider.id);return i.jsxs("div",{children:[i.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${ae.provider.id===K?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${G?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[i.jsxs("div",{onClick:()=>!G&&ce(ae.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[i.jsx("span",{className:`text-sm font-medium truncate ${ae.provider.id===K?"text-accent-primary":"text-text-primary"}`,children:ae.provider.name}),i.jsx("span",{className:"text-xs text-text-muted truncate",children:ae.provider.backend!=="unknown"&&f1(ae.provider.backend)})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!ae.provider.authAdapter&&(w[ae.provider.id]==="connected"||ae.provider.credentialRef?i.jsx("button",{type:"button",onClick:Ie=>He(Ie,ae.provider.id),disabled:_===ae.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-success/40 text-accent-success hover:bg-accent-success/10 disabled:opacity-50",title:"Disconnect provider account",children:"Connected"}):i.jsx("button",{type:"button",onClick:Ie=>Ue(Ie,ae.provider.id),disabled:_===ae.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-primary/40 text-accent-primary hover:bg-accent-primary/10 disabled:opacity-50",title:"Connect provider account",children:_===ae.provider.id?"Starting…":w[ae.provider.id]==="error"||w[ae.provider.id]==="expired"?"Retry":"Connect"})),ae.provider.id===K?i.jsx("span",{className:"text-accent-success",title:"Active provider",children:i.jsx(Pr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-4"}),i.jsx("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),he(Ie,ae.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:i.jsx(Sd,{className:`w-4 h-4 ${c===ae.provider.id?"animate-spin":""} ${ae.provider.id===U?"text-accent-primary":"text-text-muted"}`})}),i.jsx("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),de(ae.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:i.jsx(yn,{className:`w-4 h-4 transition-transform ${me?"rotate-180":""} ${ae.provider.id===U?"text-accent-primary":"text-text-muted"}`})})]})]}),me&&i.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===ae.provider.id?i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):ae.models.length>0?ae.models.map(Ie=>{const vn=jt.findIndex(rn=>rn.providerId===ae.provider.id&&rn.modelConfig.id===Ie.id)===P;return i.jsx("div",{ref:vn?H:void 0,children:i.jsx(y7,{providerId:ae.provider.id,modelConfig:Ie,isActive:je(ae.provider.id,Ie.id),isDefault:rt(ae.provider.id,Ie.id),disabled:c==="activating",hasSession:!!t,settingDefault:se,highlighted:vn,onModelClick:It,onSetDefault:Yt,onEditModel:qe})},`${ae.provider.id}/${Ie.id}`)}):i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},ae.provider.id)}),kn.length===0&&oe.trim()&&i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No models match your search"})]})}),i.jsx("div",{className:`border-t border-border px-3 py-2 ${Br?"bg-bg-tertiary":""} flex-shrink-0`,children:i.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),v&&i.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/70 px-4",role:"dialog","aria-modal":"true","aria-labelledby":"provider-device-title",onMouseDown:ae=>{ae.target===ae.currentTarget&&Le()},children:i.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border bg-bg-secondary p-6 shadow-2xl",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h2",{id:"provider-device-title",className:"text-lg font-semibold text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-sm text-text-muted",children:"Follow the provider instructions to complete authorization."})]}),i.jsx("button",{type:"button",onClick:Le,className:"rounded px-2 py-1 text-xl leading-none text-text-muted hover:bg-bg-tertiary hover:text-text-primary","aria-label":"Close",children:"×"})]}),v.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:re,className:"mt-6 w-full select-all rounded-lg border border-accent-primary/40 bg-bg-primary px-4 py-5 font-mono text-3xl font-semibold tracking-[0.2em] text-accent-primary hover:bg-bg-tertiary",title:"Copy code",children:v.userCode??"Continue"}),i.jsx("div",{className:"mt-3 text-center text-xs text-text-muted",children:E?"Copied to clipboard":"Click the code to copy it"}),i.jsxs("div",{className:"mt-6 flex gap-3",children:[i.jsx("button",{type:"button",onClick:re,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:E?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:_e,className:"flex-1 rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:D?"Reopen authorization":"Open authorization"})]}),i.jsx("p",{className:"mt-4 text-center text-xs text-text-muted",children:D?"If the browser blocked or closed the tab, reopen authorization.":"OpenFox stays open while you complete authorization in the other tab."})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"mt-6 text-sm text-text-secondary leading-relaxed bg-bg-primary p-4 rounded-lg border border-border",children:v.instructions}),i.jsx("div",{className:"mt-6 flex gap-3",children:i.jsx("button",{type:"button",onClick:_e,className:"w-full rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:D?"Reopen authorization":"Open authorization"})})]})]})}),p&&x&&i.jsx(y2,{isOpen:!0,onClose:tt,onSave:_t,initialStep:2,editProvider:{id:p.providerId,name:(Ke==null?void 0:Ke.name)??"",url:(Ke==null?void 0:Ke.url)??"",backend:(Ke==null?void 0:Ke.backend)??"unknown",apiKey:Ke==null?void 0:Ke.apiKey,isLocal:Ke==null?void 0:Ke.isLocal,thinkingField:Ke==null?void 0:Ke.thinkingField,authAdapter:Ke==null?void 0:Ke.authAdapter,transportAdapter:Ke==null?void 0:Ke.transportAdapter,models:Ke==null?void 0:Ke.models},editModelId:p.model.id})]})}function v7(){const e=Al(E=>E.servers),t=Al(E=>E.fetchServers),n=Re(E=>E.currentSession),r=n==null?void 0:n.id,[a,l]=N.useState(!1),[u,c]=N.useState(null),[d,h]=N.useState(new Set),[p,m]=N.useState(new Set),x=N.useRef(null),y=N.useCallback(async()=>{if(r)try{const E=await Se(`/api/sessions/${r}/mcp/overrides`);if(E.ok){const j=await E.json();m(new Set(j.disabledServers??[]))}}catch{}},[r]),w=N.useCallback(async()=>{await t(),await y()},[t,y]);N.useEffect(()=>{const E=()=>w();return window.addEventListener("mcp-servers-changed",E),()=>window.removeEventListener("mcp-servers-changed",E)},[w]),N.useEffect(()=>{y()},[y]),N.useEffect(()=>{a&&y()},[a,y]),qd(x,()=>l(!1));const C=E=>p.has(E.name),_=e.filter(E=>E.status==="connected"&&!C(E)),S=_.length,v=_.reduce((E,j)=>E+j.estimatedTokens,0),b=async(E,j)=>{if(r){c(null),h(T=>new Set(T).add(E));try{const T=new Set(p);j?T.add(E):T.delete(E);const D=await Se(`/api/sessions/${r}/mcp/overrides`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledServers:Array.from(T)})});if(!D.ok){const L=await D.json().catch(()=>({}));throw new Error(L.error??"Toggle failed")}m(T),await t()}catch(T){c(T instanceof Error?T.message:String(T))}finally{h(T=>{const D=new Set(T);return D.delete(E),D})}}};return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>l(!a),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:S>0?`${S} MCP server(s) active`:"No MCP server active",children:[i.jsx("span",{className:"text-sm text-accent-primary whitespace-nowrap",children:S>0?`● ${S} MCP (${ud(v)})`:"MCP"}),i.jsx(yn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:a?180:0})]}),a&&i.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:e.length===0?i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No MCP servers configured"}):e.map(E=>{const j=C(E),T=d.has(E.name);return i.jsx("div",{children:i.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-bg-tertiary",children:[i.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[i.jsx("span",{className:`text-sm ${Vg(j?"disabled":E.status)}`,children:Gg(j?"disabled":E.status)}),i.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:E.name})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[i.jsxs("span",{children:[E.tools.length," tools"]}),E.estimatedTokens>0&&i.jsxs("span",{children:[ud(E.estimatedTokens)," tokens"]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[T&&i.jsx("span",{className:"text-xs text-text-muted animate-pulse",children:"..."}),i.jsx(Yr,{enabled:!j,onClick:()=>b(E.name,!j)})]})]})},E.name)})}),i.jsx("div",{className:"border-t border-border px-3 py-2 flex-shrink-0",children:u?i.jsx("div",{className:"text-xs text-accent-error",children:u}):i.jsxs("span",{className:"text-xs text-text-muted",children:[e.length," server(s) configured"]})})]})]})}function _7(e,t){const n=e.slice(0,t),r=n.lastIndexOf("@");if(r===-1)return null;const a=n.slice(r+1);return a.includes(" ")||a.includes(`
312
312
  `)||a.includes(" ")?null:{query:a,startIndex:r}}const S7=N.forwardRef(function({text:t,cursorPos:n,workdir:r,onSelect:a},l){const u=_7(t,n),[c,d]=N.useState([]),[h,p]=N.useState(!1),[m,x]=N.useState(0),y=N.useRef(null),w=N.useRef([]),C=N.useRef(0),_=N.useRef([]);N.useEffect(()=>{C.current=m},[m]),N.useEffect(()=>{_.current=c},[c]),N.useEffect(()=>{if(!u){d([]);return}const b=setTimeout(()=>{S(u.query)},150);return()=>clearTimeout(b)},[u==null?void 0:u.query,r]);const S=async b=>{p(!0);try{const E=new URLSearchParams({q:b});r&&E.set("workdir",r);const T=await(await Se(`/api/files?${E.toString()}`)).json();d(T),x(0),C.current=0}catch(E){console.error("File search failed:",E),d([])}finally{p(!1)}},v=N.useCallback(b=>{if(!u)return!1;switch(b.key){case"ArrowDown":return b.preventDefault(),x(E=>{var T;const j=Math.min(E+1,_.current.length-1);return w.current[j]&&((T=w.current[j])==null||T.scrollIntoView({block:"nearest"})),j}),C.current=Math.min(C.current+1,_.current.length-1),!0;case"ArrowUp":return b.preventDefault(),x(E=>{var T;const j=Math.max(E-1,0);return w.current[j]&&((T=w.current[j])==null||T.scrollIntoView({block:"nearest"})),j}),C.current=Math.max(C.current-1,0),!0;case"Enter":case"Tab":{const E=_.current;return E[C.current]?(b.preventDefault(),a(E[C.current],u.startIndex),!0):!1}case"Escape":return b.preventDefault(),d([]),!0}return!1},[u,a]);return N.useImperativeHandle(l,()=>({handleKeyDown:v}),[v]),N.useEffect(()=>{if(!u)return;const b=E=>{y.current&&!y.current.contains(E.target)&&d([])};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[u]),u?h?i.jsx("div",{className:"absolute bottom-full left-0 right-0 mb-2 z-50",children:i.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg",children:i.jsx("div",{className:"p-4 text-center",children:i.jsx(hi,{size:"sm"})})})}):c.length===0?null:i.jsx("div",{ref:y,className:"absolute bottom-full left-0 right-0 mb-2 z-50",children:i.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg max-h-64 overflow-y-auto",children:i.jsx("ul",{className:"py-1",children:c.map((b,E)=>i.jsxs("li",{ref:j=>{w.current[E]=j},className:`px-3 py-2 cursor-pointer flex items-center gap-2 text-sm ${E===m?"bg-accent-primary/20 text-text-primary":"text-text-muted hover:bg-bg-tertiary"}`,onClick:()=>{u&&a(b,u.startIndex)},children:[b.type==="directory"?i.jsx(Or,{className:"w-4 h-4 shrink-0"}):i.jsx("span",{className:"w-4 h-4 shrink-0"}),i.jsx("span",{className:"truncate",children:b.path})]},b.path))})})}):null});function w7({input:e,setInput:t,attachments:n,setAttachments:r,dragOver:a,setDragOver:l,errorMessage:u,setErrorMessage:c,scrollContainerRef:d,sessionId:h,sessionMode:p,showHistory:m,history:x,selectedIndex:y,openHistory:w,closeHistory:C,navigateUp:_,navigateDown:S,selectCurrent:v,isAutoScrollActive:b,setAutoScroll:E,onOpenMessageSearch:j,onOpenCommandsModal:T,onOpenWorkflowsModal:D,onSelectWorkflow:L,onSelectWorkflowWithSubGroup:I,clearInput:P}){const W=N.useRef(null),H=N.useRef(null),R=N.useRef(0),U=N.useRef(0),V=N.useRef(null),G=_d(),Z=Re(ce=>ce.stopGeneration),X=Re(ce=>ce.cancelQueued),$=Re(ce=>ce.queuedMessages),O=Re(ce=>ce.restoredInput),M=Re(ce=>ce.clearRestoredInput),q=Re(ce=>{var de;return(de=ce.currentSession)==null?void 0:de.workdir}),z=Re(ce=>ce.currentSession),ee=N.useRef(!1),{sendMessage:Q}=g2(E);N.useEffect(()=>{var ce;O!==null&&(t(O),M(),(ce=W.current)==null||ce.focus())},[O,t,M]);const ne=N.useCallback(()=>{const ce=W.current;if(!ce)return;const de=e.length>=R.current;R.current=e.length,de||(ce.style.height="auto"),ce.style.height=`${Math.min(200,ce.scrollHeight)}px`},[e]);N.useEffect(()=>{if(!h)return;const ce=`openfox:draft:${h}`,de=localStorage.getItem(ce);de!==null&&t(de)},[h,t]),N.useEffect(()=>{var ce;(ce=W.current)==null||ce.focus(),ne()},[h,ne]),N.useEffect(()=>{if(!h)return;const ce=`openfox:draft:${h}`,de=setTimeout(()=>{e?localStorage.setItem(ce,e):localStorage.removeItem(ce)},500);return()=>clearTimeout(de)},[h,e]),N.useEffect(()=>{ne()},[e,ne]),N.useEffect(()=>{const ce=W.current;if(!ce)return;const de=async he=>{var re;if(document.activeElement!==ce)return;const De=(re=he.clipboardData)==null?void 0:re.items;if(!De)return;const Ue=[];for(const _e of Array.from(De)){let Le=_e.getAsFile();if(Le&&i$(Le.type)){if(he.preventDefault(),!Le.name){const He=s$(Le.type);Le=new File([Le],`pasted-file.${He}`,{type:Le.type})}await YS(Le,He=>Ue.push(He),c)}}Ue.length>0&&r(_e=>[..._e,...Ue])};return ce.addEventListener("paste",de),()=>ce.removeEventListener("paste",de)},[r,c]);const K=ce=>{ce.preventDefault(),!(!e.trim()&&n.length===0)&&(Q(e,n.length>0?n:void 0),P())},B=ce=>{var de;if(!((de=V.current)!=null&&de.handleKeyDown(ce))){if(m)switch(ce.key){case"Enter":{ce.preventDefault();const he=v();he&&(t(he),C());return}case"Escape":ce.preventDefault(),C(),G&&Z();return;case"ArrowUp":ce.preventDefault(),_();return;case"ArrowDown":ce.preventDefault(),S();return}if(ce.key==="ArrowUp"&&e.trim()===""&&!m){ce.preventDefault(),w();return}ce.key==="Enter"&&!ce.shiftKey&&(ce.preventDefault(),K(ce))}};async function te(ce,de,he){const De=[];for(const Ue of Array.from(ce))await YS(Ue,re=>De.push(re),he);De.length>0&&de(Ue=>[...Ue,...De])}const se=N.useCallback(async ce=>{const de=ce.target.files;!de||de.length===0||(c(null),await te(de,r,c),H.current&&(H.current.value=""))},[r,c]),xe=N.useCallback(ce=>{var de;(de=ce.dataTransfer.types)!=null&&de.includes("Files")&&(ce.preventDefault(),ce.stopPropagation(),l(!0))},[l]),oe=N.useCallback(ce=>{ce.preventDefault(),ce.stopPropagation(),l(!1)},[l]),Oe=N.useCallback(async ce=>{ce.preventDefault(),ce.stopPropagation(),l(!1),c(null);const de=ce.dataTransfer.files;!de||de.length===0||await te(de,r,c)},[r,l,c]),Me=N.useCallback(ce=>{r(n.filter(de=>de.id!==ce))},[n,r]),ze=N.useCallback(()=>{var ce;(ce=H.current)==null||ce.click()},[]),$e=()=>{var ce;!e.trim()&&n.length===0||((ce=d.current)==null||ce.scrollTo({top:d.current.scrollHeight,behavior:"smooth"}),Q(e,n),P())},je=N.useCallback((ce,de)=>{const De=ce.type==="directory"?"/":" ",Ue=e.slice(0,de),re=e.slice(U.current),_e=`${Ue}@${ce.path}${De}${re}`;t(_e);const Le=de+ce.path.length+2;U.current=Le,W.current&&(W.current.selectionStart=Le,W.current.selectionEnd=Le,W.current.focus())},[e,t]),rt=N.useCallback(ce=>{const de=ce.target.value;t(de),m&&C(),U.current=ce.target.selectionStart,!ee.current&&h&&de&&z&&z.messages.length===0&&(ee.current=!0,Se(`/api/sessions/${h}/warmup`,{method:"POST"}).catch(()=>{}))},[t,m,C,h,z]),Qe=N.useCallback(ce=>{U.current=ce.target.selectionStart},[]),fe=N.useCallback(ce=>{U.current=ce.currentTarget.selectionStart},[]);return i.jsxs("form",{onSubmit:K,className:"relative p-2 md:p-4 bg-secondary",children:[G&&i.jsx("div",{className:"absolute -top-8 left-2 md:left-4 z-10",children:i.jsx(H$,{})}),i.jsxs("div",{className:`absolute -top-8 right-2 md:right-4 z-10 flex items-center gap-2 border${b?" border-transparent":" rounded backdrop-blur-xl saturate-150 border-border"}`,children:[i.jsx(Kg,{isActive:b,onToggle:E,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),i.jsxs("button",{type:"button",onClick:j,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Browse history",children:[i.jsx(Wi,{}),"Browse history"]})]}),i.jsx("input",{ref:H,type:"file",accept:"image/*,text/*,.pdf,.json,.xml,.yaml,.yml,.js,.sh,.xhtml",onChange:se,className:"hidden",multiple:!0}),u&&i.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:u}),n.length>0&&i.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:n.map(ce=>i.jsx($$,{attachment:ce,onRemove:Me},ce.id))}),m&&i.jsx(z$,{history:x,selectedIndex:y,onSelect:ce=>{t(ce),C()},onEscape:C,onNavigate:ce=>{ce==="up"?_():S()}}),i.jsx(i7,{messages:$,onCancel:X}),i.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${a?"bg-accent-primary/10":"bg-primary"}`,onDragOver:xe,onDragLeave:oe,onDrop:Oe,children:[i.jsxs("div",{className:"relative flex-1 min-w-0",children:[i.jsx("textarea",{id:Ek,ref:W,value:e,onChange:rt,onKeyDown:B,onSelect:Qe,onKeyUp:fe,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",className:"w-full bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:"24px",maxHeight:"200px"},spellCheck:!1}),i.jsx(S7,{ref:V,text:e,cursorPos:U.current,workdir:q,onSelect:je})]}),i.jsxs("div",{className:"flex items-center self-center gap-1.5",children:[G&&i.jsxs("button",{type:"button",onClick:()=>Z(),"data-testid":"chat-stop-button",className:"flex items-center gap-1 px-4 py-1.5 rounded bg-accent-error/20 text-sm text-accent-error font-medium hover:bg-accent-error/30 transition-colors whitespace-nowrap",children:[i.jsx(ng,{}),"Abort"]}),i.jsxs("div",{className:"flex items-center",children:[i.jsx("button",{type:"button",onClick:$e,disabled:!e.trim()&&n.length===0,"data-testid":"chat-send-button",className:"px-4 py-1.5 rounded-l bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:"Send"}),i.jsx(r7,{onSendCommand:async(ce,de,he,De)=>{var re;de&&p!==de&&await Re.getState().switchMode(de);const Ue=he&&he.trim()?`${he.trim()}
313
313
 
314
314
  ${ce}`:ce;(re=d.current)==null||re.scrollTo({top:d.current.scrollHeight,behavior:"smooth"}),Q(Ue,De!=null&&De.length?De:void 0,{messageKind:"command",isSystemGenerated:!0}),P()},onSelectWorkflow:L,onSelectWorkflowWithSubGroup:I,onOpenCommandsManager:T,onOpenWorkflowsManager:D,onAttach:ze,textareaContent:e,attachments:n.length>0?n:void 0})]})]})]}),i.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(d7,{}),i.jsx(h7,{})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[Ht(ce=>ce.settings)[Te.FEATURES_PER_SESSION_MCP]==="true"&&i.jsx(v7,{}),i.jsx(b7,{})]})]})]})}const ZS=9999,Bu=N.forwardRef(function({trigger:t,children:n},r){const[a,l]=N.useState(!1),u=N.useRef(null),c=N.useRef(null),d=N.useRef(null),h=N.useCallback(()=>{l(!1)},[]);N.useImperativeHandle(r,()=>({close:h}),[h]);const p=N.useCallback(m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),a?h():(d.current=document.activeElement,l(!0))),m.key==="Escape"&&a&&h()},[a,h]);return N.useEffect(()=>{var w;if(!a){(w=d.current)==null||w.focus(),d.current=null;return}const m=C=>{c.current&&!c.current.contains(C.target)&&u.current&&!u.current.contains(C.target)&&h()},x=C=>{C.key==="Escape"&&h()},y=()=>h();return document.addEventListener("mousedown",m),document.addEventListener("keydown",x),window.addEventListener("blur",y),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",x),window.removeEventListener("blur",y)}},[a,h]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:u,role:"button",tabIndex:0,"aria-expanded":a,className:"inline-flex cursor-pointer text-text-muted hover:text-text-primary transition-colors outline-none focus-visible:ring-1 focus-visible:ring-accent-primary/50 rounded",onClick:()=>{a||(d.current=document.activeElement),l(m=>!m)},onKeyDown:p,children:t}),a&&di.createPortal(i.jsx("div",{ref:c,role:"dialog","aria-modal":"true",className:"fixed bg-bg-secondary border border-border rounded-lg shadow-xl p-3 w-[320px] max-w-[calc(100vw-16px)] max-h-[60vh] overflow-y-auto",style:(()=>{if(!u.current)return{zIndex:ZS,top:0,left:0};const m=u.current.getBoundingClientRect(),x=320,y=8;let w=m.left;return w+x>window.innerWidth-y&&(w=m.right-x),w=Math.max(y,Math.min(w,window.innerWidth-x-y)),{zIndex:ZS,top:m.bottom+4,left:w}})(),children:n}),document.body)]})});function C7({entries:e}){const t=new Map;for(const r of e)t.set(r.status,(t.get(r.status)??0)+1);const n=Bk.filter(r=>(t.get(r)??0)>0);return n.length===0?i.jsx("span",{className:"text-text-muted text-sm",children:"None"}):i.jsx("span",{className:"flex items-center gap-1.5 text-sm",children:n.map(r=>i.jsxs("span",{className:"flex items-center gap-0.5",children:[i.jsx(po,{status:r}),i.jsx("span",{className:"text-text-muted",children:t.get(r)})]},r))})}function k7({visible:e}){const t=Re(B=>B.currentSession),n=Qn(B=>B.status),r=Qn(B=>B.config),a=Qn(B=>B.start),l=Re(B=>B.contextState),u=Re(B=>B.queueUpdate),c=Qn(B=>B.logs),{branch:d,diff:h}=Wg(),[p,m]=N.useState(!1),[x,y]=N.useState(!1),[w,C]=N.useState(!1),[_,S]=N.useState(null),[v,b]=N.useState(!1),[E,j]=N.useState(!1),T=N.useRef(null),D=N.useRef(null),L=N.useRef(null),I=N.useRef(null),P=Ht(B=>B.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true";if(!e||!t)return null;const W=t.workspace?t.workspace.split("/").pop()??"original":"original",H=t.workspace??t.workdir,R=t.metadataEntries??{},U=R.criteria??[],V=["review_findings","todos"],G=V.filter(B=>{var te;return B in R&&(((te=R[B])==null?void 0:te.length)??0)>0}),Z=Object.keys(R).filter(B=>B!=="criteria"&&!V.includes(B)).filter(B=>{var te;return(((te=R[B])==null?void 0:te.length)??0)>0}),X=[...G,...Z].reduce((B,te)=>{var se;return B+(((se=R[te])==null?void 0:se.length)??0)},0),$=[...G,...Z].map(to),O=h.files,M=O.reduce((B,te)=>B+te.additions,0),q=O.reduce((B,te)=>B+te.deletions,0),z=(n==null?void 0:n.state)??"off",ee=z==="running"||z==="warning",Q=r!==null,ne=B=>{B.stopPropagation(),a()},K=B=>{B.stopPropagation(),n!=null&&n.url&&window.open(n.url,"_blank")};return i.jsxs("div",{className:"flex-shrink-0 px-4 py-1.5 border-b border-border bg-secondary",children:[i.jsxs("div",{className:"grid grid-cols-2 sm:flex sm:items-center sm:justify-between gap-x-2 gap-y-1 text-sm",children:[i.jsxs("div",{className:"flex items-center gap-1 min-w-0 sm:shrink-0",children:[i.jsx(Or,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary max-w-[120px]",children:W}),i.jsx("span",{className:"text-text-muted",children:"/"}),i.jsx(Vi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary max-w-[120px]",children:d??"-"}),O.length>0?i.jsxs("span",{className:"text-text-muted shrink-0 font-mono",children:["+",M," -",q]}):i.jsx("span",{className:"shrink-0"}),i.jsx(Bu,{ref:I,trigger:i.jsx(yn,{className:"w-3 h-3"}),children:i.jsx(Zk,{workspaceName:W,branch:d,workdir:H,showEditorLink:P,sessionId:t.id,projectId:t.projectId,onEditWorkspace:()=>{var B;(B=I.current)==null||B.close(),b(!0)},onEditBranch:()=>{var B;(B=I.current)==null||B.close(),j(!0)}})})]}),i.jsx("div",{className:"hidden sm:block w-px bg-border self-stretch mx-1"}),i.jsxs("div",{className:"flex-1 flex items-center sm:justify-center justify-self-end gap-1 min-w-0",children:[i.jsx(C7,{entries:U}),X>0&&i.jsxs("span",{className:"text-text-muted text-xs bg-bg-tertiary px-1 py-0.5 rounded leading-none",title:$.join(", "),children:["+",X]}),i.jsx(Bu,{ref:L,trigger:i.jsx(yn,{className:"w-3 h-3"}),children:i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var B;(B=L.current)==null||B.close(),S("criteria")},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(fd,{entries:U,title:"Acceptance Criteria"})}),i.jsx(Hk,{entries:U,sessionId:t.id})]}),[...G,...Z].map(B=>{const te=R[B];return i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var se;(se=L.current)==null||se.close(),S(B)},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(fd,{entries:te,title:to(B)})}),i.jsx($k,{entries:te})]},B)})]})})]}),i.jsx("div",{className:"hidden sm:block w-px bg-border self-stretch mx-1"}),i.jsx("div",{className:"col-span-2 border-t border-border sm:hidden -mx-4"}),i.jsx("div",{className:"flex items-center gap-1.5 min-w-0 shrink-0",children:l&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-muted text-xs font-mono tabular-nums",children:l.currentTokens>=1e3?`${Math.round(l.currentTokens/1e3)}K`:l.currentTokens}),i.jsx(Xg,{percent:Math.round(l.currentTokens/l.maxTokens*100),dangerZone:l.dangerZone,size:"sm"}),i.jsx(Bu,{ref:D,trigger:i.jsx(yn,{className:"w-3 h-3"}),children:i.jsx(t2,{onUpdateSystemPrompt:()=>{var B;(B=D.current)==null||B.close(),C(!0)}})})]})}),i.jsx("div",{className:"hidden sm:block w-px bg-border self-stretch mx-1"}),i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 shrink-0 justify-self-end",children:[i.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${z==="running"?"bg-accent-success":z==="warning"?"bg-accent-warning":z==="error"?"bg-accent-error":"bg-text-muted"}`}),Q?ee?i.jsx("button",{onClick:K,className:"flex items-center justify-center p-1 rounded text-sm font-medium bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors leading-none",title:"Open dev server",children:i.jsx(E1,{className:"w-3.5 h-3.5"})}):i.jsx("button",{onClick:ne,className:"flex items-center justify-center p-1 rounded text-sm font-medium bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors leading-none",title:"Start dev server",children:i.jsx(j1,{className:"w-3.5 h-3.5"})}):i.jsx("span",{className:"text-text-muted text-xs",children:"No config"}),i.jsx(Bu,{ref:T,trigger:i.jsx(yn,{className:"w-3 h-3"}),children:i.jsx(Vk,{workdir:H,compact:!0,onExpand:()=>m(!0),onConfigure:()=>{var B;(B=T.current)==null||B.close(),y(!0)}})})]})]}),p&&i.jsx(Yg,{title:"Dev Server Logs",logs:c,onClose:()=>m(!1)}),x&&i.jsx(Uk,{isOpen:!0,onClose:()=>y(!1)}),_&&t&&i.jsx(zk,{isOpen:!0,onClose:()=>S(null),entries:R[_]??[],sessionId:t.id,metadataKey:_,title:to(_)}),v&&i.jsx(Qk,{isOpen:!0,onClose:()=>b(!1),projectId:t.projectId,sessionId:t.id,currentWorkspace:W,currentBranch:d}),E&&i.jsx(Jk,{isOpen:!0,onClose:()=>j(!1),sessionId:t.id}),w&&l&&i.jsx(Qg,{isOpen:!0,onClose:()=>C(!1),isRunning:t.isRunning,onApply:()=>{t.isRunning?u():Pt.send("context.applyDynamic",{}),C(!1)}})]})}function E7(e){return(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="f"&&document.querySelector("[data-global-settings]")===null}function b2(e,t=[]){const n=new Map,r=new Map;for(const h of t)h.type==="message"?n.set(h.message.id,h):h.type==="subagent"&&r.set(h.subAgentId,h);const a=[];let l,u=1,c=null;const d=()=>{if(!c||c.size===0)return;const h=new Map;let p=0;for(const x of e)x.role!=="tool"&&x.contextWindowId===l&&(x.subAgentId&&!h.has(x.subAgentId)&&h.set(x.subAgentId,p),p++);const m=[...c.entries()].sort((x,y)=>(h.get(x[0])??0)-(h.get(y[0])??0));for(const[x,y]of m){const w=r.get(x);(w==null?void 0:w.type)==="subagent"&&w.messages.length===y.messages.length&&w.messages.every((_,S)=>_===y.messages[S])?a.push(w):a.push({type:"subagent",subAgentId:x,subAgentType:y.subAgentType,messages:y.messages})}c=null};for(let h=0;h<e.length;h++){const p=e[h];if(p.role!=="tool")if(p.contextWindowId&&l&&p.contextWindowId!==l&&(d(),u++,a.push({type:"context-divider",windowSequence:u})),l=p.contextWindowId,p.subAgentId&&p.subAgentType){c||(c=new Map);let m=c.get(p.subAgentId);m||(m={subAgentType:p.subAgentType,messages:[]},c.set(p.subAgentId,m)),m.messages.push(p)}else{d();const m=n.get(p.id);(m==null?void 0:m.type)==="message"&&m.message===p?a.push(m):a.push({type:"message",message:p})}}return d(),a}const j7=10,N7=150;function T7(e){const t=[];if(e.recentUserPrompts)for(const n of e.recentUserPrompts)t.push({id:n.id,content:n.content,timestamp:n.timestamp,sessionId:e.id,sessionName:e.title||e.id});return t}function A7(e){return[...e].sort((r,a)=>new Date(a.timestamp).getTime()-new Date(r.timestamp).getTime()).slice(0,j7).reverse().map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,formattedTimestamp:nB(r.timestamp),trimmedContent:dd(r.content,N7),sessionId:r.sessionId,sessionName:r.sessionName}))}function L7(e,t,n){const r=[],a=e.filter(l=>l.role==="user"&&!l.isSystemGenerated&&l.messageKind!=="auto-prompt");for(const l of a)r.push({id:l.id,content:l.content,timestamp:l.timestamp,sessionId:n??"",sessionName:"This session"});for(const l of t)n&&l.id===n||r.push(...T7(l));return A7(r)}function D7(e,t=[],n=null){const[r,a]=N.useState(0),[l,u]=N.useState(!1),c=N.useMemo(()=>L7(e,t,n),[e,t,n]),d=N.useCallback(()=>{c.length>0&&(a(c.length-1),u(!0))},[c.length]),h=N.useCallback(()=>{u(!1),a(0)},[]),p=N.useCallback(()=>{a(y=>c.length===0?y:y===0?c.length-1:y-1)},[c.length]),m=N.useCallback(()=>{a(y=>c.length===0?y:y===c.length-1?0:y+1)},[c.length]),x=N.useCallback(()=>{if(c.length===0||!l)return null;const y=c[r];return(y==null?void 0:y.content)??null},[c,r,l]);return{history:c,selectedIndex:r,showHistory:l,openHistory:d,closeHistory:h,navigateUp:p,navigateDown:m,selectCurrent:x}}N.memo(function({item:t}){const[n,r]=N.useState(!1);return t.type==="start"?i.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-500/10 border border-amber-500/30 rounded text-amber-300 text-sm",children:[i.jsx("span",{className:"animate-pulse",children:"●"}),i.jsx("span",{children:"Delegating image to fallback vision model..."}),t.filename&&i.jsxs("span",{className:"text-amber-400/70",children:["(",t.filename,")"]})]}):i.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-accent-success/10 border border-accent-success/30 rounded",children:[i.jsx("span",{className:"text-accent-success",children:"✓"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"text-accent-success text-sm",children:"Image description done"}),i.jsx("button",{type:"button",onClick:()=>r(!n),className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:n?"Hide":"Show"})]}),n&&t.description&&i.jsx("div",{className:"mt-2 text-xs prose prose-invert prose-sm max-w-none",children:i.jsx(Hn,{content:t.description})})]})]})});function R7({criteriaSidebarOpen:e,onCriteriaSidebarToggle:t,rawMessages:n,hiddenCount:r}={}){const a=e??!0,[l,u]=N.useState(""),[c,d]=N.useState([]),[h,p]=N.useState(!1),[m,x]=N.useState(null),[y,w]=N.useState(!1),[C,_]=N.useState(!1),[S,v]=N.useState(!1),[b,E]=N.useState(!1),[j,T]=N.useState(null),D=N.useRef(null),L=Re(fe=>fe.currentSession),I=Re(fe=>fe.messages),P=Re(fe=>fe.sessions),W=_d(),H=Re(fe=>fe.stopGeneration),R=n??I,{maxVisibleItems:U}=Xi(),V=mt(fe=>fe.defaults),G=mt(fe=>fe.userItems),Z=[...V,...G].filter(fe=>!fe.subagent),{history:X,selectedIndex:$,showHistory:O,openHistory:M,closeHistory:q,navigateUp:z,navigateDown:ee,selectCurrent:Q}=D7(R,P,L==null?void 0:L.id);N.useEffect(()=>{const fe=ce=>{T(ce.detail.stats)};return window.addEventListener("open-turn-stats",fe),()=>window.removeEventListener("open-turn-stats",fe)},[]),N.useEffect(()=>{Ot.getState().fetchWorkflows()},[]),N.useEffect(()=>{const fe=ce=>{E7(ce)&&(ce.preventDefault(),E(!0))};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[]);const ne=N.useRef([]),{displayItems:K,hiddenCount:B}=N.useMemo(()=>{const fe=b2(R,ne.current);return ne.current=fe,U>0&&fe.length>U?{displayItems:fe.slice(-U),hiddenCount:fe.length-U}:{displayItems:fe,hiddenCount:0}},[R,U]),te=r??B,{isAutoScrollActive:se,setAutoScroll:xe}=Wd(D,L),{sendMessage:oe,launchWorkflow:Oe}=g2(xe),Me=N.useCallback((fe,ce)=>{Oe(void 0,void 0,fe,ce)},[Oe]),ze=N.useCallback(fe=>{xe(!1);const ce=document.querySelector(`[data-item-index="${fe}"]`);ce&&ce.scrollIntoView({behavior:"smooth",block:"center"})},[xe]);N.useEffect(()=>{const fe=ce=>{const de=S||y||C||b||j;ce.key==="Escape"&&W&&!de&&H(),ce.key==="ScrollLock"&&xe(!se)};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[W,H,se,S,y,C,b,j]);const $e=Gl();Dl($e.quickAction,()=>{v(!0)}),Dl($e.criteriaSidebar,()=>{t==null||t()}),bT($e.agentSwitching,Z,fe=>{Re.getState().switchMode(fe)});const je=fe=>{const ce=l.trim()?l:void 0,de=c.length>0?c:void 0;Oe(ce,de,fe),Qe()},rt=(fe,ce)=>{const de=l.trim()?l:void 0,he=c.length>0?c:void 0;Oe(de,he,fe,ce),Qe()},Qe=()=>{u(""),d([]),L!=null&&L.id&&localStorage.removeItem(`openfox:draft:${L.id}`)};return i.jsxs(i.Fragment,{children:[i.jsxs(p8,{criteriaSidebarOpen:a,onCriteriaSidebarToggle:t,messages:R,children:[i.jsx(k7,{visible:!a}),i.jsx(g8,{}),j&&i.jsx(x8,{stats:j,onClose:()=>T(null)}),i.jsx(g$,{}),i.jsx(m$,{displayItems:K,scrollContainerRef:D,highlightedMessageId:null,onLaunchWorkflow:Me,onScrollToTop:()=>xe(!1),hiddenCount:te}),i.jsx(w7,{input:l,setInput:u,attachments:c,setAttachments:d,dragOver:h,setDragOver:p,errorMessage:m,setErrorMessage:x,scrollContainerRef:D,sessionId:L==null?void 0:L.id,sessionMode:L==null?void 0:L.mode,showHistory:O,history:X,selectedIndex:$,openHistory:M,closeHistory:q,navigateUp:z,navigateDown:ee,selectCurrent:Q,isAutoScrollActive:se,setAutoScroll:xe,onOpenMessageSearch:()=>E(!0),onOpenCommandsModal:()=>w(!0),onOpenWorkflowsModal:()=>_(!0),onSelectWorkflow:je,onSelectWorkflowWithSubGroup:rt,clearInput:Qe}),i.jsx(u2,{isOpen:y,onClose:()=>w(!1)}),i.jsx(f2,{isOpen:C,onClose:()=>_(!1)}),i.jsx(T$,{isOpen:S,onClose:()=>v(!1),onSearchMessages:()=>E(!0),isAutoScrollActive:se,onToggleAutoScroll:xe,textareaContent:l,onCloseComplete:Ul,onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(fe,ce)=>{const de=await mn.getState().fetchCommand(fe);if(de){const he=ce!=null&&ce.trim()?`${ce.trim()}
315
315
 
316
- ${de.prompt}`:de.prompt;de.metadata.agentMode&&await Re.getState().switchMode(de.metadata.agentMode),oe(he,c!=null&&c.length?c:void 0,{messageKind:"command",isSystemGenerated:!0}),Qe()}},onSelectWorkflow:fe=>{const ce=l.trim()||void 0,de=c.length>0?c:void 0;Oe(ce,de,fe),Qe()}})]}),b&&i.jsx(B$,{isOpen:b,onClose:()=>{E(!1),Ul(!0)},displayItems:K,onNavigate:ze})]})}function O7(){var b;const[,e]=oo("/p/:projectId/s/:sessionId/readonly"),t=e==null?void 0:e.sessionId,[n,r]=N.useState(null),[a,l]=N.useState([]),[u,c]=N.useState(0),[d,h]=N.useState(!0),[p,m]=N.useState(null),x=async()=>{if(t){h(!0),m(null);try{const E=await Se(`/api/sessions/${t}?full=true`);if(!E.ok){m(`Failed to load session (${E.status})`),h(!1);return}const j=await E.json();r(j.session??null),l(j.messages??[]),c(j.hiddenCount??0)}catch(E){m(E instanceof Error?E.message:"Unknown error")}finally{h(!1)}}};N.useEffect(()=>{Ht.getState().getSettings([...Zp])},[]),N.useEffect(()=>{x()},[t]);const{showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S}=Xi(),v=N.useMemo(()=>b2(a),[a]);return d?i.jsx("div",{className:"h-screen flex items-center justify-center bg-primary",children:i.jsx(hi,{})}):p?i.jsx("div",{className:"h-screen flex items-center justify-center bg-primary",children:i.jsxs("div",{className:"text-center space-y-4",children:[i.jsx("div",{className:"text-red-400 text-sm",children:p}),i.jsx("button",{onClick:x,className:"px-3 py-1.5 text-sm bg-bg-tertiary text-text-primary border border-border rounded hover:bg-bg-tertiary/80 transition-colors",children:"Retry"})]})}):i.jsxs("div",{className:"h-screen print:h-auto flex flex-col bg-primary",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-secondary shrink-0 print:hidden",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("h1",{className:"text-sm font-medium text-text-primary truncate",children:[((b=n==null?void 0:n.metadata)==null?void 0:b.title)??"Session"," — Read-only view"]}),i.jsxs("span",{className:"text-xs text-text-muted whitespace-nowrap",children:[a.length," messages",u>0?` (${u} older hidden)`:""]})]}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("button",{onClick:x,disabled:d,className:"px-3 py-1 text-xs bg-bg-tertiary text-text-primary border border-border rounded hover:bg-bg-tertiary/80 transition-colors disabled:opacity-50",children:d?"Refreshing...":"Refresh"})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto print:overflow-visible scrollbar-stable",children:[i.jsx("div",{className:"pt-4",children:i.jsx(c2,{displayItems:v,showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S})}),i.jsx("div",{className:"h-8"})]})]})}function e1({isOpen:e,isRetry:t,onSubmit:n,onCancel:r}){const[a,l]=N.useState(""),u=N.useRef(null);N.useEffect(()=>{e&&(l(""),setTimeout(()=>{var d;return(d=u.current)==null?void 0:d.focus()},100))},[e]);const c=d=>{d.preventDefault(),a.trim()&&n(a)};return i.jsx(wt,{isOpen:e,onClose:r,title:t?"Invalid Password":"Password Required",size:"sm",children:i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsx("p",{className:"text-text-secondary text-sm",children:t?"The password you entered was incorrect. Please try again.":"This server requires a password to connect."}),i.jsx(oi,{ref:u,type:"password",value:a,onChange:d=>l(d.target.value),placeholder:"Enter password",autoFocus:!0}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ze,{type:"button",variant:"secondary",onClick:r,children:"Cancel"}),i.jsx(Ze,{type:"submit",disabled:!a.trim(),children:t?"Try Again":"Connect"})]})]})})}function I7({currentStep:e,totalSteps:t,labels:n,onStepClick:r}){return i.jsx("div",{className:"flex justify-center py-6",children:i.jsx("div",{className:"flex items-center",children:Array.from({length:t},(a,l)=>{const u=l+1,c=u<e,d=u===e;return i.jsxs("div",{className:"flex items-center",children:[i.jsx("button",{onClick:()=>r==null?void 0:r(u),className:`size-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors shrink-0 ${c?"bg-accent-primary text-text-primary hover:opacity-80":d?"bg-accent-primary text-text-primary":"bg-bg-tertiary text-text-muted"}`,children:c?"✓":u}),i.jsx("button",{onClick:()=>r==null?void 0:r(u),className:`ml-2 mr-4 text-sm whitespace-nowrap hidden sm:block ${d?"text-text-primary font-medium":"text-text-muted hover:text-text-secondary"}`,children:n[l]}),l<t-1&&i.jsx("div",{className:`w-12 sm:w-20 h-0.5 mr-4 ${c?"bg-accent-primary":"bg-border"}`})]},l)})})})}function M7({onNext:e}){const[t,n]=N.useState([]),[r,a]=N.useState([]),[l,u]=N.useState(!1),[c,d]=N.useState(null),[h,p]=N.useState(null),[m,x]=N.useState(null);N.useEffect(()=>{y()},[]);async function y(){try{const j=await Se("/api/providers");if(j.ok){const D=(await j.json()).providers.map(L=>({id:L.id,name:L.name,url:L.url,backend:L.backend,model:null,apiKey:L.apiKey,isLocal:L.isLocal,thinkingField:L.thinkingField,models:L.models}));n(D),a(D)}}catch{}}async function w(j){const T=j.id.startsWith("temp-"),D=r.some(P=>P.id===j.id),L=r.length===0&&c===null,I=x2(j);try{let P;if(T){const H=await Se("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!H.ok)throw new Error("Failed to create provider");const R=await H.json();P={...j,id:R.provider.id,model:null}}else{if(!(await Se(`/api/providers/${j.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)})).ok)throw new Error("Failed to update provider");P={...j,model:null}}const W=H=>H.some(R=>R.id===P.id)?H.map(R=>R.id===P.id?P:R):[...H,P];a(W),n(W),L&&!D&&e({providers:[P]})}catch{if(T){const P={...j,model:null};a(W=>[...W,P])}}}function C(){d(null),u(!0)}function _(j){d(j),u(!0)}function S(){u(!1),d(null)}function v(j){p(j),t.some(D=>D.id===j)?Se(`/api/providers/${j}`,{method:"DELETE"}).then(()=>{a(r.filter(D=>D.id!==j)),n(t.filter(D=>D.id!==j)),p(null)}).catch(()=>p(null)):(a(r.filter(D=>D.id!==j)),p(null))}function b(){const j=r.filter(T=>!T.id.startsWith("temp-"));e({providers:j})}const E=r.length>0;return i.jsxs("div",{className:"max-w-xl mx-auto",children:[i.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"LLM Providers"}),i.jsx("p",{className:"text-text-secondary mb-8",children:"Manage your LLM server connections"}),i.jsxs("div",{className:"space-y-4",children:[r.length>0?i.jsx("div",{className:"space-y-2",children:r.map(j=>i.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"px-2 py-0.5 bg-accent-primary/25 text-accent-primary rounded text-xs font-medium",children:f1(j.backend)}),i.jsx("span",{className:"text-text-primary font-medium",children:j.name}),i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${j.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:j.isLocal?"local":"api"})]}),i.jsx("p",{className:"text-text-muted text-sm mt-1 truncate",children:j.url}),j.model&&i.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",j.model]})]}),i.jsx("div",{className:"flex items-center gap-1",children:m===j.id?i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>v(j.id),disabled:h===j.id,className:"px-2 py-1 text-xs text-red-500 hover:text-red-400 bg-red-500/10 rounded transition-colors disabled:opacity-50",children:h===j.id?"Deleting...":"Confirm"}),i.jsx("button",{onClick:()=>x(null),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>_(j),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary border border-border rounded transition-colors",children:"Edit"}),i.jsx("button",{onClick:()=>x(j.id),className:"p-2 text-text-muted hover:text-red-500 transition-colors",title:"Remove provider",children:i.jsx(lo,{})})]})})]},j.id))}):i.jsx("div",{className:"bg-bg-secondary rounded-lg p-8 text-center border border-border",children:i.jsx("p",{className:"text-text-muted",children:"No providers configured yet"})}),i.jsxs("button",{onClick:C,"data-testid":"onboarding-add-provider-button",className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-bg-secondary border border-dashed border-border rounded-lg text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[i.jsx(Es,{className:"w-4 h-4"}),"Add Provider"]}),i.jsx("button",{onClick:b,disabled:!E,"data-testid":"onboarding-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]}),i.jsx(y2,{isOpen:l,onClose:S,onSave:w,initialStep:1,editProvider:c??void 0})]})}function P7({onNext:e}){const[t,n]=N.useState(""),[r,a]=N.useState(!1);return N.useEffect(()=>{Se("/api/config").then(l=>l.json()).then(l=>{l.workdir?n(l.workdir):fetch(ks("/api/directories?path=")+encodeURIComponent("/home")).then(u=>u.json()).then(u=>{u.current&&n(u.current)}).catch(()=>{})}).catch(()=>{fetch(ks("/api/directories?path=")+encodeURIComponent("/home")).then(l=>l.json()).then(l=>{l.current&&n(l.current)}).catch(()=>{})})},[]),i.jsxs("div",{className:"max-w-xl mx-auto",children:[i.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Your Projects Folder"}),i.jsx("p",{className:"text-text-secondary mb-8",children:"Where should OpenFox create project folders?"}),i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Workspace directory"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:t,onChange:l=>n(l.target.value),placeholder:"/home/user/projects","data-testid":"onboarding-workdir-input",className:"flex-1 px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),i.jsx("button",{onClick:()=>a(!0),className:"px-4 py-2 bg-bg-secondary border border-border rounded-lg hover:border-text-muted",children:"Browse"})]})]}),r&&i.jsx(Cd,{initialPath:t||void 0,onSelect:l=>{n(l),a(!1)},onClose:()=>a(!1)}),i.jsx("button",{onClick:()=>e({workdir:t}),disabled:!t,"data-testid":"onboarding-workdir-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]})]})}function B7({onNext:e}){const[t,n]=N.useState(!1),[r,a]=N.useState("http://localhost:11434"),[l,u]=N.useState("qwen3.5:0.8b"),[c,d]=N.useState("ollama"),{copied:h,copy:p}=vk();N.useEffect(()=>{Se("/api/config").then(x=>x.json()).then(x=>{x.visionFallback&&(n(x.visionFallback.enabled),a(x.visionFallback.url),u(x.visionFallback.model),x.visionFallback.backend&&d(x.visionFallback.backend))}).catch(()=>{})},[]);function m(x){if(x){e({});return}e({visionFallback:{enabled:t,url:r,model:l,timeout:120,backend:c}})}return i.jsxs("div",{className:"max-w-xl mx-auto",children:[i.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Vision (Optional)"}),i.jsx("p",{className:"text-text-secondary mb-8",children:"Configure a vision model for non-vision models"}),i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"bg-bg-secondary rounded-lg p-4 border border-border",children:[i.jsx("p",{className:"text-text-secondary text-sm mb-2",children:"You need a server with a vision model. Choose your backend type below."}),i.jsx("p",{className:"text-text-secondary text-sm mb-2",children:"For Ollama:"}),i.jsx("a",{href:"https://ollama.com/download",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline text-sm",children:"Download Ollama"}),i.jsxs("div",{className:"mt-3 p-2 bg-bg-primary rounded border border-border flex items-center justify-between gap-2",children:[i.jsx("code",{className:"text-text-secondary text-xs",children:"ollama pull qwen3.5:0.8b"}),i.jsx("button",{onClick:()=>p("ollama pull qwen3.5:0.8b"),className:"text-text-muted hover:text-text-primary transition-colors",title:"Copy",children:h?i.jsx(Pr,{className:"w-4 h-4 text-accent-primary"}):i.jsx(nT,{className:"w-4 h-4"})})]}),i.jsxs("p",{className:"text-text-secondary text-sm mt-3",children:["For OpenAI-compatible servers (vLLM, sglang, llama.cpp): use the ",i.jsx("strong",{children:"OpenAI"})," backend type."]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t,onChange:x=>n(x.target.checked),className:"w-5 h-5 rounded border-border bg-bg-secondary text-accent-primary focus:ring-accent-primary"}),i.jsx("span",{className:"text-text-primary",children:"Enable vision fallback for non-vision models"})]}),t&&i.jsxs("div",{className:"space-y-4 pl-8",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Backend type"}),i.jsxs("select",{value:c,onChange:x=>d(x.target.value),className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary focus:outline-none focus:border-accent-primary",children:[i.jsx("option",{value:"ollama",children:"Ollama"}),i.jsx("option",{value:"openai",children:"OpenAI-compatible (vLLM, sglang, llama.cpp)"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision server URL"}),i.jsx("input",{type:"text",value:r,onChange:x=>a(x.target.value),placeholder:c==="ollama"?"http://localhost:11434":"http://localhost:8000/v1",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision model name"}),i.jsx("input",{type:"text",value:l,onChange:x=>u(x.target.value),placeholder:c==="ollama"?"qwen3.5:0.8b":"qwen3.5-27b",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]})]}),i.jsxs("div",{className:"flex items-center justify-between pt-4",children:[i.jsx("button",{onClick:()=>m(!0),"data-testid":"onboarding-skip-button",className:"text-text-muted hover:text-text-secondary text-sm underline",children:"Skip for now"}),i.jsx("button",{onClick:()=>m(!1),className:"px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 transition-colors",children:"Finish Setup"})]})]})]})}function $7({onComplete:e}){const[t,n]=N.useState(1),[r,a]=N.useState(!1),[l,u]=N.useState({});async function c(m){u(x=>({...x,providers:m.providers})),n(2)}async function d(m){u(x=>({...x,...m})),n(3)}async function h(m){a(!0);try{if(!(await Se("/api/init/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:l.workdir,visionFallback:m.visionFallback})})).ok)throw new Error("Failed to save config");e()}catch(x){console.error("Failed to save onboarding data:",x),a(!1)}}const p=m=>{n(m)};return i.jsxs("div",{className:"w-full max-w-xl mx-auto px-6 py-16 relative",children:[i.jsx(ec,{onClick:e,className:"absolute top-4 right-4 p-2",variant:"modal",size:"xl"}),i.jsx(I7,{currentStep:t,totalSteps:3,labels:["LLM Providers","Projects Folder","Vision"],onStepClick:p}),i.jsx("div",{className:"max-w-xl mx-auto",children:r?i.jsxs("div",{className:"text-center",children:[i.jsx(Es,{className:"w-6 h-6"}),i.jsx("p",{className:"mt-4 text-text-secondary",children:"Saving your settings..."})]}):i.jsxs(i.Fragment,{children:[t===1&&i.jsx(M7,{onNext:c}),t===2&&i.jsx(P7,{onNext:d}),t===3&&i.jsx(B7,{onNext:h})]})})]})}function z7({projectId:e}){var p;const[,t]=Ln(),n=Re(m=>m.sessionsWithPendingConfirmations),r=Re(m=>{var x;return(x=m.currentSession)==null?void 0:x.id}),a=Re(m=>m.crossSessionConfirmations),l=Re(m=>m.sessions),u=n.find(m=>m!==r);if(!u)return null;const c=l.find(m=>m.id===u),d=(c==null?void 0:c.title)??u.slice(0,6),h=((p=a[u])==null?void 0:p.length)??0;return i.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-amber-500/15 border-b border-amber-500/30 cursor-pointer hover:bg-amber-500/20 transition-colors",onClick:()=>t(e?`/p/${e}/s/${u}`:`/s/${u}`),role:"button",tabIndex:0,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&t(e?`/p/${e}/s/${u}`:`/s/${u}`)},children:[i.jsx(tg,{className:"w-4 h-4 text-amber-400 flex-shrink-0"}),i.jsxs("span",{className:"text-sm text-amber-300 flex-1 truncate",children:[h," confirmation",h>1?"s":"",' pending in session "',d,'"']}),i.jsx("span",{className:"text-xs text-amber-400 font-medium flex-shrink-0",children:"View session →"})]})}const cp="openfox_updated_to",up="update_pending";function H7(){const[e,t]=N.useState(!1),n=localStorage.getItem(cp),r=localStorage.getItem(up);N.useEffect(()=>{if(!n||!r)return;const l=setTimeout(()=>{localStorage.removeItem(cp),localStorage.removeItem(up),t(!0)},8e3);return()=>clearTimeout(l)},[n,r]);const a=()=>{localStorage.removeItem(cp),localStorage.removeItem(up),t(!0)};return e||r!=="true"||!n?null:i.jsxs("div",{className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-[100] flex items-center gap-3 px-4 py-2.5 bg-bg-secondary border border-border rounded-lg shadow-xl animate-slide-down",role:"status","aria-live":"polite",children:[i.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-accent-primary/20",children:i.jsx(Pr,{className:"w-3 h-3 text-accent-primary"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:"OpenFox updated successfully"}),i.jsxs("span",{className:"text-xs text-text-muted",children:["Now running ",n]})]}),i.jsx("button",{onClick:a,className:"ml-2 p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Dismiss",children:i.jsx(rg,{className:"w-3.5 h-3.5"})})]})}typeof window<"u"&&(Rt.getState().loadUserPresets(),Rt.getState().applySavedTheme());function nx(){return typeof window>"u"?!1:localStorage.getItem("openfox_token")!==null}function v2(){return i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx(hi,{})})}function U7({sidebarOpen:e,onSidebarToggle:t}){const[,n]=oo("/p/:projectId"),r=n==null?void 0:n.projectId,a=Re(d=>d.connectionStatus),l=Ft(d=>d.currentProject),u=nx();return XN({canLoad:a==="connected"||u,projectId:r,currentProjectId:l==null?void 0:l.id}),!l||l.id!==r?i.jsx(v2,{}):i.jsxs(i.Fragment,{children:[i.jsx(Ik,{projectId:r,isOpen:e,onClose:t}),i.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:i.jsx(yB,{})})]})}function F7({sidebarOpen:e,onSidebarToggle:t,rightSidebarOpen:n,onRightSidebarToggle:r}){const[,a]=oo("/p/:projectId/s/:sessionId"),l=a==null?void 0:a.projectId,u=a==null?void 0:a.sessionId,[,c]=Ln(),d=Re(C=>C.connectionStatus),h=Re(C=>C.currentSession),p=Re(C=>C.error),m=Re(C=>C.clearError),x=Ft(C=>C.currentProject),y=nx();return QN({canLoad:d==="connected"||y,projectId:l,sessionId:u,currentProjectId:x==null?void 0:x.id,currentSessionId:h==null?void 0:h.id}),N.useEffect(()=>{(p==null?void 0:p.code)==="NOT_FOUND"&&l&&(m(),c(`/p/${l}`))},[p,l,m,c]),!x||x.id!==l?i.jsx(v2,{}):i.jsxs(i.Fragment,{children:[i.jsx(Ik,{projectId:l,isOpen:e,onClose:t}),i.jsxs("div",{className:"flex-1 min-w-0 bg-primary flex flex-col",children:[i.jsx(z7,{projectId:l}),i.jsx(R7,{criteriaSidebarOpen:n,onCriteriaSidebarToggle:r})]})]})}function V7(){const e=Qt(r=>r.fetchConfig),[,t]=Ln();async function n(){await e(),t("/")}return i.jsx("div",{className:"flex-1 overflow-y-auto",children:i.jsx($7,{onComplete:n})})}function G7(){const{connectionStatus:e}=VN(),t=Qt(O=>O.fetchConfig),n=Qt(O=>O.refreshProviderModels),r=Qt(O=>O.providers),a=Qt(O=>O.activeProviderId),[,l]=Ln(),u=nx(),[c,d]=N.useState(!1);N.useEffect(()=>{(e==="connected"||u)&&t().then(()=>{d(!0),Ht.getState().getSettings([...Zp,Te.DISPLAY_THEME,Te.DISPLAY_USER_PRESETS,Te.DISPLAY_CUSTOM_CSS,Te.KEYBINDINGS]),Al.getState().fetchServers()})},[e,u,t]),N.useEffect(()=>{c&&a&&n(a).then(()=>{const O=Qt.getState().defaultModelSelection;(O?O.split("/")[0]:null)!==a&&t()})},[c,a,n,t]);const h=Ht(O=>O.settings);N.useEffect(()=>{c&&r.length===0&&l("/onboarding")},[c,r.length]),N.useEffect(()=>{const{applyPreset:O,applyTokens:M,setFollowSystemTheme:q,initSystemThemeListener:z}=Rt.getState(),ee=h[Te.DISPLAY_THEME],Q=h[Te.DISPLAY_USER_PRESETS],ne=h[Te.DISPLAY_FOLLOW_SYSTEM_THEME];if(Q&&localStorage.setItem("openfox:userPresets",Q),ee){localStorage.setItem("openfox:theme",ee);try{const B=JSON.parse(ee);B.preset&&B.tokens?(O(B.preset),Rt.setState({basePreset:B.preset}),M(B.tokens)):B.preset?O(B.preset):B.tokens&&M(B.tokens)}catch{O("dark")}}else O("system");ne!==void 0&&Rt.getState().followSystemTheme!==(ne==="true")&&q(ne==="true");const K=z();return()=>K()},[h[Te.DISPLAY_THEME],h[Te.DISPLAY_USER_PRESETS]]),N.useEffect(()=>{const O=h[Te.DISPLAY_CUSTOM_CSS]??"";let M=document.getElementById("custom-css");M||(M=document.createElement("style"),M.id="custom-css",document.head.appendChild(M)),M.textContent=O},[h[Te.DISPLAY_CUSTOM_CSS]]);const[p,m]=N.useState(!1);N.useEffect(()=>{if(localStorage.getItem("update_pending")!=="true")return;const M=Ht.getState().settings[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE];M!==void 0&&M!=="false"&&m(!0)},[h[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]]);const x=()=>{const O=localStorage.getItem("openfox:leftSidebar");return O!==null?O==="true":!0},y=()=>{const O=localStorage.getItem("openfox:rightSidebar");return O!==null?O==="true":!0},[w,C]=N.useState(x),[_,S]=N.useState(y),[v,b]=N.useState(!1),[E,j]=N.useState(!1),[T,D]=N.useState(!1),L=bN();N.useEffect(()=>{const O=()=>{D(window.innerWidth<768)};return O(),window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]);const[I]=Ln(),P=/^\/p\/[^/]+$/.test(I),W=T?v:P?!0:w,H=T?E:_,R=()=>{T?b(!v):C(!w)},U=()=>{T?j(!E):S(!_)};N.useEffect(()=>{T||localStorage.setItem("openfox:leftSidebar",String(w))},[w,T]),N.useEffect(()=>{T||localStorage.setItem("openfox:rightSidebar",String(_))},[_,T]),N.useEffect(()=>{(e==="connected"||u)&&t()},[e,t,u]);const V=Re(O=>O.showPasswordModal),G=Re(O=>O.passwordModalRetry),Z=Re(O=>O.submitPassword),X=Re(O=>O.cancelPassword),[$]=oo("/p/:projectId/s/:sessionId/readonly");return!$&&e!=="connected"&&!V&&!u?i.jsxs(i.Fragment,{children:[i.jsx(e1,{isOpen:!0,isRetry:G,onSubmit:Z,onCancel:X}),i.jsx("div",{className:"h-screen flex items-center justify-center",children:i.jsx(jT,{text:"Connecting to server..."})})]}):$?i.jsx(O7,{}):i.jsxs(i.Fragment,{children:[i.jsx(e1,{isOpen:V,isRetry:G,onSubmit:Z,onCancel:X}),i.jsxs("div",{className:"flex flex-col",style:{height:T?`calc(${L.offsetTop}px + ${L.height}px)`:"100vh"},children:[i.jsx(mB,{}),i.jsx(aB,{onMenuClick:R,onCriteriaToggle:U}),i.jsx("div",{className:"flex-1 flex overflow-hidden",children:i.jsxs(mN,{children:[i.jsx(ol,{path:"/onboarding",children:i.jsx(V7,{})}),i.jsx(ol,{path:"/p/:projectId/s/:sessionId",children:i.jsx(F7,{sidebarOpen:W,onSidebarToggle:R,rightSidebarOpen:H,onRightSidebarToggle:U})}),i.jsx(ol,{path:"/p/:projectId/new",children:i.jsx(xB,{})}),i.jsx(ol,{path:"/p/:projectId",children:i.jsx(U7,{sidebarOpen:W,onSidebarToggle:R})}),i.jsx(ol,{path:"/",children:i.jsx(gB,{})})]})})]}),i.jsx(H7,{}),i.jsx(_k,{isOpen:p,onClose:()=>m(!1)})]})}qj.createRoot(document.getElementById("root")).render(i.jsx(si.StrictMode,{children:i.jsx(c1,{base:d1,children:i.jsx(G7,{})})}));
316
+ ${de.prompt}`:de.prompt;de.metadata.agentMode&&await Re.getState().switchMode(de.metadata.agentMode),oe(he,c!=null&&c.length?c:void 0,{messageKind:"command",isSystemGenerated:!0}),Qe()}},onSelectWorkflow:fe=>{const ce=l.trim()||void 0,de=c.length>0?c:void 0;Oe(ce,de,fe),Qe()}})]}),b&&i.jsx(B$,{isOpen:b,onClose:()=>{E(!1),Ul(!0)},displayItems:K,onNavigate:ze})]})}function O7(){var b;const[,e]=oo("/p/:projectId/s/:sessionId/readonly"),t=e==null?void 0:e.sessionId,[n,r]=N.useState(null),[a,l]=N.useState([]),[u,c]=N.useState(0),[d,h]=N.useState(!0),[p,m]=N.useState(null),x=async()=>{if(t){h(!0),m(null);try{const E=await Se(`/api/sessions/${t}?full=true`);if(!E.ok){m(`Failed to load session (${E.status})`),h(!1);return}const j=await E.json();r(j.session??null),l(j.messages??[]),c(j.hiddenCount??0)}catch(E){m(E instanceof Error?E.message:"Unknown error")}finally{h(!1)}}};N.useEffect(()=>{Ht.getState().getSettings([...Zp])},[]),N.useEffect(()=>{x()},[t]);const{showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S}=Xi(),v=N.useMemo(()=>b2(a),[a]);return d?i.jsx("div",{className:"h-screen flex items-center justify-center bg-primary",children:i.jsx(hi,{})}):p?i.jsx("div",{className:"h-screen flex items-center justify-center bg-primary",children:i.jsxs("div",{className:"text-center space-y-4",children:[i.jsx("div",{className:"text-red-400 text-sm",children:p}),i.jsx("button",{onClick:x,className:"px-3 py-1.5 text-sm bg-bg-tertiary text-text-primary border border-border rounded hover:bg-bg-tertiary/80 transition-colors",children:"Retry"})]})}):i.jsxs("div",{className:"h-screen print:h-auto flex flex-col bg-primary",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-secondary shrink-0 print:hidden",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("h1",{className:"text-sm font-medium text-text-primary truncate",children:[((b=n==null?void 0:n.metadata)==null?void 0:b.title)??"Session"," — Read-only view"]}),i.jsxs("span",{className:"text-xs text-text-muted whitespace-nowrap",children:[a.length," messages",u>0?` (${u} older hidden)`:""]})]}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("button",{onClick:x,disabled:d,className:"px-3 py-1 text-xs bg-bg-tertiary text-text-primary border border-border rounded hover:bg-bg-tertiary/80 transition-colors disabled:opacity-50",children:d?"Refreshing...":"Refresh"})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto print:overflow-visible scrollbar-stable",children:[i.jsx("div",{className:"pt-4",children:i.jsx(c2,{displayItems:v,showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S})}),i.jsx("div",{className:"h-8"})]})]})}function e1({isOpen:e,isRetry:t,onSubmit:n,onCancel:r}){const[a,l]=N.useState(""),u=N.useRef(null);N.useEffect(()=>{e&&(l(""),setTimeout(()=>{var d;return(d=u.current)==null?void 0:d.focus()},100))},[e]);const c=d=>{d.preventDefault(),a.trim()&&n(a)};return i.jsx(wt,{isOpen:e,onClose:r,title:t?"Invalid Password":"Password Required",size:"sm",children:i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsx("p",{className:"text-text-secondary text-sm",children:t?"The password you entered was incorrect. Please try again.":"This server requires a password to connect."}),i.jsx(oi,{ref:u,type:"password",value:a,onChange:d=>l(d.target.value),placeholder:"Enter password",autoFocus:!0}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ze,{type:"button",variant:"secondary",onClick:r,children:"Cancel"}),i.jsx(Ze,{type:"submit",disabled:!a.trim(),children:t?"Try Again":"Connect"})]})]})})}function I7({currentStep:e,totalSteps:t,labels:n,onStepClick:r}){return i.jsx("div",{className:"flex justify-center py-6",children:i.jsx("div",{className:"flex items-center",children:Array.from({length:t},(a,l)=>{const u=l+1,c=u<e,d=u===e;return i.jsxs("div",{className:"flex items-center",children:[i.jsx("button",{onClick:()=>r==null?void 0:r(u),className:`size-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors shrink-0 ${c?"bg-accent-primary text-text-primary hover:opacity-80":d?"bg-accent-primary text-text-primary":"bg-bg-tertiary text-text-muted"}`,children:c?"✓":u}),i.jsx("button",{onClick:()=>r==null?void 0:r(u),className:`ml-2 mr-4 text-sm whitespace-nowrap hidden sm:block ${d?"text-text-primary font-medium":"text-text-muted hover:text-text-secondary"}`,children:n[l]}),l<t-1&&i.jsx("div",{className:`w-12 sm:w-20 h-0.5 mr-4 ${c?"bg-accent-primary":"bg-border"}`})]},l)})})})}function M7({onNext:e}){const[t,n]=N.useState([]),[r,a]=N.useState([]),[l,u]=N.useState(!1),[c,d]=N.useState(null),[h,p]=N.useState(null),[m,x]=N.useState(null);N.useEffect(()=>{y()},[]);async function y(){try{const j=await Se("/api/providers");if(j.ok){const D=(await j.json()).providers.map(L=>({id:L.id,name:L.name,url:L.url,backend:L.backend,model:null,apiKey:L.apiKey,isLocal:L.isLocal,thinkingField:L.thinkingField,models:L.models}));n(D),a(D)}}catch{}}async function w(j){const T=j.id.startsWith("temp-"),D=r.some(P=>P.id===j.id),L=r.length===0&&c===null,I=x2(j);try{let P;if(T){const H=await Se("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!H.ok)throw new Error("Failed to create provider");const R=await H.json();P={...j,id:R.provider.id,model:null}}else{if(!(await Se(`/api/providers/${j.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)})).ok)throw new Error("Failed to update provider");P={...j,model:null}}const W=H=>H.some(R=>R.id===P.id)?H.map(R=>R.id===P.id?P:R):[...H,P];a(W),n(W),L&&!D&&e({providers:[P]})}catch{if(T){const P={...j,model:null};a(W=>[...W,P])}}}function C(){d(null),u(!0)}function _(j){d(j),u(!0)}function S(){u(!1),d(null)}function v(j){p(j),t.some(D=>D.id===j)?Se(`/api/providers/${j}`,{method:"DELETE"}).then(()=>{a(r.filter(D=>D.id!==j)),n(t.filter(D=>D.id!==j)),p(null)}).catch(()=>p(null)):(a(r.filter(D=>D.id!==j)),p(null))}function b(){const j=r.filter(T=>!T.id.startsWith("temp-"));e({providers:j})}const E=r.length>0;return i.jsxs("div",{className:"max-w-xl mx-auto",children:[i.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"LLM Providers"}),i.jsx("p",{className:"text-text-secondary mb-8",children:"Manage your LLM server connections"}),i.jsxs("div",{className:"space-y-4",children:[r.length>0?i.jsx("div",{className:"space-y-2",children:r.map(j=>i.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"px-2 py-0.5 bg-accent-primary/25 text-accent-primary rounded text-xs font-medium",children:f1(j.backend)}),i.jsx("span",{className:"text-text-primary font-medium",children:j.name}),i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${j.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:j.isLocal?"local":"api"})]}),i.jsx("p",{className:"text-text-muted text-sm mt-1 truncate",children:j.url}),j.model&&i.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",j.model]})]}),i.jsx("div",{className:"flex items-center gap-1",children:m===j.id?i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>v(j.id),disabled:h===j.id,className:"px-2 py-1 text-xs text-red-500 hover:text-red-400 bg-red-500/10 rounded transition-colors disabled:opacity-50",children:h===j.id?"Deleting...":"Confirm"}),i.jsx("button",{onClick:()=>x(null),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>_(j),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary border border-border rounded transition-colors",children:"Edit"}),i.jsx("button",{onClick:()=>x(j.id),className:"p-2 text-text-muted hover:text-red-500 transition-colors",title:"Remove provider",children:i.jsx(lo,{})})]})})]},j.id))}):i.jsx("div",{className:"bg-bg-secondary rounded-lg p-8 text-center border border-border",children:i.jsx("p",{className:"text-text-muted",children:"No providers configured yet"})}),i.jsxs("button",{onClick:C,"data-testid":"onboarding-add-provider-button",className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-bg-secondary border border-dashed border-border rounded-lg text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[i.jsx(Es,{className:"w-4 h-4"}),"Add Provider"]}),i.jsx("button",{onClick:b,disabled:!E,"data-testid":"onboarding-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]}),i.jsx(y2,{isOpen:l,onClose:S,onSave:w,initialStep:1,editProvider:c??void 0})]})}function P7({onNext:e}){const[t,n]=N.useState(""),[r,a]=N.useState(!1);return N.useEffect(()=>{Se("/api/config").then(l=>l.json()).then(l=>{l.workdir?n(l.workdir):fetch(ks("/api/directories?path=")+encodeURIComponent("/home")).then(u=>u.json()).then(u=>{u.current&&n(u.current)}).catch(()=>{})}).catch(()=>{fetch(ks("/api/directories?path=")+encodeURIComponent("/home")).then(l=>l.json()).then(l=>{l.current&&n(l.current)}).catch(()=>{})})},[]),i.jsxs("div",{className:"max-w-xl mx-auto",children:[i.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Your Projects Folder"}),i.jsx("p",{className:"text-text-secondary mb-8",children:"Where should OpenFox create project folders?"}),i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Workspace directory"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:t,onChange:l=>n(l.target.value),placeholder:"/home/user/projects","data-testid":"onboarding-workdir-input",className:"flex-1 px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),i.jsx("button",{onClick:()=>a(!0),className:"px-4 py-2 bg-bg-secondary border border-border rounded-lg hover:border-text-muted",children:"Browse"})]})]}),r&&i.jsx(Cd,{initialPath:t||void 0,onSelect:l=>{n(l),a(!1)},onClose:()=>a(!1)}),i.jsx("button",{onClick:()=>e({workdir:t}),disabled:!t,"data-testid":"onboarding-workdir-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]})]})}function B7({onNext:e}){const[t,n]=N.useState(!1),[r,a]=N.useState("http://localhost:11434"),[l,u]=N.useState("qwen3.5:0.8b"),[c,d]=N.useState("ollama"),{copied:h,copy:p}=vk();N.useEffect(()=>{Se("/api/config").then(x=>x.json()).then(x=>{x.visionFallback&&(n(x.visionFallback.enabled),a(x.visionFallback.url),u(x.visionFallback.model),x.visionFallback.backend&&d(x.visionFallback.backend))}).catch(()=>{})},[]);function m(x){if(x){e({});return}e({visionFallback:{enabled:t,url:r,model:l,timeout:120,backend:c}})}return i.jsxs("div",{className:"max-w-xl mx-auto",children:[i.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Vision (Optional)"}),i.jsx("p",{className:"text-text-secondary mb-8",children:"Configure a vision model for non-vision models"}),i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"bg-bg-secondary rounded-lg p-4 border border-border",children:[i.jsx("p",{className:"text-text-secondary text-sm mb-2",children:"You need a server with a vision model. Choose your backend type below."}),i.jsx("p",{className:"text-text-secondary text-sm mb-2",children:"For Ollama:"}),i.jsx("a",{href:"https://ollama.com/download",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline text-sm",children:"Download Ollama"}),i.jsxs("div",{className:"mt-3 p-2 bg-bg-primary rounded border border-border flex items-center justify-between gap-2",children:[i.jsx("code",{className:"text-text-secondary text-xs",children:"ollama pull qwen3.5:0.8b"}),i.jsx("button",{onClick:()=>p("ollama pull qwen3.5:0.8b"),className:"text-text-muted hover:text-text-primary transition-colors",title:"Copy",children:h?i.jsx(Pr,{className:"w-4 h-4 text-accent-primary"}):i.jsx(nT,{className:"w-4 h-4"})})]}),i.jsxs("p",{className:"text-text-secondary text-sm mt-3",children:["For OpenAI-compatible servers (vLLM, sglang, llama.cpp): use the ",i.jsx("strong",{children:"OpenAI"})," backend type."]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t,onChange:x=>n(x.target.checked),className:"w-5 h-5 rounded border-border bg-bg-secondary text-accent-primary focus:ring-accent-primary"}),i.jsx("span",{className:"text-text-primary",children:"Enable vision fallback for non-vision models"})]}),t&&i.jsxs("div",{className:"space-y-4 pl-8",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Backend type"}),i.jsxs("select",{value:c,onChange:x=>d(x.target.value),className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary focus:outline-none focus:border-accent-primary",children:[i.jsx("option",{value:"ollama",children:"Ollama"}),i.jsx("option",{value:"openai",children:"OpenAI-compatible (vLLM, sglang, llama.cpp)"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision server URL"}),i.jsx("input",{type:"text",value:r,onChange:x=>a(x.target.value),placeholder:c==="ollama"?"http://localhost:11434":"http://localhost:8000/v1",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision model name"}),i.jsx("input",{type:"text",value:l,onChange:x=>u(x.target.value),placeholder:c==="ollama"?"qwen3.5:0.8b":"qwen3.5-27b",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]})]}),i.jsxs("div",{className:"flex items-center justify-between pt-4",children:[i.jsx("button",{onClick:()=>m(!0),"data-testid":"onboarding-skip-button",className:"text-text-muted hover:text-text-secondary text-sm underline",children:"Skip for now"}),i.jsx("button",{onClick:()=>m(!1),className:"px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 transition-colors",children:"Finish Setup"})]})]})]})}function $7({onComplete:e}){const[t,n]=N.useState(1),[r,a]=N.useState(!1),[l,u]=N.useState({});async function c(m){u(x=>({...x,providers:m.providers})),n(2)}async function d(m){u(x=>({...x,...m})),n(3)}async function h(m){a(!0);try{if(!(await Se("/api/init/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:l.workdir,visionFallback:m.visionFallback})})).ok)throw new Error("Failed to save config");e()}catch(x){console.error("Failed to save onboarding data:",x),a(!1)}}const p=m=>{n(m)};return i.jsxs("div",{className:"w-full max-w-xl mx-auto px-6 py-16 relative",children:[i.jsx(ec,{onClick:e,className:"absolute top-4 right-4 p-2",variant:"modal",size:"xl"}),i.jsx(I7,{currentStep:t,totalSteps:3,labels:["LLM Providers","Projects Folder","Vision"],onStepClick:p}),i.jsx("div",{className:"max-w-xl mx-auto",children:r?i.jsxs("div",{className:"text-center",children:[i.jsx(Es,{className:"w-6 h-6"}),i.jsx("p",{className:"mt-4 text-text-secondary",children:"Saving your settings..."})]}):i.jsxs(i.Fragment,{children:[t===1&&i.jsx(M7,{onNext:c}),t===2&&i.jsx(P7,{onNext:d}),t===3&&i.jsx(B7,{onNext:h})]})})]})}function z7({projectId:e}){var p;const[,t]=Ln(),n=Re(m=>m.sessionsWithPendingConfirmations),r=Re(m=>{var x;return(x=m.currentSession)==null?void 0:x.id}),a=Re(m=>m.crossSessionConfirmations),l=Re(m=>m.sessions),u=n.find(m=>m!==r);if(!u)return null;const c=l.find(m=>m.id===u),d=(c==null?void 0:c.title)??u.slice(0,6),h=((p=a[u])==null?void 0:p.length)??0;return i.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-amber-500/15 border-b border-amber-500/30 cursor-pointer hover:bg-amber-500/20 transition-colors",onClick:()=>t(e?`/p/${e}/s/${u}`:`/s/${u}`),role:"button",tabIndex:0,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&t(e?`/p/${e}/s/${u}`:`/s/${u}`)},children:[i.jsx(tg,{className:"w-4 h-4 text-amber-400 flex-shrink-0"}),i.jsxs("span",{className:"text-sm text-amber-300 flex-1 truncate",children:[h," confirmation",h>1?"s":"",' pending in session "',d,'"']}),i.jsx("span",{className:"text-xs text-amber-400 font-medium flex-shrink-0",children:"View session →"})]})}const cp="openfox_updated_to",up="update_pending";function H7(){const[e,t]=N.useState(!1),n=localStorage.getItem(cp),r=localStorage.getItem(up);N.useEffect(()=>{if(!n||!r)return;const l=setTimeout(()=>{localStorage.removeItem(cp),localStorage.removeItem(up),t(!0)},8e3);return()=>clearTimeout(l)},[n,r]);const a=()=>{localStorage.removeItem(cp),localStorage.removeItem(up),t(!0)};return e||r!=="true"||!n?null:i.jsxs("div",{className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-[100] flex items-center gap-3 px-4 py-2.5 bg-bg-secondary border border-border rounded-lg shadow-xl animate-slide-down",role:"status","aria-live":"polite",children:[i.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-accent-primary/20",children:i.jsx(Pr,{className:"w-3 h-3 text-accent-primary"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:"OpenFox updated successfully"}),i.jsxs("span",{className:"text-xs text-text-muted",children:["Now running ",n]})]}),i.jsx("button",{onClick:a,className:"ml-2 p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Dismiss",children:i.jsx(rg,{className:"w-3.5 h-3.5"})})]})}typeof window<"u"&&(Rt.getState().loadUserPresets(),Rt.getState().applySavedTheme());function nx(){return typeof window>"u"?!1:localStorage.getItem("openfox_token")!==null}function v2(){return i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx(hi,{})})}function U7({sidebarOpen:e,onSidebarToggle:t}){const[,n]=oo("/p/:projectId"),r=n==null?void 0:n.projectId,a=Re(d=>d.connectionStatus),l=Ft(d=>d.currentProject),u=nx();return XN({canLoad:a==="connected"||u,projectId:r,currentProjectId:l==null?void 0:l.id}),!l||l.id!==r?i.jsx(v2,{}):i.jsxs(i.Fragment,{children:[i.jsx(Ik,{projectId:r,isOpen:e,onClose:t}),i.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:i.jsx(yB,{})})]})}function F7({sidebarOpen:e,onSidebarToggle:t,rightSidebarOpen:n,onRightSidebarToggle:r}){const[,a]=oo("/p/:projectId/s/:sessionId"),l=a==null?void 0:a.projectId,u=a==null?void 0:a.sessionId,[,c]=Ln(),d=Re(C=>C.connectionStatus),h=Re(C=>C.currentSession),p=Re(C=>C.error),m=Re(C=>C.clearError),x=Ft(C=>C.currentProject),y=nx();return QN({canLoad:d==="connected"||y,projectId:l,sessionId:u,currentProjectId:x==null?void 0:x.id,currentSessionId:h==null?void 0:h.id}),N.useEffect(()=>{(p==null?void 0:p.code)==="NOT_FOUND"&&l&&(m(),c(`/p/${l}`))},[p,l,m,c]),!x||x.id!==l?i.jsx(v2,{}):i.jsxs(i.Fragment,{children:[i.jsx(Ik,{projectId:l,isOpen:e,onClose:t}),i.jsxs("div",{className:"flex-1 min-w-0 bg-primary flex flex-col",children:[i.jsx(z7,{projectId:l}),i.jsx(R7,{criteriaSidebarOpen:n,onCriteriaSidebarToggle:r})]})]})}function V7(){const e=Kt(r=>r.fetchConfig),[,t]=Ln();async function n(){await e(),t("/")}return i.jsx("div",{className:"flex-1 overflow-y-auto",children:i.jsx($7,{onComplete:n})})}function G7(){const{connectionStatus:e}=VN(),t=Kt(O=>O.fetchConfig),n=Kt(O=>O.refreshProviderModels),r=Kt(O=>O.providers),a=Kt(O=>O.activeProviderId),[,l]=Ln(),u=nx(),[c,d]=N.useState(!1);N.useEffect(()=>{(e==="connected"||u)&&t().then(()=>{d(!0),Ht.getState().getSettings([...Zp,Te.DISPLAY_THEME,Te.DISPLAY_USER_PRESETS,Te.DISPLAY_CUSTOM_CSS,Te.KEYBINDINGS]),Al.getState().fetchServers()})},[e,u,t]),N.useEffect(()=>{c&&a&&n(a).then(()=>{const O=Kt.getState().defaultModelSelection;(O?O.split("/")[0]:null)!==a&&t()})},[c,a,n,t]);const h=Ht(O=>O.settings);N.useEffect(()=>{c&&r.length===0&&l("/onboarding")},[c,r.length]),N.useEffect(()=>{const{applyPreset:O,applyTokens:M,setFollowSystemTheme:q,initSystemThemeListener:z}=Rt.getState(),ee=h[Te.DISPLAY_THEME],Q=h[Te.DISPLAY_USER_PRESETS],ne=h[Te.DISPLAY_FOLLOW_SYSTEM_THEME];if(Q&&localStorage.setItem("openfox:userPresets",Q),ee){localStorage.setItem("openfox:theme",ee);try{const B=JSON.parse(ee);B.preset&&B.tokens?(O(B.preset),Rt.setState({basePreset:B.preset}),M(B.tokens)):B.preset?O(B.preset):B.tokens&&M(B.tokens)}catch{O("dark")}}else O("system");ne!==void 0&&Rt.getState().followSystemTheme!==(ne==="true")&&q(ne==="true");const K=z();return()=>K()},[h[Te.DISPLAY_THEME],h[Te.DISPLAY_USER_PRESETS]]),N.useEffect(()=>{const O=h[Te.DISPLAY_CUSTOM_CSS]??"";let M=document.getElementById("custom-css");M||(M=document.createElement("style"),M.id="custom-css",document.head.appendChild(M)),M.textContent=O},[h[Te.DISPLAY_CUSTOM_CSS]]);const[p,m]=N.useState(!1);N.useEffect(()=>{const O=Ht.getState().settings[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE];if(O===void 0||O==="false")return;let M=!1;if(localStorage.getItem("update_pending")==="true"&&(M=!0,localStorage.removeItem("update_pending")),c){const z=Kt.getState().version,ee=localStorage.getItem("openfox_last_version");z&&ee&&z!==ee&&(M=!0),localStorage.setItem("openfox_last_version",z??"")}M&&m(!0)},[h[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE],c]);const x=()=>{const O=localStorage.getItem("openfox:leftSidebar");return O!==null?O==="true":!0},y=()=>{const O=localStorage.getItem("openfox:rightSidebar");return O!==null?O==="true":!0},[w,C]=N.useState(x),[_,S]=N.useState(y),[v,b]=N.useState(!1),[E,j]=N.useState(!1),[T,D]=N.useState(!1),L=bN();N.useEffect(()=>{const O=()=>{D(window.innerWidth<768)};return O(),window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]);const[I]=Ln(),P=/^\/p\/[^/]+$/.test(I),W=T?v:P?!0:w,H=T?E:_,R=()=>{T?b(!v):C(!w)},U=()=>{T?j(!E):S(!_)};N.useEffect(()=>{T||localStorage.setItem("openfox:leftSidebar",String(w))},[w,T]),N.useEffect(()=>{T||localStorage.setItem("openfox:rightSidebar",String(_))},[_,T]),N.useEffect(()=>{(e==="connected"||u)&&t()},[e,t,u]);const V=Re(O=>O.showPasswordModal),G=Re(O=>O.passwordModalRetry),Z=Re(O=>O.submitPassword),X=Re(O=>O.cancelPassword),[$]=oo("/p/:projectId/s/:sessionId/readonly");return!$&&e!=="connected"&&!V&&!u?i.jsxs(i.Fragment,{children:[i.jsx(e1,{isOpen:!0,isRetry:G,onSubmit:Z,onCancel:X}),i.jsx("div",{className:"h-screen flex items-center justify-center",children:i.jsx(jT,{text:"Connecting to server..."})})]}):$?i.jsx(O7,{}):i.jsxs(i.Fragment,{children:[i.jsx(e1,{isOpen:V,isRetry:G,onSubmit:Z,onCancel:X}),i.jsxs("div",{className:"flex flex-col",style:{height:T?`calc(${L.offsetTop}px + ${L.height}px)`:"100vh"},children:[i.jsx(mB,{}),i.jsx(aB,{onMenuClick:R,onCriteriaToggle:U}),i.jsx("div",{className:"flex-1 flex overflow-hidden",children:i.jsxs(mN,{children:[i.jsx(ol,{path:"/onboarding",children:i.jsx(V7,{})}),i.jsx(ol,{path:"/p/:projectId/s/:sessionId",children:i.jsx(F7,{sidebarOpen:W,onSidebarToggle:R,rightSidebarOpen:H,onRightSidebarToggle:U})}),i.jsx(ol,{path:"/p/:projectId/new",children:i.jsx(xB,{})}),i.jsx(ol,{path:"/p/:projectId",children:i.jsx(U7,{sidebarOpen:W,onSidebarToggle:R})}),i.jsx(ol,{path:"/",children:i.jsx(gB,{})})]})})]}),i.jsx(H7,{}),i.jsx(_k,{isOpen:p,onClose:()=>m(!1)})]})}qj.createRoot(document.getElementById("root")).render(i.jsx(si.StrictMode,{children:i.jsx(c1,{base:d1,children:i.jsx(G7,{})})}));