openfox 2.0.93 → 2.0.95

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/CHANGELOG.md +25 -0
  3. package/dist/{chat-handler-MSQFJH7S.js → chat-handler-5FV3TGQD.js} +22 -22
  4. package/dist/{chunk-IAAHDCJN.js → chunk-27SDWNKL.js} +8 -5
  5. package/dist/{chunk-TQATAKVV.js → chunk-4R7G5JB6.js} +1 -1
  6. package/dist/{chunk-3NGD6IVM.js → chunk-5N5JXT7R.js} +3 -3
  7. package/dist/{chunk-NV63HYNR.js → chunk-5UFTFBNW.js} +8 -8
  8. package/dist/{chunk-BJHPUMRX.js → chunk-62X2MPO6.js} +2 -2
  9. package/dist/{chunk-FK6R2YTQ.js → chunk-6RHMIMID.js} +17 -17
  10. package/dist/{chunk-PYJ2SRVC.js → chunk-7P7OKBYQ.js} +20 -4
  11. package/dist/{chunk-GAIAJDPH.js → chunk-D6T3X22W.js} +149 -52
  12. package/dist/{chunk-6OAJNCRY.js → chunk-GLF65XDS.js} +22 -1
  13. package/dist/{chunk-U7D72C4O.js → chunk-HAFRPV7I.js} +13 -3
  14. package/dist/{chunk-AA4PXMSI.js → chunk-KG2PJVOE.js} +253 -95
  15. package/dist/{chunk-NW2KP7PE.js → chunk-MB7STVMR.js} +6 -6
  16. package/dist/{chunk-SXHGRPCI.js → chunk-MC3MCMAF.js} +4 -4
  17. package/dist/{chunk-U2RSFH6A.js → chunk-MRWR3SIT.js} +2 -2
  18. package/dist/{chunk-WWC3R3YL.js → chunk-NLN5LPQ4.js} +2 -2
  19. package/dist/{chunk-NGN3Q26A.js → chunk-OHBY2673.js} +2 -2
  20. package/dist/{chunk-RJQDC2OO.js → chunk-OZD247P4.js} +10 -10
  21. package/dist/{chunk-3QQKKZMF.js → chunk-P637C6X3.js} +2 -2
  22. package/dist/{chunk-C56Z4OVW.js → chunk-SJJVNSA6.js} +2 -2
  23. package/dist/{chunk-7YBGCZSI.js → chunk-TDHDLDGQ.js} +10 -20
  24. package/dist/{chunk-6J5IZ2NL.js → chunk-TSHJW7OC.js} +37 -6
  25. package/dist/{chunk-54Q4TGG6.js → chunk-UEOEA6BB.js} +2 -2
  26. package/dist/chunk-VKU7YBLH.js +7 -0
  27. package/dist/{chunk-ESJNJ5B6.js → chunk-W7P5P54O.js} +3 -3
  28. package/dist/{chunk-ST4NYXLH.js → chunk-WWFH5GAR.js} +2 -2
  29. package/dist/{chunk-YM267G4F.js → chunk-YCPUV7AR.js} +4 -4
  30. package/dist/{chunk-GH5PL3JW.js → chunk-YPBV47DH.js} +6 -9
  31. package/dist/{chunk-DH32AHTL.js → chunk-ZASSAZ73.js} +2 -2
  32. package/dist/{chunk-AQ4KCGXL.js → chunk-ZMSHE564.js} +3 -3
  33. package/dist/cli/dev.js +1 -1
  34. package/dist/cli/index.js +1 -1
  35. package/dist/{client-RBXMHFX3.js → client-RENSCJPZ.js} +5 -5
  36. package/dist/{compactor-R7GGPBPR.js → compactor-3RXIAIPR.js} +10 -10
  37. package/dist/{dynamic-context-4UPNVL3N.js → dynamic-context-CJFDFUJF.js} +9 -9
  38. package/dist/{events-D5AFN2CW.js → events-QHZDLHEB.js} +9 -7
  39. package/dist/{folding-BO6Z6HMP.js → folding-O4OYOTPS.js} +5 -5
  40. package/dist/http-client-U6DVFL7F.js +11 -0
  41. package/dist/{inspect-proxy-NZ3VSMSC.js → inspect-proxy-GF6OI7MR.js} +4 -4
  42. package/dist/{manager-ZPQ6VSM5.js → manager-53J5P4EZ.js} +5 -5
  43. package/dist/{orchestrator-YQI2D4LW.js → orchestrator-LDVMBC23.js} +21 -21
  44. package/dist/package.json +1 -1
  45. package/dist/{path-security-DP75YZK5.js → path-security-72KGHGSV.js} +10 -10
  46. package/dist/{platform-UKZ2QC34.js → platform-7KXP3VVA.js} +4 -4
  47. package/dist/{processor-LVQWRG6M.js → processor-32QUVPV6.js} +21 -21
  48. package/dist/{project-creator-2WMZYQME.js → project-creator-SMWFMIU5.js} +3 -3
  49. package/dist/{projects-N6KVZGMS.js → projects-M5XKC7O6.js} +3 -3
  50. package/dist/{protocol-8BzyapcK.d.ts → protocol-C5ROb3nH.d.ts} +5 -4
  51. package/dist/{protocol-4ZDERZNC.js → protocol-YDNGGADL.js} +3 -3
  52. package/dist/provider/index.d.ts +4 -4
  53. package/dist/{provider-SYYZI2KX.js → provider-A74GHQUO.js} +6 -6
  54. package/dist/{provider-manager-P3ZSA5QS.js → provider-manager-PBOF77RQ.js} +6 -6
  55. package/dist/{registry-ERUV33AP.js → registry-XBEHPY7C.js} +4 -4
  56. package/dist/{serve-HEHWSYMX.js → serve-GL5WUPRP.js} +29 -29
  57. package/dist/server/index.d.ts +39 -3
  58. package/dist/server/index.js +28 -28
  59. package/dist/server-OYVGQU7O.js +46 -0
  60. package/dist/{session-overrides-NPVYNHTM.js → session-overrides-QWD4V5KW.js} +6 -6
  61. package/dist/{sessions-7KCM5QH4.js → sessions-BT4PION7.js} +15 -7
  62. package/dist/{settings-2OVKFWR5.js → settings-2WVGUPYV.js} +3 -3
  63. package/dist/shared/index.d.ts +3 -3
  64. package/dist/shared/index.js +1 -1
  65. package/dist/{tools-HDD7RHEG.js → tools-UTA3TV7P.js} +19 -19
  66. package/dist/{types-_OEK96iM.d.ts → types-D-dEQIrh.d.ts} +1 -1
  67. package/dist/{types-Ci7Tdpq3.d.ts → types-DHxO1nqw.d.ts} +17 -1
  68. package/dist/{update-JARYMNGH.js → update-VUTN743C.js} +2 -2
  69. package/dist/web/assets/{index-DxTIqntH.js → index-BUiw9fSe.js} +22 -22
  70. package/dist/web/assets/{index-B3lfsL1_.css → index-BlV1FebL.css} +1 -1
  71. package/dist/web/index.html +2 -2
  72. package/dist/web/sw.js +1 -1
  73. package/dist/{workspace-YLTMP3OX.js → workspace-IIRKILYL.js} +4 -4
  74. package/package.json +1 -1
  75. package/dist/chunk-LVZ6VQ3K.js +0 -7
  76. package/dist/http-client-E3CV6E5D.js +0 -11
  77. package/dist/server-AAIYC4BH.js +0 -46
@@ -46,8 +46,8 @@ var IE=Object.defineProperty;var ME=Object.getPrototypeOf;var PE=Reflect.get;var
46
46
  `);for(k=g=0;g<le.length&&!le[g].includes("DetermineComponentFrameRoot");)g++;for(;k<ge.length&&!ge[k].includes("DetermineComponentFrameRoot");)k++;if(g===le.length||k===ge.length)for(g=le.length-1,k=ge.length-1;1<=g&&0<=k&&le[g]!==ge[k];)k--;for(;1<=g&&0<=k;g--,k--)if(le[g]!==ge[k]){if(g!==1||k!==1)do if(g--,k--,0>k||le[g]!==ge[k]){var ke=`
47
47
  `+le[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:"")?Re(f):""}function Ee(s,o){switch(s.tag){case 26:case 27:case 5:return Re(s.type);case 16:return Re("Lazy");case 13:return s.child!==o&&o!==null?Re("Suspense Fallback"):Re("Suspense");case 19:return Re("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return Re("Activity");default:return""}}function st(s){try{var o="",f=null;do o+=Ee(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 ot=Object.prototype.hasOwnProperty,je=e.unstable_scheduleCallback,Me=e.unstable_cancelCallback,lt=e.unstable_shouldYield,we=e.unstable_requestPaint,Ie=e.unstable_now,qe=e.unstable_getCurrentPriorityLevel,te=e.unstable_ImmediatePriority,ae=e.unstable_UserBlockingPriority,se=e.unstable_NormalPriority,me=e.unstable_LowPriority,Ue=e.unstable_IdlePriority,He=e.log,Ye=e.unstable_setDisableYieldValue,ct=null,Je=null;function Ze(s){if(typeof He=="function"&&Ye(s),Je&&typeof Je.setStrictMode=="function")try{Je.setStrictMode(ct,s)}catch{}}var tt=Math.clz32?Math.clz32:rn,Nt=Math.log,dt=Math.LN2;function rn(s){return s>>>=0,s===0?32:31-(Nt(s)/dt|0)|0}var Un=256,ye=262144,Ge=4194304;function oe(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 fe(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=oe(g):(F&=Y,F!==0?k=oe(F):f||(f=Y&~s,f!==0&&(k=oe(f))))):(Y=g&~A,Y!==0?k=oe(Y):F!==0?k=oe(F):f||(f=g&~s,f!==0&&(k=oe(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 Pe(s,o){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&o)===0}function St(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 bn(){var s=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),s}function fn(s){for(var o=[],f=0;31>f;f++)o.push(s);return o}function Pr(s,o){s.pendingLanes|=o,o!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function Ns(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,le=s.expirationTimes,ge=s.hiddenUpdates;for(f=F&~f;0<f;){var ke=31-tt(f),Ae=1<<ke;Y[ke]=0,le[ke]=-1;var xe=ge[ke];if(xe!==null)for(ge[ke]=null,ke=0;ke<xe.length;ke++){var be=xe[ke];be!==null&&(be.lane&=-536870913)}f&=~Ae}g!==0&&xi(s,g,0),A!==0&&k===0&&s.tag!==0&&(s.suspendedLanes|=A&~(F&~o))}function xi(s,o,f){s.pendingLanes|=o,s.suspendedLanes&=~o;var g=31-tt(o);s.entangledLanes|=o,s.entanglements[g]=s.entanglements[g]|1073741824|f&261930}function Ts(s,o){var f=s.entangledLanes|=o;for(s=s.entanglements;f;){var g=31-tt(f),k=1<<g;k&o|s[g]&o&&(s[g]|=o),f&=~k}}function As(s,o){var f=o&-o;return f=(f&42)!==0?1:Se(f),(f&(s.suspendedLanes|o))!==0?0:f}function Se(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 Ce(s){return s&=-s,2<s?8<s?(s&134217727)!==0?32:268435456:8:2}function Oe(){var s=Z.p;return s!==0?s:(s=window.event,s===void 0?32:Fv(s.type))}function We(s,o){var f=Z.p;try{return Z.p=s,o()}finally{Z.p=f}}var Ve=Math.random().toString(36).slice(2),Qe="__reactFiber$"+Ve,at="__reactProps$"+Ve,Zt="__reactContainer$"+Ve,mn="__reactEvents$"+Ve,Zn="__reactListeners$"+Ve,k2="__reactHandles$"+Ve,ax="__reactResources$"+Ve,yo="__reactMarker$"+Ve;function Zd(s){delete s[Qe],delete s[at],delete s[mn],delete s[Zn],delete s[k2]}function sa(s){var o=s[Qe];if(o)return o;for(var f=s.parentNode;f;){if(o=f[Zt]||f[Qe]){if(f=o.alternate,o.child!==null||f!==null&&f.child!==null)for(s=Ev(s);s!==null;){if(f=s[Qe])return f;s=Ev(s)}return o}s=f,f=s.parentNode}return null}function ia(s){if(s=s[Qe]||s[Zt]){var o=s.tag;if(o===5||o===6||o===13||o===31||o===26||o===27||o===3)return s}return null}function bo(s){var o=s.tag;if(o===5||o===26||o===27||o===6)return s.stateNode;throw Error(r(33))}function aa(s){var o=s[ax];return o||(o=s[ax]={hoistableStyles:new Map,hoistableScripts:new Map}),o}function vn(s){s[yo]=!0}var ox=new Set,lx={};function yi(s,o){oa(s,o),oa(s+"Capture",o)}function oa(s,o){for(lx[s]=o,s=0;s<o.length;s++)ox.add(o[s])}var j2=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]*$"),cx={},ux={};function E2(s){return ot.call(ux,s)?!0:ot.call(cx,s)?!1:j2.test(s)?ux[s]=!0:(cx[s]=!0,!1)}function sc(s,o,f){if(E2(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 ic(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 ur(s){switch(typeof s){case"bigint":case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function dx(s){var o=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(o==="checkbox"||o==="radio")}function N2(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 eh(s){if(!s._valueTracker){var o=dx(s)?"checked":"value";s._valueTracker=N2(s,o,""+s[o])}}function hx(s){if(!s)return!1;var o=s._valueTracker;if(!o)return!0;var f=o.getValue(),g="";return s&&(g=dx(s)?s.checked?"true":"false":s.value),s=g,s!==f?(o.setValue(s),!0):!1}function ac(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 T2=/[\n"\\]/g;function dr(s){return s.replace(T2,function(o){return"\\"+o.charCodeAt(0).toString(16)+" "})}function th(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=""+ur(o)):s.value!==""+ur(o)&&(s.value=""+ur(o)):F!=="submit"&&F!=="reset"||s.removeAttribute("value"),o!=null?nh(s,F,ur(o)):f!=null?nh(s,F,ur(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=""+ur(Y):s.removeAttribute("name")}function fx(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)){eh(s);return}f=f!=null?""+ur(f):"",o=o!=null?""+ur(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),eh(s)}function nh(s,o,f){o==="number"&&ac(s.ownerDocument)===s||s.defaultValue===""+f||(s.defaultValue=""+f)}function la(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=""+ur(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 mx(s,o,f){if(o!=null&&(o=""+ur(o),o!==s.value&&(s.value=o),f==null)){s.defaultValue!==o&&(s.defaultValue=o);return}s.defaultValue=f!=null?""+ur(f):""}function px(s,o,f,g){if(o==null){if(g!=null){if(f!=null)throw Error(r(92));if(G(g)){if(1<g.length)throw Error(r(93));g=g[0]}f=g}f==null&&(f=""),o=f}f=ur(o),s.defaultValue=f,g=s.textContent,g===f&&g!==""&&g!==null&&(s.value=g),eh(s)}function ca(s,o){if(o){var f=s.firstChild;if(f&&f===s.lastChild&&f.nodeType===3){f.nodeValue=o;return}}s.textContent=o}var A2=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 gx(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||A2.has(o)?o==="float"?s.cssFloat=f:s[o]=(""+f).trim():s[o]=f+"px"}function xx(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&&gx(s,k,g)}else for(var A in o)o.hasOwnProperty(A)&&gx(s,A,o[A])}function rh(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 L2=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"]]),D2=/^[\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 oc(s){return D2.test(""+s)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":s}function Zr(){}var sh=null;function ih(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var ua=null,da=null;function yx(s){var o=ia(s);if(o&&(s=o.stateNode)){var f=s[at]||null;e:switch(s=o.stateNode,o.type){case"input":if(th(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="'+dr(""+o)+'"][type="radio"]'),o=0;o<f.length;o++){var g=f[o];if(g!==s&&g.form===s.form){var k=g[at]||null;if(!k)throw Error(r(90));th(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&&hx(g)}break e;case"textarea":mx(s,f.value,f.defaultValue);break e;case"select":o=f.value,o!=null&&la(s,!!f.multiple,o,!1)}}}var ah=!1;function bx(s,o,f){if(ah)return s(o,f);ah=!0;try{var g=s(o);return g}finally{if(ah=!1,(ua!==null||da!==null)&&(Kc(),ua&&(o=ua,s=da,da=ua=null,yx(o),s)))for(o=0;o<s.length;o++)yx(s[o])}}function vo(s,o){var f=s.stateNode;if(f===null)return null;var g=f[at]||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"),oh=!1;if(es)try{var _o={};Object.defineProperty(_o,"passive",{get:function(){oh=!0}}),window.addEventListener("test",_o,_o),window.removeEventListener("test",_o,_o)}catch{oh=!1}var Ls=null,lh=null,lc=null;function vx(){if(lc)return lc;var s,o=lh,f=o.length,g,k="value"in Ls?Ls.value:Ls.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 lc=k.slice(s,1<g?1-g:void 0)}function cc(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 uc(){return!0}function _x(){return!1}function Fn(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)?uc:_x,this.isPropagationStopped=_x,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=uc)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=uc)},persist:function(){},isPersistent:uc}),o}var bi={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(s){return s.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},dc=Fn(bi),So=m({},bi,{view:0,detail:0}),R2=Fn(So),ch,uh,wo,hc=m({},So,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:hh,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!==wo&&(wo&&s.type==="mousemove"?(ch=s.screenX-wo.screenX,uh=s.screenY-wo.screenY):uh=ch=0,wo=s),ch)},movementY:function(s){return"movementY"in s?s.movementY:uh}}),Sx=Fn(hc),O2=m({},hc,{dataTransfer:0}),I2=Fn(O2),M2=m({},So,{relatedTarget:0}),dh=Fn(M2),P2=m({},bi,{animationName:0,elapsedTime:0,pseudoElement:0}),B2=Fn(P2),$2=m({},bi,{clipboardData:function(s){return"clipboardData"in s?s.clipboardData:window.clipboardData}}),z2=Fn($2),H2=m({},bi,{data:0}),wx=Fn(H2),U2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},F2={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"},V2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function G2(s){var o=this.nativeEvent;return o.getModifierState?o.getModifierState(s):(s=V2[s])?!!o[s]:!1}function hh(){return G2}var W2=m({},So,{key:function(s){if(s.key){var o=U2[s.key]||s.key;if(o!=="Unidentified")return o}return s.type==="keypress"?(s=cc(s),s===13?"Enter":String.fromCharCode(s)):s.type==="keydown"||s.type==="keyup"?F2[s.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:hh,charCode:function(s){return s.type==="keypress"?cc(s):0},keyCode:function(s){return s.type==="keydown"||s.type==="keyup"?s.keyCode:0},which:function(s){return s.type==="keypress"?cc(s):s.type==="keydown"||s.type==="keyup"?s.keyCode:0}}),q2=Fn(W2),K2=m({},hc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Cx=Fn(K2),Y2=m({},So,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:hh}),X2=Fn(Y2),Q2=m({},bi,{propertyName:0,elapsedTime:0,pseudoElement:0}),J2=Fn(Q2),Z2=m({},hc,{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}),ej=Fn(Z2),tj=m({},bi,{newState:0,oldState:0}),nj=Fn(tj),rj=[9,13,27,32],fh=es&&"CompositionEvent"in window,Co=null;es&&"documentMode"in document&&(Co=document.documentMode);var sj=es&&"TextEvent"in window&&!Co,kx=es&&(!fh||Co&&8<Co&&11>=Co),jx=" ",Ex=!1;function Nx(s,o){switch(s){case"keyup":return rj.indexOf(o.keyCode)!==-1;case"keydown":return o.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Tx(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var ha=!1;function ij(s,o){switch(s){case"compositionend":return Tx(o);case"keypress":return o.which!==32?null:(Ex=!0,jx);case"textInput":return s=o.data,s===jx&&Ex?null:s;default:return null}}function aj(s,o){if(ha)return s==="compositionend"||!fh&&Nx(s,o)?(s=vx(),lc=lh=Ls=null,ha=!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 kx&&o.locale!=="ko"?null:o.data;default:return null}}var oj={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 Ax(s){var o=s&&s.nodeName&&s.nodeName.toLowerCase();return o==="input"?!!oj[s.type]:o==="textarea"}function Lx(s,o,f,g){ua?da?da.push(g):da=[g]:ua=g,o=tu(o,"onChange"),0<o.length&&(f=new dc("onChange","change",null,f,g),s.push({event:f,listeners:o}))}var ko=null,jo=null;function lj(s){fv(s,0)}function fc(s){var o=bo(s);if(hx(o))return s}function Dx(s,o){if(s==="change")return o}var Rx=!1;if(es){var mh;if(es){var ph="oninput"in document;if(!ph){var Ox=document.createElement("div");Ox.setAttribute("oninput","return;"),ph=typeof Ox.oninput=="function"}mh=ph}else mh=!1;Rx=mh&&(!document.documentMode||9<document.documentMode)}function Ix(){ko&&(ko.detachEvent("onpropertychange",Mx),jo=ko=null)}function Mx(s){if(s.propertyName==="value"&&fc(jo)){var o=[];Lx(o,jo,s,ih(s)),bx(lj,o)}}function cj(s,o,f){s==="focusin"?(Ix(),ko=o,jo=f,ko.attachEvent("onpropertychange",Mx)):s==="focusout"&&Ix()}function uj(s){if(s==="selectionchange"||s==="keyup"||s==="keydown")return fc(jo)}function dj(s,o){if(s==="click")return fc(o)}function hj(s,o){if(s==="input"||s==="change")return fc(o)}function fj(s,o){return s===o&&(s!==0||1/s===1/o)||s!==s&&o!==o}var er=typeof Object.is=="function"?Object.is:fj;function Eo(s,o){if(er(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(!ot.call(o,k)||!er(s[k],o[k]))return!1}return!0}function Px(s){for(;s&&s.firstChild;)s=s.firstChild;return s}function Bx(s,o){var f=Px(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=Px(f)}}function $x(s,o){return s&&o?s===o?!0:s&&s.nodeType===3?!1:o&&o.nodeType===3?$x(s,o.parentNode):"contains"in s?s.contains(o):s.compareDocumentPosition?!!(s.compareDocumentPosition(o)&16):!1:!1}function zx(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var o=ac(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=ac(s.document)}return o}function gh(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 mj=es&&"documentMode"in document&&11>=document.documentMode,fa=null,xh=null,No=null,yh=!1;function Hx(s,o,f){var g=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;yh||fa==null||fa!==ac(g)||(g=fa,"selectionStart"in g&&gh(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}),No&&Eo(No,g)||(No=g,g=tu(xh,"onSelect"),0<g.length&&(o=new dc("onSelect","select",null,o,f),s.push({event:o,listeners:g}),o.target=fa)))}function vi(s,o){var f={};return f[s.toLowerCase()]=o.toLowerCase(),f["Webkit"+s]="webkit"+o,f["Moz"+s]="moz"+o,f}var ma={animationend:vi("Animation","AnimationEnd"),animationiteration:vi("Animation","AnimationIteration"),animationstart:vi("Animation","AnimationStart"),transitionrun:vi("Transition","TransitionRun"),transitionstart:vi("Transition","TransitionStart"),transitioncancel:vi("Transition","TransitionCancel"),transitionend:vi("Transition","TransitionEnd")},bh={},Ux={};es&&(Ux=document.createElement("div").style,"AnimationEvent"in window||(delete ma.animationend.animation,delete ma.animationiteration.animation,delete ma.animationstart.animation),"TransitionEvent"in window||delete ma.transitionend.transition);function _i(s){if(bh[s])return bh[s];if(!ma[s])return s;var o=ma[s],f;for(f in o)if(o.hasOwnProperty(f)&&f in Ux)return bh[s]=o[f];return s}var Fx=_i("animationend"),Vx=_i("animationiteration"),Gx=_i("animationstart"),pj=_i("transitionrun"),gj=_i("transitionstart"),xj=_i("transitioncancel"),Wx=_i("transitionend"),qx=new Map,vh="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(" ");vh.push("scrollEnd");function jr(s,o){qx.set(s,o),yi(o,[s])}var mc=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)},hr=[],pa=0,_h=0;function pc(){for(var s=pa,o=_h=pa=0;o<s;){var f=hr[o];hr[o++]=null;var g=hr[o];hr[o++]=null;var k=hr[o];hr[o++]=null;var A=hr[o];if(hr[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&&Kx(f,k,A)}}function gc(s,o,f,g){hr[pa++]=s,hr[pa++]=o,hr[pa++]=f,hr[pa++]=g,_h|=g,s.lanes|=g,s=s.alternate,s!==null&&(s.lanes|=g)}function Sh(s,o,f,g){return gc(s,o,f,g),xc(s)}function Si(s,o){return gc(s,null,null,o),xc(s)}function Kx(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-tt(f),s=A.hiddenUpdates,g=s[k],g===null?s[k]=[o]:g.push(o),o.lane=f|536870912),A):null}function xc(s){if(50<Xo)throw Xo=0,Df=null,Error(r(185));for(var o=s.return;o!==null;)s=o,o=s.return;return s.tag===3?s.stateNode:null}var ga={};function yj(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 tr(s,o,f,g){return new yj(s,o,f,g)}function wh(s){return s=s.prototype,!(!s||!s.isReactComponent)}function ts(s,o){var f=s.alternate;return f===null?(f=tr(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 Yx(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 yc(s,o,f,g,k,A){var F=0;if(g=s,typeof s=="function")wh(s)&&(F=1);else if(typeof s=="string")F=wE(s,f,ne.current)?26:s==="html"||s==="head"||s==="body"?27:5;else e:switch(s){case O:return s=tr(31,f,o,k),s.elementType=O,s.lanes=A,s;case C:return wi(f.children,k,A,o);case _:F=8,k|=24;break;case S:return s=tr(12,f,o,k|2),s.elementType=S,s.lanes=A,s;case N:return s=tr(13,f,o,k),s.elementType=N,s.lanes=A,s;case T:return s=tr(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 j: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=tr(F,f,o,k),o.elementType=s,o.type=g,o.lanes=A,o}function wi(s,o,f,g){return s=tr(7,s,g,o),s.lanes=f,s}function Ch(s,o,f){return s=tr(6,s,null,o),s.lanes=f,s}function Xx(s){var o=tr(18,null,null,0);return o.stateNode=s,o}function kh(s,o,f){return o=tr(4,s.children!==null?s.children:[],s.key,o),o.lanes=f,o.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},o}var Qx=new WeakMap;function fr(s,o){if(typeof s=="object"&&s!==null){var f=Qx.get(s);return f!==void 0?f:(o={value:s,source:o,stack:st(o)},Qx.set(s,o),o)}return{value:s,source:o,stack:st(o)}}var xa=[],ya=0,bc=null,To=0,mr=[],pr=0,Ds=null,Br=1,$r="";function ns(s,o){xa[ya++]=To,xa[ya++]=bc,bc=s,To=o}function Jx(s,o,f){mr[pr++]=Br,mr[pr++]=$r,mr[pr++]=Ds,Ds=s;var g=Br;s=$r;var k=32-tt(g)-1;g&=~(1<<k),f+=1;var A=32-tt(o)+k;if(30<A){var F=k-k%5;A=(g&(1<<F)-1).toString(32),g>>=F,k-=F,Br=1<<32-tt(o)+k|f<<k|g,$r=A+s}else Br=1<<A|f<<k|g,$r=s}function jh(s){s.return!==null&&(ns(s,1),Jx(s,1,0))}function Eh(s){for(;s===bc;)bc=xa[--ya],xa[ya]=null,To=xa[--ya],xa[ya]=null;for(;s===Ds;)Ds=mr[--pr],mr[pr]=null,$r=mr[--pr],mr[pr]=null,Br=mr[--pr],mr[pr]=null}function Zx(s,o){mr[pr++]=Br,mr[pr++]=$r,mr[pr++]=Ds,Br=o.id,$r=o.overflow,Ds=s}var Cn=null,Wt=null,kt=!1,Rs=null,gr=!1,Nh=Error(r(519));function Os(s){var o=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ao(fr(o,s)),Nh}function ey(s){var o=s.stateNode,f=s.type,g=s.memoizedProps;switch(o[Qe]=s,o[at]=g,f){case"dialog":bt("cancel",o),bt("close",o);break;case"iframe":case"object":case"embed":bt("load",o);break;case"video":case"audio":for(f=0;f<Jo.length;f++)bt(Jo[f],o);break;case"source":bt("error",o);break;case"img":case"image":case"link":bt("error",o),bt("load",o);break;case"details":bt("toggle",o);break;case"input":bt("invalid",o),fx(o,g.value,g.defaultValue,g.checked,g.defaultChecked,g.type,g.name,!0);break;case"select":bt("invalid",o);break;case"textarea":bt("invalid",o),px(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||xv(o.textContent,f)?(g.popover!=null&&(bt("beforetoggle",o),bt("toggle",o)),g.onScroll!=null&&bt("scroll",o),g.onScrollEnd!=null&&bt("scrollend",o),g.onClick!=null&&(o.onclick=Zr),o=!0):o=!1,o||Os(s,!0)}function ty(s){for(Cn=s.return;Cn;)switch(Cn.tag){case 5:case 31:case 13:gr=!1;return;case 27:case 3:gr=!0;return;default:Cn=Cn.return}}function ba(s){if(s!==Cn)return!1;if(!kt)return ty(s),kt=!0,!1;var o=s.tag,f;if((f=o!==3&&o!==27)&&((f=o===5)&&(f=s.type,f=!(f!=="form"&&f!=="button")||qf(s.type,s.memoizedProps)),f=!f),f&&Wt&&Os(s),ty(s),o===13){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Wt=jv(s)}else if(o===31){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Wt=jv(s)}else o===27?(o=Wt,Ks(s.type)?(s=Jf,Jf=null,Wt=s):Wt=o):Wt=Cn?yr(s.stateNode.nextSibling):null;return!0}function Ci(){Wt=Cn=null,kt=!1}function Th(){var s=Rs;return s!==null&&(qn===null?qn=s:qn.push.apply(qn,s),Rs=null),s}function Ao(s){Rs===null?Rs=[s]:Rs.push(s)}var Ah=B(null),ki=null,rs=null;function Is(s,o,f){z(Ah,o._currentValue),o._currentValue=f}function ss(s){s._currentValue=Ah.current,q(Ah)}function Lh(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 Dh(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 le=0;le<o.length;le++)if(Y.context===o[le]){A.lanes|=f,Y=A.alternate,Y!==null&&(Y.lanes|=f),Lh(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),Lh(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 va(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;er(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(rl):s=[rl])}k=k.return}s!==null&&Dh(o,s,f,g),o.flags|=262144}function vc(s){for(s=s.firstContext;s!==null;){if(!er(s.context._currentValue,s.memoizedValue))return!0;s=s.next}return!1}function ji(s){ki=s,rs=null,s=s.dependencies,s!==null&&(s.firstContext=null)}function kn(s){return ny(ki,s)}function _c(s,o){return ki===null&&ji(s),ny(s,o)}function ny(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 bj=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()})}},vj=e.unstable_scheduleCallback,_j=e.unstable_NormalPriority,sn={$$typeof:b,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Rh(){return{controller:new bj,data:new Map,refCount:0}}function Lo(s){s.refCount--,s.refCount===0&&vj(_j,function(){s.controller.abort()})}var Do=null,Oh=0,_a=0,Sa=null;function Sj(s,o){if(Do===null){var f=Do=[];Oh=0,_a=Bf(),Sa={status:"pending",value:void 0,then:function(g){f.push(g)}}}return Oh++,o.then(ry,ry),o}function ry(){if(--Oh===0&&Do!==null){Sa!==null&&(Sa.status="fulfilled");var s=Do;Do=null,_a=0,Sa=null;for(var o=0;o<s.length;o++)(0,s[o])()}}function wj(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 sy=V.S;V.S=function(s,o){Hb=Ie(),typeof o=="object"&&o!==null&&typeof o.then=="function"&&Sj(s,o),sy!==null&&sy(s,o)};var Ei=B(null);function Ih(){var s=Ei.current;return s!==null?s:$t.pooledCache}function Sc(s,o){o===null?z(Ei,Ei.current):z(Ei,o.pool)}function iy(){var s=Ih();return s===null?null:{parent:sn._currentValue,pool:s}}var wa=Error(r(460)),Mh=Error(r(474)),wc=Error(r(542)),Cc={then:function(){}};function ay(s){return s=s.status,s==="fulfilled"||s==="rejected"}function oy(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,cy(s),s;default:if(typeof o.status=="string")o.then(Zr,Zr);else{if(s=$t,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,cy(s),s}throw Ti=o,wa}}function Ni(s){try{var o=s._init;return o(s._payload)}catch(f){throw f!==null&&typeof f=="object"&&typeof f.then=="function"?(Ti=f,wa):f}}var Ti=null;function ly(){if(Ti===null)throw Error(r(459));var s=Ti;return Ti=null,s}function cy(s){if(s===wa||s===wc)throw Error(r(483))}var Ca=null,Ro=0;function kc(s){var o=Ro;return Ro+=1,Ca===null&&(Ca=[]),oy(Ca,s,o)}function Oo(s,o){o=o.props.ref,s.ref=o!==void 0?o:null}function jc(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 uy(s){function o(de,ue){if(s){var pe=de.deletions;pe===null?(de.deletions=[ue],de.flags|=16):pe.push(ue)}}function f(de,ue){if(!s)return null;for(;ue!==null;)o(de,ue),ue=ue.sibling;return null}function g(de){for(var ue=new Map;de!==null;)de.key!==null?ue.set(de.key,de):ue.set(de.index,de),de=de.sibling;return ue}function k(de,ue){return de=ts(de,ue),de.index=0,de.sibling=null,de}function A(de,ue,pe){return de.index=pe,s?(pe=de.alternate,pe!==null?(pe=pe.index,pe<ue?(de.flags|=67108866,ue):pe):(de.flags|=67108866,ue)):(de.flags|=1048576,ue)}function F(de){return s&&de.alternate===null&&(de.flags|=67108866),de}function Y(de,ue,pe,Ne){return ue===null||ue.tag!==6?(ue=Ch(pe,de.mode,Ne),ue.return=de,ue):(ue=k(ue,pe),ue.return=de,ue)}function le(de,ue,pe,Ne){var et=pe.type;return et===C?ke(de,ue,pe.props.children,Ne,pe.key):ue!==null&&(ue.elementType===et||typeof et=="object"&&et!==null&&et.$$typeof===L&&Ni(et)===ue.type)?(ue=k(ue,pe.props),Oo(ue,pe),ue.return=de,ue):(ue=yc(pe.type,pe.key,pe.props,null,de.mode,Ne),Oo(ue,pe),ue.return=de,ue)}function ge(de,ue,pe,Ne){return ue===null||ue.tag!==4||ue.stateNode.containerInfo!==pe.containerInfo||ue.stateNode.implementation!==pe.implementation?(ue=kh(pe,de.mode,Ne),ue.return=de,ue):(ue=k(ue,pe.children||[]),ue.return=de,ue)}function ke(de,ue,pe,Ne,et){return ue===null||ue.tag!==7?(ue=wi(pe,de.mode,Ne,et),ue.return=de,ue):(ue=k(ue,pe),ue.return=de,ue)}function Ae(de,ue,pe){if(typeof ue=="string"&&ue!==""||typeof ue=="number"||typeof ue=="bigint")return ue=Ch(""+ue,de.mode,pe),ue.return=de,ue;if(typeof ue=="object"&&ue!==null){switch(ue.$$typeof){case y:return pe=yc(ue.type,ue.key,ue.props,null,de.mode,pe),Oo(pe,ue),pe.return=de,pe;case w:return ue=kh(ue,de.mode,pe),ue.return=de,ue;case L:return ue=Ni(ue),Ae(de,ue,pe)}if(G(ue)||U(ue))return ue=wi(ue,de.mode,pe,null),ue.return=de,ue;if(typeof ue.then=="function")return Ae(de,kc(ue),pe);if(ue.$$typeof===b)return Ae(de,_c(de,ue),pe);jc(de,ue)}return null}function xe(de,ue,pe,Ne){var et=ue!==null?ue.key:null;if(typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint")return et!==null?null:Y(de,ue,""+pe,Ne);if(typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case y:return pe.key===et?le(de,ue,pe,Ne):null;case w:return pe.key===et?ge(de,ue,pe,Ne):null;case L:return pe=Ni(pe),xe(de,ue,pe,Ne)}if(G(pe)||U(pe))return et!==null?null:ke(de,ue,pe,Ne,null);if(typeof pe.then=="function")return xe(de,ue,kc(pe),Ne);if(pe.$$typeof===b)return xe(de,ue,_c(de,pe),Ne);jc(de,pe)}return null}function be(de,ue,pe,Ne,et){if(typeof Ne=="string"&&Ne!==""||typeof Ne=="number"||typeof Ne=="bigint")return de=de.get(pe)||null,Y(ue,de,""+Ne,et);if(typeof Ne=="object"&&Ne!==null){switch(Ne.$$typeof){case y:return de=de.get(Ne.key===null?pe:Ne.key)||null,le(ue,de,Ne,et);case w:return de=de.get(Ne.key===null?pe:Ne.key)||null,ge(ue,de,Ne,et);case L:return Ne=Ni(Ne),be(de,ue,pe,Ne,et)}if(G(Ne)||U(Ne))return de=de.get(pe)||null,ke(ue,de,Ne,et,null);if(typeof Ne.then=="function")return be(de,ue,pe,kc(Ne),et);if(Ne.$$typeof===b)return be(de,ue,pe,_c(ue,Ne),et);jc(ue,Ne)}return null}function Ke(de,ue,pe,Ne){for(var et=null,Tt=null,Xe=ue,mt=ue=0,Ct=null;Xe!==null&&mt<pe.length;mt++){Xe.index>mt?(Ct=Xe,Xe=null):Ct=Xe.sibling;var At=xe(de,Xe,pe[mt],Ne);if(At===null){Xe===null&&(Xe=Ct);break}s&&Xe&&At.alternate===null&&o(de,Xe),ue=A(At,ue,mt),Tt===null?et=At:Tt.sibling=At,Tt=At,Xe=Ct}if(mt===pe.length)return f(de,Xe),kt&&ns(de,mt),et;if(Xe===null){for(;mt<pe.length;mt++)Xe=Ae(de,pe[mt],Ne),Xe!==null&&(ue=A(Xe,ue,mt),Tt===null?et=Xe:Tt.sibling=Xe,Tt=Xe);return kt&&ns(de,mt),et}for(Xe=g(Xe);mt<pe.length;mt++)Ct=be(Xe,de,mt,pe[mt],Ne),Ct!==null&&(s&&Ct.alternate!==null&&Xe.delete(Ct.key===null?mt:Ct.key),ue=A(Ct,ue,mt),Tt===null?et=Ct:Tt.sibling=Ct,Tt=Ct);return s&&Xe.forEach(function(Zs){return o(de,Zs)}),kt&&ns(de,mt),et}function it(de,ue,pe,Ne){if(pe==null)throw Error(r(151));for(var et=null,Tt=null,Xe=ue,mt=ue=0,Ct=null,At=pe.next();Xe!==null&&!At.done;mt++,At=pe.next()){Xe.index>mt?(Ct=Xe,Xe=null):Ct=Xe.sibling;var Zs=xe(de,Xe,At.value,Ne);if(Zs===null){Xe===null&&(Xe=Ct);break}s&&Xe&&Zs.alternate===null&&o(de,Xe),ue=A(Zs,ue,mt),Tt===null?et=Zs:Tt.sibling=Zs,Tt=Zs,Xe=Ct}if(At.done)return f(de,Xe),kt&&ns(de,mt),et;if(Xe===null){for(;!At.done;mt++,At=pe.next())At=Ae(de,At.value,Ne),At!==null&&(ue=A(At,ue,mt),Tt===null?et=At:Tt.sibling=At,Tt=At);return kt&&ns(de,mt),et}for(Xe=g(Xe);!At.done;mt++,At=pe.next())At=be(Xe,de,mt,At.value,Ne),At!==null&&(s&&At.alternate!==null&&Xe.delete(At.key===null?mt:At.key),ue=A(At,ue,mt),Tt===null?et=At:Tt.sibling=At,Tt=At);return s&&Xe.forEach(function(OE){return o(de,OE)}),kt&&ns(de,mt),et}function Mt(de,ue,pe,Ne){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 et=pe.key;ue!==null;){if(ue.key===et){if(et=pe.type,et===C){if(ue.tag===7){f(de,ue.sibling),Ne=k(ue,pe.props.children),Ne.return=de,de=Ne;break e}}else if(ue.elementType===et||typeof et=="object"&&et!==null&&et.$$typeof===L&&Ni(et)===ue.type){f(de,ue.sibling),Ne=k(ue,pe.props),Oo(Ne,pe),Ne.return=de,de=Ne;break e}f(de,ue);break}else o(de,ue);ue=ue.sibling}pe.type===C?(Ne=wi(pe.props.children,de.mode,Ne,pe.key),Ne.return=de,de=Ne):(Ne=yc(pe.type,pe.key,pe.props,null,de.mode,Ne),Oo(Ne,pe),Ne.return=de,de=Ne)}return F(de);case w:e:{for(et=pe.key;ue!==null;){if(ue.key===et)if(ue.tag===4&&ue.stateNode.containerInfo===pe.containerInfo&&ue.stateNode.implementation===pe.implementation){f(de,ue.sibling),Ne=k(ue,pe.children||[]),Ne.return=de,de=Ne;break e}else{f(de,ue);break}else o(de,ue);ue=ue.sibling}Ne=kh(pe,de.mode,Ne),Ne.return=de,de=Ne}return F(de);case L:return pe=Ni(pe),Mt(de,ue,pe,Ne)}if(G(pe))return Ke(de,ue,pe,Ne);if(U(pe)){if(et=U(pe),typeof et!="function")throw Error(r(150));return pe=et.call(pe),it(de,ue,pe,Ne)}if(typeof pe.then=="function")return Mt(de,ue,kc(pe),Ne);if(pe.$$typeof===b)return Mt(de,ue,_c(de,pe),Ne);jc(de,pe)}return typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint"?(pe=""+pe,ue!==null&&ue.tag===6?(f(de,ue.sibling),Ne=k(ue,pe),Ne.return=de,de=Ne):(f(de,ue),Ne=Ch(pe,de.mode,Ne),Ne.return=de,de=Ne),F(de)):f(de,ue)}return function(de,ue,pe,Ne){try{Ro=0;var et=Mt(de,ue,pe,Ne);return Ca=null,et}catch(Xe){if(Xe===wa||Xe===wc)throw Xe;var Tt=tr(29,Xe,null,de.mode);return Tt.lanes=Ne,Tt.return=de,Tt}finally{}}}var Ai=uy(!0),dy=uy(!1),Ms=!1;function Ph(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Bh(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 Ps(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function Bs(s,o,f){var g=s.updateQueue;if(g===null)return null;if(g=g.shared,(Lt&2)!==0){var k=g.pending;return k===null?o.next=o:(o.next=k.next,k.next=o),g.pending=o,o=xc(s),Kx(s,null,f),o}return gc(s,g,o,f),xc(s)}function Io(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,Ts(s,f)}}function $h(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 zh=!1;function Mo(){if(zh){var s=Sa;if(s!==null)throw s}}function Po(s,o,f,g){zh=!1;var k=s.updateQueue;Ms=!1;var A=k.firstBaseUpdate,F=k.lastBaseUpdate,Y=k.shared.pending;if(Y!==null){k.shared.pending=null;var le=Y,ge=le.next;le.next=null,F===null?A=ge:F.next=ge,F=le;var ke=s.alternate;ke!==null&&(ke=ke.updateQueue,Y=ke.lastBaseUpdate,Y!==F&&(Y===null?ke.firstBaseUpdate=ge:Y.next=ge,ke.lastBaseUpdate=le))}if(A!==null){var Ae=k.baseState;F=0,ke=ge=le=null,Y=A;do{var xe=Y.lane&-536870913,be=xe!==Y.lane;if(be?(wt&xe)===xe:(g&xe)===xe){xe!==0&&xe===_a&&(zh=!0),ke!==null&&(ke=ke.next={lane:0,tag:Y.tag,payload:Y.payload,callback:null,next:null});e:{var Ke=s,it=Y;xe=o;var Mt=f;switch(it.tag){case 1:if(Ke=it.payload,typeof Ke=="function"){Ae=Ke.call(Mt,Ae,xe);break e}Ae=Ke;break e;case 3:Ke.flags=Ke.flags&-65537|128;case 0:if(Ke=it.payload,xe=typeof Ke=="function"?Ke.call(Mt,Ae,xe):Ke,xe==null)break e;Ae=m({},Ae,xe);break e;case 2:Ms=!0}}xe=Y.callback,xe!==null&&(s.flags|=64,be&&(s.flags|=8192),be=k.callbacks,be===null?k.callbacks=[xe]:be.push(xe))}else be={lane:xe,tag:Y.tag,payload:Y.payload,callback:Y.callback,next:null},ke===null?(ge=ke=be,le=Ae):ke=ke.next=be,F|=xe;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&&(le=Ae),k.baseState=le,k.firstBaseUpdate=ge,k.lastBaseUpdate=ke,A===null&&(k.shared.lanes=0),Fs|=F,s.lanes=F,s.memoizedState=Ae}}function hy(s,o){if(typeof s!="function")throw Error(r(191,s));s.call(o)}function fy(s,o){var f=s.callbacks;if(f!==null)for(s.callbacks=null,s=0;s<f.length;s++)hy(f[s],o)}var ka=B(null),Ec=B(0);function my(s,o){s=fs,z(Ec,s),z(ka,o),fs=s|o.baseLanes}function Hh(){z(Ec,fs),z(ka,ka.current)}function Uh(){fs=Ec.current,q(ka),q(Ec)}var nr=B(null),xr=null;function $s(s){var o=s.alternate;z(en,en.current&1),z(nr,s),xr===null&&(o===null||ka.current!==null||o.memoizedState!==null)&&(xr=s)}function Fh(s){z(en,en.current),z(nr,s),xr===null&&(xr=s)}function py(s){s.tag===22?(z(en,en.current),z(nr,s),xr===null&&(xr=s)):zs()}function zs(){z(en,en.current),z(nr,nr.current)}function rr(s){q(nr),xr===s&&(xr=null),q(en)}var en=B(0);function Nc(s){for(var o=s;o!==null;){if(o.tag===13){var f=o.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||Xf(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,ft=null,Ot=null,an=null,Tc=!1,ja=!1,Li=!1,Ac=0,Bo=0,Ea=null,Cj=0;function Qt(){throw Error(r(321))}function Vh(s,o){if(o===null)return!1;for(var f=0;f<o.length&&f<s.length;f++)if(!er(s[f],o[f]))return!1;return!0}function Gh(s,o,f,g,k,A){return is=A,ft=o,o.memoizedState=null,o.updateQueue=null,o.lanes=0,V.H=s===null||s.memoizedState===null?Jy:of,Li=!1,A=f(g,k),Li=!1,ja&&(A=xy(o,f,g,k)),gy(s),A}function gy(s){V.H=Ho;var o=Ot!==null&&Ot.next!==null;if(is=0,an=Ot=ft=null,Tc=!1,Bo=0,Ea=null,o)throw Error(r(300));s===null||on||(s=s.dependencies,s!==null&&vc(s)&&(on=!0))}function xy(s,o,f,g){ft=s;var k=0;do{if(ja&&(Ea=null),Bo=0,ja=!1,25<=k)throw Error(r(301));if(k+=1,an=Ot=null,s.updateQueue!=null){var A=s.updateQueue;A.lastEffect=null,A.events=null,A.stores=null,A.memoCache!=null&&(A.memoCache.index=0)}V.H=Zy,A=o(f,g)}while(ja);return A}function kj(){var s=V.H,o=s.useState()[0];return o=typeof o.then=="function"?$o(o):o,s=s.useState()[0],(Ot!==null?Ot.memoizedState:null)!==s&&(ft.flags|=1024),o}function Wh(){var s=Ac!==0;return Ac=0,s}function qh(s,o,f){o.updateQueue=s.updateQueue,o.flags&=-2053,s.lanes&=~f}function Kh(s){if(Tc){for(s=s.memoizedState;s!==null;){var o=s.queue;o!==null&&(o.pending=null),s=s.next}Tc=!1}is=0,an=Ot=ft=null,ja=!1,Bo=Ac=0,Ea=null}function Pn(){var s={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return an===null?ft.memoizedState=an=s:an=an.next=s,an}function tn(){if(Ot===null){var s=ft.alternate;s=s!==null?s.memoizedState:null}else s=Ot.next;var o=an===null?ft.memoizedState:an.next;if(o!==null)an=o,Ot=s;else{if(s===null)throw ft.alternate===null?Error(r(467)):Error(r(310));Ot=s,s={memoizedState:Ot.memoizedState,baseState:Ot.baseState,baseQueue:Ot.baseQueue,queue:Ot.queue,next:null},an===null?ft.memoizedState=an=s:an=an.next=s}return an}function Lc(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function $o(s){var o=Bo;return Bo+=1,Ea===null&&(Ea=[]),s=oy(Ea,s,o),o=ft,(an===null?o.memoizedState:an.next)===null&&(o=o.alternate,V.H=o===null||o.memoizedState===null?Jy:of),s}function Dc(s){if(s!==null&&typeof s=="object"){if(typeof s.then=="function")return $o(s);if(s.$$typeof===b)return kn(s)}throw Error(r(438,String(s)))}function Yh(s){var o=null,f=ft.updateQueue;if(f!==null&&(o=f.memoCache),o==null){var g=ft.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=Lc(),ft.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]=M;return o.index++,f}function as(s,o){return typeof o=="function"?o(s):o}function Rc(s){var o=tn();return Xh(o,Ot,s)}function Xh(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,le=null,ge=o,ke=!1;do{var Ae=ge.lane&-536870913;if(Ae!==ge.lane?(wt&Ae)===Ae:(is&Ae)===Ae){var xe=ge.revertLane;if(xe===0)le!==null&&(le=le.next={lane:0,revertLane:0,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null}),Ae===_a&&(ke=!0);else if((is&xe)===xe){ge=ge.next,xe===_a&&(ke=!0);continue}else Ae={lane:0,revertLane:ge.revertLane,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},le===null?(Y=le=Ae,F=A):le=le.next=Ae,ft.lanes|=xe,Fs|=xe;Ae=ge.action,Li&&f(A,Ae),A=ge.hasEagerState?ge.eagerState:f(A,Ae)}else xe={lane:Ae,revertLane:ge.revertLane,gesture:ge.gesture,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},le===null?(Y=le=xe,F=A):le=le.next=xe,ft.lanes|=Ae,Fs|=Ae;ge=ge.next}while(ge!==null&&ge!==o);if(le===null?F=A:le.next=Y,!er(A,s.memoizedState)&&(on=!0,ke&&(f=Sa,f!==null)))throw f;s.memoizedState=A,s.baseState=F,s.baseQueue=le,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);er(A,o.memoizedState)||(on=!0),o.memoizedState=A,o.baseQueue===null&&(o.baseState=A),f.lastRenderedState=A}return[A,g]}function yy(s,o,f){var g=ft,k=tn(),A=kt;if(A){if(f===void 0)throw Error(r(407));f=f()}else f=o();var F=!er((Ot||k).memoizedState,f);if(F&&(k.memoizedState=f,on=!0),k=k.queue,ef(_y.bind(null,g,k,s),[s]),k.getSnapshot!==o||F||an!==null&&an.memoizedState.tag&1){if(g.flags|=2048,Na(9,{destroy:void 0},vy.bind(null,g,k,f,o),null),$t===null)throw Error(r(349));A||(is&127)!==0||by(g,o,f)}return f}function by(s,o,f){s.flags|=16384,s={getSnapshot:o,value:f},o=ft.updateQueue,o===null?(o=Lc(),ft.updateQueue=o,o.stores=[s]):(f=o.stores,f===null?o.stores=[s]:f.push(s))}function vy(s,o,f,g){o.value=f,o.getSnapshot=g,Sy(o)&&wy(s)}function _y(s,o,f){return f(function(){Sy(o)&&wy(s)})}function Sy(s){var o=s.getSnapshot;s=s.value;try{var f=o();return!er(s,f)}catch{return!0}}function wy(s){var o=Si(s,2);o!==null&&Kn(o,s,2)}function Jh(s){var o=Pn();if(typeof s=="function"){var f=s;if(s=f(),Li){Ze(!0);try{f()}finally{Ze(!1)}}}return o.memoizedState=o.baseState=s,o.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:s},o}function Cy(s,o,f,g){return s.baseState=f,Xh(s,Ot,typeof g=="function"?g:as)}function jj(s,o,f,g,k){if(Mc(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)}};V.T!==null?f(!0):A.isTransition=!1,g(A),f=o.pending,f===null?(A.next=o.pending=A,ky(o,A)):(A.next=f.next,o.pending=f.next=A)}}function ky(s,o){var f=o.action,g=o.payload,k=s.state;if(o.isTransition){var A=V.T,F={};V.T=F;try{var Y=f(k,g),le=V.S;le!==null&&le(F,Y),jy(s,o,Y)}catch(ge){Zh(s,o,ge)}finally{A!==null&&F.types!==null&&(A.types=F.types),V.T=A}}else try{A=f(k,g),jy(s,o,A)}catch(ge){Zh(s,o,ge)}}function jy(s,o,f){f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(function(g){Ey(s,o,g)},function(g){return Zh(s,o,g)}):Ey(s,o,f)}function Ey(s,o,f){o.status="fulfilled",o.value=f,Ny(o),s.state=f,o=s.pending,o!==null&&(f=o.next,f===o?s.pending=null:(f=f.next,o.next=f,ky(s,f)))}function Zh(s,o,f){var g=s.pending;if(s.pending=null,g!==null){g=g.next;do o.status="rejected",o.reason=f,Ny(o),o=o.next;while(o!==g)}s.action=null}function Ny(s){s=s.listeners;for(var o=0;o<s.length;o++)(0,s[o])()}function Ty(s,o){return o}function Ay(s,o){if(kt){var f=$t.formState;if(f!==null){e:{var g=ft;if(kt){if(Wt){t:{for(var k=Wt,A=gr;k.nodeType!==8;){if(!A){k=null;break t}if(k=yr(k.nextSibling),k===null){k=null;break t}}A=k.data,k=A==="F!"||A==="F"?k:null}if(k){Wt=yr(k.nextSibling),g=k.data==="F!";break e}}Os(g)}g=!1}g&&(o=f[0])}}return f=Pn(),f.memoizedState=f.baseState=o,g={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ty,lastRenderedState:o},f.queue=g,f=Yy.bind(null,ft,g),g.dispatch=f,g=Jh(!1),A=af.bind(null,ft,!1,g.queue),g=Pn(),k={state:o,dispatch:null,action:s,pending:null},g.queue=k,f=jj.bind(null,ft,k,A,f),k.dispatch=f,g.memoizedState=s,[o,f,!1]}function Ly(s){var o=tn();return Dy(o,Ot,s)}function Dy(s,o,f){if(o=Xh(s,o,Ty)[0],s=Rc(as)[0],typeof o=="object"&&o!==null&&typeof o.then=="function")try{var g=$o(o)}catch(F){throw F===wa?wc:F}else g=o;o=tn();var k=o.queue,A=k.dispatch;return f!==o.memoizedState&&(ft.flags|=2048,Na(9,{destroy:void 0},Ej.bind(null,k,f),null)),[g,A,s]}function Ej(s,o){s.action=o}function Ry(s){var o=tn(),f=Ot;if(f!==null)return Dy(o,f,s);tn(),o=o.memoizedState,f=tn();var g=f.queue.dispatch;return f.memoizedState=s,[o,g,!1]}function Na(s,o,f,g){return s={tag:s,create:f,deps:g,inst:o,next:null},o=ft.updateQueue,o===null&&(o=Lc(),ft.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 Oy(){return tn().memoizedState}function Oc(s,o,f,g){var k=Pn();ft.flags|=s,k.memoizedState=Na(1|o,{destroy:void 0},f,g===void 0?null:g)}function Ic(s,o,f,g){var k=tn();g=g===void 0?null:g;var A=k.memoizedState.inst;Ot!==null&&g!==null&&Vh(g,Ot.memoizedState.deps)?k.memoizedState=Na(o,A,f,g):(ft.flags|=s,k.memoizedState=Na(1|o,A,f,g))}function Iy(s,o){Oc(8390656,8,s,o)}function ef(s,o){Ic(2048,8,s,o)}function Nj(s){ft.flags|=4;var o=ft.updateQueue;if(o===null)o=Lc(),ft.updateQueue=o,o.events=[s];else{var f=o.events;f===null?o.events=[s]:f.push(s)}}function My(s){var o=tn().memoizedState;return Nj({ref:o,nextImpl:s}),function(){if((Lt&2)!==0)throw Error(r(440));return o.impl.apply(void 0,arguments)}}function Py(s,o){return Ic(4,2,s,o)}function By(s,o){return Ic(4,4,s,o)}function $y(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 zy(s,o,f){f=f!=null?f.concat([s]):null,Ic(4,4,$y.bind(null,o,s),f)}function tf(){}function Hy(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;return o!==null&&Vh(o,g[1])?g[0]:(f.memoizedState=[s,o],s)}function Uy(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;if(o!==null&&Vh(o,g[1]))return g[0];if(g=s(),Li){Ze(!0);try{s()}finally{Ze(!1)}}return f.memoizedState=[g,o],g}function nf(s,o,f){return f===void 0||(is&1073741824)!==0&&(wt&261930)===0?s.memoizedState=o:(s.memoizedState=f,s=Fb(),ft.lanes|=s,Fs|=s,f)}function Fy(s,o,f,g){return er(f,o)?f:ka.current!==null?(s=nf(s,f,g),er(s,o)||(on=!0),s):(is&42)===0||(is&1073741824)!==0&&(wt&261930)===0?(on=!0,s.memoizedState=f):(s=Fb(),ft.lanes|=s,Fs|=s,o)}function Vy(s,o,f,g,k){var A=Z.p;Z.p=A!==0&&8>A?A:8;var F=V.T,Y={};V.T=Y,af(s,!1,o,f);try{var le=k(),ge=V.S;if(ge!==null&&ge(Y,le),le!==null&&typeof le=="object"&&typeof le.then=="function"){var ke=wj(le,g);zo(s,o,ke,ar(s))}else zo(s,o,g,ar(s))}catch(Ae){zo(s,o,{then:function(){},status:"rejected",reason:Ae},ar())}finally{Z.p=A,F!==null&&Y.types!==null&&(F.types=Y.types),V.T=F}}function Tj(){}function rf(s,o,f,g){if(s.tag!==5)throw Error(r(476));var k=Gy(s).queue;Vy(s,k,o,X,f===null?Tj:function(){return Wy(s),f(g)})}function Gy(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 Wy(s){var o=Gy(s);o.next===null&&(o=s.alternate.memoizedState),zo(s,o.next.queue,{},ar())}function sf(){return kn(rl)}function qy(){return tn().memoizedState}function Ky(){return tn().memoizedState}function Aj(s){for(var o=s.return;o!==null;){switch(o.tag){case 24:case 3:var f=ar();s=Ps(f);var g=Bs(o,s,f);g!==null&&(Kn(g,o,f),Io(g,o,f)),o={cache:Rh()},s.payload=o;return}o=o.return}}function Lj(s,o,f){var g=ar();f={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null},Mc(s)?Xy(o,f):(f=Sh(s,o,f,g),f!==null&&(Kn(f,s,g),Qy(f,o,g)))}function Yy(s,o,f){var g=ar();zo(s,o,f,g)}function zo(s,o,f,g){var k={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null};if(Mc(s))Xy(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,er(Y,F))return gc(s,o,k,0),$t===null&&pc(),!1}catch{}finally{}if(f=Sh(s,o,k,g),f!==null)return Kn(f,s,g),Qy(f,o,g),!0}return!1}function af(s,o,f,g){if(g={lane:2,revertLane:Bf(),gesture:null,action:g,hasEagerState:!1,eagerState:null,next:null},Mc(s)){if(o)throw Error(r(479))}else o=Sh(s,f,g,2),o!==null&&Kn(o,s,2)}function Mc(s){var o=s.alternate;return s===ft||o!==null&&o===ft}function Xy(s,o){ja=Tc=!0;var f=s.pending;f===null?o.next=o:(o.next=f.next,f.next=o),s.pending=o}function Qy(s,o,f){if((f&4194048)!==0){var g=o.lanes;g&=s.pendingLanes,f|=g,o.lanes=f,Ts(s,f)}}var Ho={readContext:kn,use:Dc,useCallback:Qt,useContext:Qt,useEffect:Qt,useImperativeHandle:Qt,useLayoutEffect:Qt,useInsertionEffect:Qt,useMemo:Qt,useReducer:Qt,useRef:Qt,useState:Qt,useDebugValue:Qt,useDeferredValue:Qt,useTransition:Qt,useSyncExternalStore:Qt,useId:Qt,useHostTransitionStatus:Qt,useFormState:Qt,useActionState:Qt,useOptimistic:Qt,useMemoCache:Qt,useCacheRefresh:Qt};Ho.useEffectEvent=Qt;var Jy={readContext:kn,use:Dc,useCallback:function(s,o){return Pn().memoizedState=[s,o===void 0?null:o],s},useContext:kn,useEffect:Iy,useImperativeHandle:function(s,o,f){f=f!=null?f.concat([s]):null,Oc(4194308,4,$y.bind(null,o,s),f)},useLayoutEffect:function(s,o){return Oc(4194308,4,s,o)},useInsertionEffect:function(s,o){Oc(4,2,s,o)},useMemo:function(s,o){var f=Pn();o=o===void 0?null:o;var g=s();if(Li){Ze(!0);try{s()}finally{Ze(!1)}}return f.memoizedState=[g,o],g},useReducer:function(s,o,f){var g=Pn();if(f!==void 0){var k=f(o);if(Li){Ze(!0);try{f(o)}finally{Ze(!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=Lj.bind(null,ft,s),[g.memoizedState,s]},useRef:function(s){var o=Pn();return s={current:s},o.memoizedState=s},useState:function(s){s=Jh(s);var o=s.queue,f=Yy.bind(null,ft,o);return o.dispatch=f,[s.memoizedState,f]},useDebugValue:tf,useDeferredValue:function(s,o){var f=Pn();return nf(f,s,o)},useTransition:function(){var s=Jh(!1);return s=Vy.bind(null,ft,s.queue,!0,!1),Pn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,o,f){var g=ft,k=Pn();if(kt){if(f===void 0)throw Error(r(407));f=f()}else{if(f=o(),$t===null)throw Error(r(349));(wt&127)!==0||by(g,o,f)}k.memoizedState=f;var A={value:f,getSnapshot:o};return k.queue=A,Iy(_y.bind(null,g,A,s),[s]),g.flags|=2048,Na(9,{destroy:void 0},vy.bind(null,g,A,f,o),null),f},useId:function(){var s=Pn(),o=$t.identifierPrefix;if(kt){var f=$r,g=Br;f=(g&~(1<<32-tt(g)-1)).toString(32)+f,o="_"+o+"R_"+f,f=Ac++,0<f&&(o+="H"+f.toString(32)),o+="_"}else f=Cj++,o="_"+o+"r_"+f.toString(32)+"_";return s.memoizedState=o},useHostTransitionStatus:sf,useFormState:Ay,useActionState:Ay,useOptimistic:function(s){var o=Pn();o.memoizedState=o.baseState=s;var f={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return o.queue=f,o=af.bind(null,ft,!0,f),f.dispatch=o,[s,o]},useMemoCache:Yh,useCacheRefresh:function(){return Pn().memoizedState=Aj.bind(null,ft)},useEffectEvent:function(s){var o=Pn(),f={impl:s};return o.memoizedState=f,function(){if((Lt&2)!==0)throw Error(r(440));return f.impl.apply(void 0,arguments)}}},of={readContext:kn,use:Dc,useCallback:Hy,useContext:kn,useEffect:ef,useImperativeHandle:zy,useInsertionEffect:Py,useLayoutEffect:By,useMemo:Uy,useReducer:Rc,useRef:Oy,useState:function(){return Rc(as)},useDebugValue:tf,useDeferredValue:function(s,o){var f=tn();return Fy(f,Ot.memoizedState,s,o)},useTransition:function(){var s=Rc(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:$o(s),o]},useSyncExternalStore:yy,useId:qy,useHostTransitionStatus:sf,useFormState:Ly,useActionState:Ly,useOptimistic:function(s,o){var f=tn();return Cy(f,Ot,s,o)},useMemoCache:Yh,useCacheRefresh:Ky};of.useEffectEvent=My;var Zy={readContext:kn,use:Dc,useCallback:Hy,useContext:kn,useEffect:ef,useImperativeHandle:zy,useInsertionEffect:Py,useLayoutEffect:By,useMemo:Uy,useReducer:Qh,useRef:Oy,useState:function(){return Qh(as)},useDebugValue:tf,useDeferredValue:function(s,o){var f=tn();return Ot===null?nf(f,s,o):Fy(f,Ot.memoizedState,s,o)},useTransition:function(){var s=Qh(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:$o(s),o]},useSyncExternalStore:yy,useId:qy,useHostTransitionStatus:sf,useFormState:Ry,useActionState:Ry,useOptimistic:function(s,o){var f=tn();return Ot!==null?Cy(f,Ot,s,o):(f.baseState=s,[s,f.queue.dispatch])},useMemoCache:Yh,useCacheRefresh:Ky};Zy.useEffectEvent=My;function lf(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 cf={enqueueSetState:function(s,o,f){s=s._reactInternals;var g=ar(),k=Ps(g);k.payload=o,f!=null&&(k.callback=f),o=Bs(s,k,g),o!==null&&(Kn(o,s,g),Io(o,s,g))},enqueueReplaceState:function(s,o,f){s=s._reactInternals;var g=ar(),k=Ps(g);k.tag=1,k.payload=o,f!=null&&(k.callback=f),o=Bs(s,k,g),o!==null&&(Kn(o,s,g),Io(o,s,g))},enqueueForceUpdate:function(s,o){s=s._reactInternals;var f=ar(),g=Ps(f);g.tag=2,o!=null&&(g.callback=o),o=Bs(s,g,f),o!==null&&(Kn(o,s,f),Io(o,s,f))}};function eb(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?!Eo(f,g)||!Eo(k,A):!0}function tb(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&&cf.enqueueReplaceState(o,o.state,null)}function Di(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 nb(s){mc(s)}function rb(s){console.error(s)}function sb(s){mc(s)}function Pc(s,o){try{var f=s.onUncaughtError;f(o.value,{componentStack:o.stack})}catch(g){setTimeout(function(){throw g})}}function ib(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 uf(s,o,f){return f=Ps(f),f.tag=3,f.payload={element:null},f.callback=function(){Pc(s,o)},f}function ab(s){return s=Ps(s),s.tag=3,s}function ob(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(){ib(o,f,g)}}var F=f.stateNode;F!==null&&typeof F.componentDidCatch=="function"&&(s.callback=function(){ib(o,f,g),typeof k!="function"&&(Vs===null?Vs=new Set([this]):Vs.add(this));var Y=g.stack;this.componentDidCatch(g.value,{componentStack:Y!==null?Y:""})})}function Dj(s,o,f,g,k){if(f.flags|=32768,g!==null&&typeof g=="object"&&typeof g.then=="function"){if(o=f.alternate,o!==null&&va(o,f,k,!0),f=nr.current,f!==null){switch(f.tag){case 31:case 13:return xr===null?Yc():f.alternate===null&&Jt===0&&(Jt=3),f.flags&=-257,f.flags|=65536,f.lanes=k,g===Cc?f.flags|=16384:(o=f.updateQueue,o===null?f.updateQueue=new Set([g]):o.add(g),If(s,g,k)),!1;case 22:return f.flags|=65536,g===Cc?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)),If(s,g,k)),!1}throw Error(r(435,f.tag))}return If(s,g,k),Yc(),!1}if(kt)return o=nr.current,o!==null?((o.flags&65536)===0&&(o.flags|=256),o.flags|=65536,o.lanes=k,g!==Nh&&(s=Error(r(422),{cause:g}),Ao(fr(s,f)))):(g!==Nh&&(o=Error(r(423),{cause:g}),Ao(fr(o,f))),s=s.current.alternate,s.flags|=65536,k&=-k,s.lanes|=k,g=fr(g,f),k=uf(s.stateNode,g,k),$h(s,k),Jt!==4&&(Jt=2)),!1;var A=Error(r(520),{cause:g});if(A=fr(A,f),Yo===null?Yo=[A]:Yo.push(A),Jt!==4&&(Jt=2),o===null)return!0;g=fr(g,f),f=o;do{switch(f.tag){case 3:return f.flags|=65536,s=k&-k,f.lanes|=s,s=uf(f.stateNode,g,s),$h(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"&&(Vs===null||!Vs.has(A))))return f.flags|=65536,k&=-k,f.lanes|=k,k=ab(k),ob(k,s,f,g),$h(f,k),!1}f=f.return}while(f!==null);return!1}var df=Error(r(461)),on=!1;function jn(s,o,f,g){o.child=s===null?dy(o,null,f,g):Ai(o,s.child,f,g)}function lb(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 ji(o),g=Gh(s,o,f,F,A,k),Y=Wh(),s!==null&&!on?(qh(s,o,k),os(s,o,k)):(kt&&Y&&jh(o),o.flags|=1,jn(s,o,g,k),o.child)}function cb(s,o,f,g,k){if(s===null){var A=f.type;return typeof A=="function"&&!wh(A)&&A.defaultProps===void 0&&f.compare===null?(o.tag=15,o.type=A,ub(s,o,A,g,k)):(s=yc(f.type,null,g,o,o.mode,k),s.ref=o.ref,s.return=o,o.child=s)}if(A=s.child,!bf(s,k)){var F=A.memoizedProps;if(f=f.compare,f=f!==null?f:Eo,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 ub(s,o,f,g,k){if(s!==null){var A=s.memoizedProps;if(Eo(A,g)&&s.ref===o.ref)if(on=!1,o.pendingProps=g=A,bf(s,k))(s.flags&131072)!==0&&(on=!0);else return o.lanes=s.lanes,os(s,o,k)}return hf(s,o,f,g,k)}function db(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 hb(s,o,A,f,g)}if((f&536870912)!==0)o.memoizedState={baseLanes:0,cachePool:null},s!==null&&Sc(o,A!==null?A.cachePool:null),A!==null?my(o,A):Hh(),py(o);else return g=o.lanes=536870912,hb(s,o,A!==null?A.baseLanes|f:f,f,g)}else A!==null?(Sc(o,A.cachePool),my(o,A),zs(),o.memoizedState=null):(s!==null&&Sc(o,null),Hh(),zs());return jn(s,o,k,f),o.child}function Uo(s,o){return s!==null&&s.tag===22||o.stateNode!==null||(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.sibling}function hb(s,o,f,g,k){var A=Ih();return A=A===null?null:{parent:sn._currentValue,pool:A},o.memoizedState={baseLanes:f,cachePool:A},s!==null&&Sc(o,null),Hh(),py(o),s!==null&&va(s,o,g,!0),o.childLanes=k,null}function Bc(s,o){return o=zc({mode:o.mode,children:o.children},s.mode),o.ref=s.ref,s.child=o,o.return=s,o}function fb(s,o,f){return Ai(o,s.child,null,f),s=Bc(o,o.pendingProps),s.flags|=2,rr(o),o.memoizedState=null,s}function Rj(s,o,f){var g=o.pendingProps,k=(o.flags&128)!==0;if(o.flags&=-129,s===null){if(kt){if(g.mode==="hidden")return s=Bc(o,g),o.lanes=536870912,Uo(null,s);if(Fh(o),(s=Wt)?(s=kv(s,gr),s=s!==null&&s.data==="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:Ds!==null?{id:Br,overflow:$r}:null,retryLane:536870912,hydrationErrors:null},f=Xx(s),f.return=o,o.child=f,Cn=o,Wt=null)):s=null,s===null)throw Os(o);return o.lanes=536870912,null}return Bc(o,g)}var A=s.memoizedState;if(A!==null){var F=A.dehydrated;if(Fh(o),k)if(o.flags&256)o.flags&=-257,o=fb(s,o,f);else if(o.memoizedState!==null)o.child=s.child,o.flags|=128,o=null;else throw Error(r(558));else if(on||va(s,o,f,!1),k=(f&s.childLanes)!==0,on||k){if(g=$t,g!==null&&(F=As(g,f),F!==0&&F!==A.retryLane))throw A.retryLane=F,Si(s,F),Kn(g,s,F),df;Yc(),o=fb(s,o,f)}else s=A.treeContext,Wt=yr(F.nextSibling),Cn=o,kt=!0,Rs=null,gr=!1,s!==null&&Zx(o,s),o=Bc(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 $c(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 hf(s,o,f,g,k){return ji(o),f=Gh(s,o,f,g,void 0,k),g=Wh(),s!==null&&!on?(qh(s,o,k),os(s,o,k)):(kt&&g&&jh(o),o.flags|=1,jn(s,o,f,k),o.child)}function mb(s,o,f,g,k,A){return ji(o),o.updateQueue=null,f=xy(o,g,f,k),gy(s),g=Wh(),s!==null&&!on?(qh(s,o,A),os(s,o,A)):(kt&&g&&jh(o),o.flags|=1,jn(s,o,f,A),o.child)}function pb(s,o,f,g,k){if(ji(o),o.stateNode===null){var A=ga,F=f.contextType;typeof F=="object"&&F!==null&&(A=kn(F)),A=new f(g,A),o.memoizedState=A.state!==null&&A.state!==void 0?A.state:null,A.updater=cf,o.stateNode=A,A._reactInternals=o,A=o.stateNode,A.props=g,A.state=o.memoizedState,A.refs={},Ph(o),F=f.contextType,A.context=typeof F=="object"&&F!==null?kn(F):ga,A.state=o.memoizedState,F=f.getDerivedStateFromProps,typeof F=="function"&&(lf(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&&cf.enqueueReplaceState(A,A.state,null),Po(o,g,A,k),Mo(),A.state=o.memoizedState),typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!0}else if(s===null){A=o.stateNode;var Y=o.memoizedProps,le=Di(f,Y);A.props=le;var ge=A.context,ke=f.contextType;F=ga,typeof ke=="object"&&ke!==null&&(F=kn(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)&&tb(o,A,g,F),Ms=!1;var xe=o.memoizedState;A.state=xe,Po(o,g,A,k),Mo(),ge=o.memoizedState,Y||xe!==ge||Ms?(typeof Ae=="function"&&(lf(o,f,Ae,g),ge=o.memoizedState),(le=Ms||eb(o,f,le,g,xe,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=le):(typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!1)}else{A=o.stateNode,Bh(s,o),F=o.memoizedProps,ke=Di(f,F),A.props=ke,Ae=o.pendingProps,xe=A.context,ge=f.contextType,le=ga,typeof ge=="object"&&ge!==null&&(le=kn(ge)),Y=f.getDerivedStateFromProps,(ge=typeof Y=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(F!==Ae||xe!==le)&&tb(o,A,g,le),Ms=!1,xe=o.memoizedState,A.state=xe,Po(o,g,A,k),Mo();var be=o.memoizedState;F!==Ae||xe!==be||Ms||s!==null&&s.dependencies!==null&&vc(s.dependencies)?(typeof Y=="function"&&(lf(o,f,Y,g),be=o.memoizedState),(ke=Ms||eb(o,f,ke,g,xe,be,le)||s!==null&&s.dependencies!==null&&vc(s.dependencies))?(ge||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(g,be,le),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(g,be,le)),typeof A.componentDidUpdate=="function"&&(o.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(o.flags|=1024)):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=1024),o.memoizedProps=g,o.memoizedState=be),A.props=g,A.state=be,A.context=le,g=ke):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=1024),g=!1)}return A=g,$c(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=Ai(o,s.child,null,k),o.child=Ai(o,null,f,k)):jn(s,o,f,k),o.memoizedState=A.state,s=o.child):s=os(s,o,k),s}function gb(s,o,f,g){return Ci(),o.flags|=256,jn(s,o,f,g),o.child}var ff={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function mf(s){return{baseLanes:s,cachePool:iy()}}function pf(s,o,f){return s=s!==null?s.childLanes&~f:0,o&&(s|=ir),s}function xb(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(kt){if(k?$s(o):zs(),(s=Wt)?(s=kv(s,gr),s=s!==null&&s.data!=="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:Ds!==null?{id:Br,overflow:$r}:null,retryLane:536870912,hydrationErrors:null},f=Xx(s),f.return=o,o.child=f,Cn=o,Wt=null)):s=null,s===null)throw Os(o);return Qf(s)?o.lanes=32:o.lanes=536870912,null}var Y=g.children;return g=g.fallback,k?(zs(),k=o.mode,Y=zc({mode:"hidden",children:Y},k),g=wi(g,k,f,null),Y.return=o,g.return=o,Y.sibling=g,o.child=Y,g=o.child,g.memoizedState=mf(f),g.childLanes=pf(s,F,f),o.memoizedState=ff,Uo(null,g)):($s(o),gf(o,Y))}var le=s.memoizedState;if(le!==null&&(Y=le.dehydrated,Y!==null)){if(A)o.flags&256?($s(o),o.flags&=-257,o=xf(s,o,f)):o.memoizedState!==null?(zs(),o.child=s.child,o.flags|=128,o=null):(zs(),Y=g.fallback,k=o.mode,g=zc({mode:"visible",children:g.children},k),Y=wi(Y,k,f,null),Y.flags|=2,g.return=o,Y.return=o,g.sibling=Y,o.child=g,Ai(o,s.child,null,f),g=o.child,g.memoizedState=mf(f),g.childLanes=pf(s,F,f),o.memoizedState=ff,o=Uo(null,g));else if($s(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,Ao({value:g,source:null,stack:null}),o=xf(s,o,f)}else if(on||va(s,o,f,!1),F=(f&s.childLanes)!==0,on||F){if(F=$t,F!==null&&(g=As(F,f),g!==0&&g!==le.retryLane))throw le.retryLane=g,Si(s,g),Kn(F,s,g),df;Xf(Y)||Yc(),o=xf(s,o,f)}else Xf(Y)?(o.flags|=192,o.child=s.child,o=null):(s=le.treeContext,Wt=yr(Y.nextSibling),Cn=o,kt=!0,Rs=null,gr=!1,s!==null&&Zx(o,s),o=gf(o,g.children),o.flags|=4096);return o}return k?(zs(),Y=g.fallback,k=o.mode,le=s.child,ge=le.sibling,g=ts(le,{mode:"hidden",children:g.children}),g.subtreeFlags=le.subtreeFlags&65011712,ge!==null?Y=ts(ge,Y):(Y=wi(Y,k,f,null),Y.flags|=2),Y.return=o,g.return=o,g.sibling=Y,o.child=g,Uo(null,g),g=o.child,Y=s.child.memoizedState,Y===null?Y=mf(f):(k=Y.cachePool,k!==null?(le=sn._currentValue,k=k.parent!==le?{parent:le,pool:le}:k):k=iy(),Y={baseLanes:Y.baseLanes|f,cachePool:k}),g.memoizedState=Y,g.childLanes=pf(s,F,f),o.memoizedState=ff,Uo(s.child,g)):($s(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 gf(s,o){return o=zc({mode:"visible",children:o},s.mode),o.return=s,s.child=o}function zc(s,o){return s=tr(22,s,null,o),s.lanes=0,s}function xf(s,o,f){return Ai(o,s.child,null,f),s=gf(o,o.pendingProps.children),s.flags|=2,o.memoizedState=null,s}function yb(s,o,f){s.lanes|=o;var g=s.alternate;g!==null&&(g.lanes|=o),Lh(s.return,o,f)}function yf(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 bb(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),jn(s,o,g,f),g=kt?To:0,!Y&&s!==null&&(s.flags&128)!==0)e:for(s=o.child;s!==null;){if(s.tag===13)s.memoizedState!==null&&yb(s,f,o);else if(s.tag===19)yb(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&&Nc(s)===null&&(k=f),f=f.sibling;f=k,f===null?(k=o.child,o.child=null):(k=f.sibling,f.sibling=null),yf(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&&Nc(s)===null){o.child=k;break}s=k.sibling,k.sibling=f,f=k,k=s}yf(o,!0,f,null,A,g);break;case"together":yf(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),Fs|=o.lanes,(f&o.childLanes)===0)if(s!==null){if(va(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 bf(s,o){return(s.lanes&o)!==0?!0:(s=s.dependencies,!!(s!==null&&vc(s)))}function Oj(s,o,f){switch(o.tag){case 3:P(o,o.stateNode.containerInfo),Is(o,sn,s.memoizedState.cache),Ci();break;case 27:case 5:ie(o);break;case 4:P(o,o.stateNode.containerInfo);break;case 10:Is(o,o.type,o.memoizedProps.value);break;case 31:if(o.memoizedState!==null)return o.flags|=128,Fh(o),null;break;case 13:var g=o.memoizedState;if(g!==null)return g.dehydrated!==null?($s(o),o.flags|=128,null):(f&o.child.childLanes)!==0?xb(s,o,f):($s(o),s=os(s,o,f),s!==null?s.sibling:null);$s(o);break;case 19:var k=(s.flags&128)!==0;if(g=(f&o.childLanes)!==0,g||(va(s,o,f,!1),g=(f&o.childLanes)!==0),k){if(g)return bb(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,db(s,o,f,o.pendingProps);case 24:Is(o,sn,s.memoizedState.cache)}return os(s,o,f)}function vb(s,o,f){if(s!==null)if(s.memoizedProps!==o.pendingProps)on=!0;else{if(!bf(s,f)&&(o.flags&128)===0)return on=!1,Oj(s,o,f);on=(s.flags&131072)!==0}else on=!1,kt&&(o.flags&1048576)!==0&&Jx(o,To,o.index);switch(o.lanes=0,o.tag){case 16:e:{var g=o.pendingProps;if(s=Ni(o.elementType),o.type=s,typeof s=="function")wh(s)?(g=Di(s,g),o.tag=1,o=pb(null,o,s,g,f)):(o.tag=0,o=hf(null,o,s,g,f));else{if(s!=null){var k=s.$$typeof;if(k===j){o.tag=11,o=lb(null,o,s,g,f);break e}else if(k===D){o.tag=14,o=cb(null,o,s,g,f);break e}}throw o=H(s)||s,Error(r(306,o,""))}}return o;case 0:return hf(s,o,o.type,o.pendingProps,f);case 1:return g=o.type,k=Di(g,o.pendingProps),pb(s,o,g,k,f);case 3:e:{if(P(o,o.stateNode.containerInfo),s===null)throw Error(r(387));g=o.pendingProps;var A=o.memoizedState;k=A.element,Bh(s,o),Po(o,g,null,f);var F=o.memoizedState;if(g=F.cache,Is(o,sn,g),g!==A.cache&&Dh(o,[sn],f,!0),Mo(),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=gb(s,o,g,f);break e}else if(g!==k){k=fr(Error(r(424)),o),Ao(k),o=gb(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(Wt=yr(s.firstChild),Cn=o,kt=!0,Rs=null,gr=!0,f=dy(o,null,g,f),o.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling}else{if(Ci(),g===k){o=os(s,o,f);break e}jn(s,o,g,f)}o=o.child}return o;case 26:return $c(s,o),s===null?(f=Lv(o.type,null,o.pendingProps,null))?o.memoizedState=f:kt||(f=o.type,s=o.pendingProps,g=nu(Q.current).createElement(f),g[Qe]=o,g[at]=s,En(g,f,s),vn(g),o.stateNode=g):o.memoizedState=Lv(o.type,s.memoizedProps,o.pendingProps,s.memoizedState),null;case 27:return ie(o),s===null&&kt&&(g=o.stateNode=Nv(o.type,o.pendingProps,Q.current),Cn=o,gr=!0,k=Wt,Ks(o.type)?(Jf=k,Wt=yr(g.firstChild)):Wt=k),jn(s,o,o.pendingProps.children,f),$c(s,o),s===null&&(o.flags|=4194304),o.child;case 5:return s===null&&kt&&((k=g=Wt)&&(g=uE(g,o.type,o.pendingProps,gr),g!==null?(o.stateNode=g,Cn=o,Wt=yr(g.firstChild),gr=!1,k=!0):k=!1),k||Os(o)),ie(o),k=o.type,A=o.pendingProps,F=s!==null?s.memoizedProps:null,g=A.children,qf(k,A)?g=null:F!==null&&qf(k,F)&&(o.flags|=32),o.memoizedState!==null&&(k=Gh(s,o,kj,null,null,f),rl._currentValue=k),$c(s,o),jn(s,o,g,f),o.child;case 6:return s===null&&kt&&((s=f=Wt)&&(f=dE(f,o.pendingProps,gr),f!==null?(o.stateNode=f,Cn=o,Wt=null,s=!0):s=!1),s||Os(o)),null;case 13:return xb(s,o,f);case 4:return P(o,o.stateNode.containerInfo),g=o.pendingProps,s===null?o.child=Ai(o,null,g,f):jn(s,o,g,f),o.child;case 11:return lb(s,o,o.type,o.pendingProps,f);case 7:return jn(s,o,o.pendingProps,f),o.child;case 8:return jn(s,o,o.pendingProps.children,f),o.child;case 12:return jn(s,o,o.pendingProps.children,f),o.child;case 10:return g=o.pendingProps,Is(o,o.type,g.value),jn(s,o,g.children,f),o.child;case 9:return k=o.type._context,g=o.pendingProps.children,ji(o),k=kn(k),g=g(k),o.flags|=1,jn(s,o,g,f),o.child;case 14:return cb(s,o,o.type,o.pendingProps,f);case 15:return ub(s,o,o.type,o.pendingProps,f);case 19:return bb(s,o,f);case 31:return Rj(s,o,f);case 22:return db(s,o,f,o.pendingProps);case 24:return ji(o),g=kn(sn),s===null?(k=Ih(),k===null&&(k=$t,A=Rh(),k.pooledCache=A,A.refCount++,A!==null&&(k.pooledCacheLanes|=f),k=A),o.memoizedState={parent:g,cache:k},Ph(o),Is(o,sn,k)):((s.lanes&f)!==0&&(Bh(s,o),Po(o,null,null,f),Mo()),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),Is(o,sn,g)):(g=A.cache,Is(o,sn,g),g!==k.cache&&Dh(o,[sn],f,!0))),jn(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 vf(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(qb())s.flags|=8192;else throw Ti=Cc,Mh}else s.flags&=-16777217}function _b(s,o){if(o.type!=="stylesheet"||(o.state.loading&4)!==0)s.flags&=-16777217;else if(s.flags|=16777216,!Mv(o))if(qb())s.flags|=8192;else throw Ti=Cc,Mh}function Hc(s,o){o!==null&&(s.flags|=4),s.flags&16384&&(o=s.tag!==22?bn():536870912,s.lanes|=o,Da|=o)}function Fo(s,o){if(!kt)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 qt(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 Ij(s,o,f){var g=o.pendingProps;switch(Eh(o),o.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return qt(o),null;case 1:return qt(o),null;case 3:return f=o.stateNode,g=null,s!==null&&(g=s.memoizedState.cache),o.memoizedState.cache!==g&&(o.flags|=2048),ss(sn),J(),f.pendingContext&&(f.context=f.pendingContext,f.pendingContext=null),(s===null||s.child===null)&&(ba(o)?ls(o):s===null||s.memoizedState.isDehydrated&&(o.flags&256)===0||(o.flags|=1024,Th())),qt(o),null;case 26:var k=o.type,A=o.memoizedState;return s===null?(ls(o),A!==null?(qt(o),_b(o,A)):(qt(o),vf(o,k,null,g,f))):A?A!==s.memoizedState?(ls(o),qt(o),_b(o,A)):(qt(o),o.flags&=-16777217):(s=s.memoizedProps,s!==g&&ls(o),qt(o),vf(o,k,s,g,f)),null;case 27:if(he(o),f=Q.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 qt(o),null}s=ne.current,ba(o)?ey(o):(s=Nv(k,g,f),o.stateNode=s,ls(o))}return qt(o),null;case 5:if(he(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 qt(o),null}if(A=ne.current,ba(o))ey(o);else{var F=nu(Q.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[Qe]=o,A[at]=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(En(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 qt(o),vf(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=Q.current,ba(o)){if(s=o.stateNode,f=o.memoizedProps,g=null,k=Cn,k!==null)switch(k.tag){case 27:case 5:g=k.memoizedProps}s[Qe]=o,s=!!(s.nodeValue===f||g!==null&&g.suppressHydrationWarning===!0||xv(s.nodeValue,f)),s||Os(o,!0)}else s=nu(s).createTextNode(g),s[Qe]=o,o.stateNode=s}return qt(o),null;case 31:if(f=o.memoizedState,s===null||s.memoizedState!==null){if(g=ba(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[Qe]=o}else Ci(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;qt(o),s=!1}else f=Th(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=f),s=!0;if(!s)return o.flags&256?(rr(o),o):(rr(o),null);if((o.flags&128)!==0)throw Error(r(558))}return qt(o),null;case 13:if(g=o.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(k=ba(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[Qe]=o}else Ci(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;qt(o),k=!1}else k=Th(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=k),k=!0;if(!k)return o.flags&256?(rr(o),o):(rr(o),null)}return rr(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),Hc(o,o.updateQueue),qt(o),null);case 4:return J(),s===null&&Uf(o.stateNode.containerInfo),qt(o),null;case 10:return ss(o.type),qt(o),null;case 19:if(q(en),g=o.memoizedState,g===null)return qt(o),null;if(k=(o.flags&128)!==0,A=g.rendering,A===null)if(k)Fo(g,!1);else{if(Jt!==0||s!==null&&(s.flags&128)!==0)for(s=o.child;s!==null;){if(A=Nc(s),A!==null){for(o.flags|=128,Fo(g,!1),s=A.updateQueue,o.updateQueue=s,Hc(o,s),o.subtreeFlags=0,s=f,f=o.child;f!==null;)Yx(f,s),f=f.sibling;return z(en,en.current&1|2),kt&&ns(o,g.treeForkCount),o.child}s=s.sibling}g.tail!==null&&Ie()>Wc&&(o.flags|=128,k=!0,Fo(g,!1),o.lanes=4194304)}else{if(!k)if(s=Nc(A),s!==null){if(o.flags|=128,k=!0,s=s.updateQueue,o.updateQueue=s,Hc(o,s),Fo(g,!0),g.tail===null&&g.tailMode==="hidden"&&!A.alternate&&!kt)return qt(o),null}else 2*Ie()-g.renderingStartTime>Wc&&f!==536870912&&(o.flags|=128,k=!0,Fo(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=Ie(),s.sibling=null,f=en.current,z(en,k?f&1|2:f&1),kt&&ns(o,g.treeForkCount),s):(qt(o),null);case 22:case 23:return rr(o),Uh(),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&&(qt(o),o.subtreeFlags&6&&(o.flags|=8192)):qt(o),f=o.updateQueue,f!==null&&Hc(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(Ei),null;case 24:return f=null,s!==null&&(f=s.memoizedState.cache),o.memoizedState.cache!==f&&(o.flags|=2048),ss(sn),qt(o),null;case 25:return null;case 30:return null}throw Error(r(156,o.tag))}function Mj(s,o){switch(Eh(o),o.tag){case 1:return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 3:return ss(sn),J(),s=o.flags,(s&65536)!==0&&(s&128)===0?(o.flags=s&-65537|128,o):null;case 26:case 27:case 5:return he(o),null;case 31:if(o.memoizedState!==null){if(rr(o),o.alternate===null)throw Error(r(340));Ci()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 13:if(rr(o),s=o.memoizedState,s!==null&&s.dehydrated!==null){if(o.alternate===null)throw Error(r(340));Ci()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 19:return q(en),null;case 4:return J(),null;case 10:return ss(o.type),null;case 22:case 23:return rr(o),Uh(),s!==null&&q(Ei),s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 24:return ss(sn),null;case 25:return null;default:return null}}function Sb(s,o){switch(Eh(o),o.tag){case 3:ss(sn),J();break;case 26:case 27:case 5:he(o);break;case 4:J();break;case 31:o.memoizedState!==null&&rr(o);break;case 13:rr(o);break;case 19:q(en);break;case 10:ss(o.type);break;case 22:case 23:rr(o),Uh(),s!==null&&q(Ei);break;case 24:ss(sn)}}function Vo(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){Rt(o,o.return,Y)}}function Hs(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 le=f,ge=Y;try{ge()}catch(ke){Rt(k,le,ke)}}}g=g.next}while(g!==A)}}catch(ke){Rt(o,o.return,ke)}}function wb(s){var o=s.updateQueue;if(o!==null){var f=s.stateNode;try{fy(o,f)}catch(g){Rt(s,s.return,g)}}}function Cb(s,o,f){f.props=Di(s.type,s.memoizedProps),f.state=s.memoizedState;try{f.componentWillUnmount()}catch(g){Rt(s,o,g)}}function Go(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){Rt(s,o,k)}}function zr(s,o){var f=s.ref,g=s.refCleanup;if(f!==null)if(typeof g=="function")try{g()}catch(k){Rt(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){Rt(s,o,k)}else f.current=null}function kb(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){Rt(s,s.return,k)}}function _f(s,o,f){try{var g=s.stateNode;sE(g,s.type,f,o),g[at]=o}catch(k){Rt(s,s.return,k)}}function jb(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&Ks(s.type)||s.tag===4}function Sf(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||jb(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&&Ks(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 wf(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&&Ks(s.type)&&(f=s.stateNode,o=null),s=s.child,s!==null))for(wf(s,o,f),s=s.sibling;s!==null;)wf(s,o,f),s=s.sibling}function Uc(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&&Ks(s.type)&&(f=s.stateNode),s=s.child,s!==null))for(Uc(s,o,f),s=s.sibling;s!==null;)Uc(s,o,f),s=s.sibling}function Eb(s){var o=s.stateNode,f=s.memoizedProps;try{for(var g=s.type,k=o.attributes;k.length;)o.removeAttributeNode(k[0]);En(o,g,f),o[Qe]=s,o[at]=f}catch(A){Rt(s,s.return,A)}}var cs=!1,ln=!1,Cf=!1,Nb=typeof WeakSet=="function"?WeakSet:Set,_n=null;function Pj(s,o){if(s=s.containerInfo,Gf=cu,s=zx(s),gh(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,le=-1,ge=0,ke=0,Ae=s,xe=null;t:for(;;){for(var be;Ae!==f||k!==0&&Ae.nodeType!==3||(Y=F+k),Ae!==A||g!==0&&Ae.nodeType!==3||(le=F+g),Ae.nodeType===3&&(F+=Ae.nodeValue.length),(be=Ae.firstChild)!==null;)xe=Ae,Ae=be;for(;;){if(Ae===s)break t;if(xe===f&&++ge===k&&(Y=F),xe===A&&++ke===g&&(le=F),(be=Ae.nextSibling)!==null)break;Ae=xe,xe=Ae.parentNode}Ae=be}f=Y===-1||le===-1?null:{start:Y,end:le}}else f=null}f=f||{start:0,end:0}}else f=null;for(Wf={focusedElem:s,selectionRange:f},cu=!1,_n=o;_n!==null;)if(o=_n,s=o.child,(o.subtreeFlags&1028)!==0&&s!==null)s.return=o,_n=s;else for(;_n!==null;){switch(o=_n,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 Ke=Di(f.type,k);s=g.getSnapshotBeforeUpdate(Ke,A),g.__reactInternalSnapshotBeforeUpdate=s}catch(it){Rt(f,f.return,it)}}break;case 3:if((s&1024)!==0){if(s=o.stateNode.containerInfo,f=s.nodeType,f===9)Yf(s);else if(f===1)switch(s.nodeName){case"HEAD":case"HTML":case"BODY":Yf(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,_n=s;break}_n=o.return}}function Tb(s,o,f){var g=f.flags;switch(f.tag){case 0:case 11:case 15:ds(s,f),g&4&&Vo(5,f);break;case 1:if(ds(s,f),g&4)if(s=f.stateNode,o===null)try{s.componentDidMount()}catch(F){Rt(f,f.return,F)}else{var k=Di(f.type,o.memoizedProps);o=o.memoizedState;try{s.componentDidUpdate(k,o,s.__reactInternalSnapshotBeforeUpdate)}catch(F){Rt(f,f.return,F)}}g&64&&wb(f),g&512&&Go(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{fy(s,o)}catch(F){Rt(f,f.return,F)}}break;case 27:o===null&&g&4&&Eb(f);case 26:case 5:ds(s,f),o===null&&g&4&&kb(f),g&512&&Go(f,f.return);break;case 12:ds(s,f);break;case 31:ds(s,f),g&4&&Db(s,f);break;case 13:ds(s,f),g&4&&Rb(s,f),g&64&&(s=f.memoizedState,s!==null&&(s=s.dehydrated,s!==null&&(f=Wj.bind(null,f),hE(s,f))));break;case 22:if(g=f.memoizedState!==null||cs,!g){o=o!==null&&o.memoizedState!==null||ln,k=cs;var A=ln;cs=g,(ln=o)&&!A?hs(s,f,(f.subtreeFlags&8772)!==0):ds(s,f),cs=k,ln=A}break;case 30:break;default:ds(s,f)}}function Ab(s){var o=s.alternate;o!==null&&(s.alternate=null,Ab(o)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(o=s.stateNode,o!==null&&Zd(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 Kt=null,Vn=!1;function us(s,o,f){for(f=f.child;f!==null;)Lb(s,o,f),f=f.sibling}function Lb(s,o,f){if(Je&&typeof Je.onCommitFiberUnmount=="function")try{Je.onCommitFiberUnmount(ct,f)}catch{}switch(f.tag){case 26:ln||zr(f,o),us(s,o,f),f.memoizedState?f.memoizedState.count--:f.stateNode&&(f=f.stateNode,f.parentNode.removeChild(f));break;case 27:ln||zr(f,o);var g=Kt,k=Vn;Ks(f.type)&&(Kt=f.stateNode,Vn=!1),us(s,o,f),el(f.stateNode),Kt=g,Vn=k;break;case 5:ln||zr(f,o);case 6:if(g=Kt,k=Vn,Kt=null,us(s,o,f),Kt=g,Vn=k,Kt!==null)if(Vn)try{(Kt.nodeType===9?Kt.body:Kt.nodeName==="HTML"?Kt.ownerDocument.body:Kt).removeChild(f.stateNode)}catch(A){Rt(f,o,A)}else try{Kt.removeChild(f.stateNode)}catch(A){Rt(f,o,A)}break;case 18:Kt!==null&&(Vn?(s=Kt,wv(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,f.stateNode),za(s)):wv(Kt,f.stateNode));break;case 4:g=Kt,k=Vn,Kt=f.stateNode.containerInfo,Vn=!0,us(s,o,f),Kt=g,Vn=k;break;case 0:case 11:case 14:case 15:Hs(2,f,o),ln||Hs(4,f,o),us(s,o,f);break;case 1:ln||(zr(f,o),g=f.stateNode,typeof g.componentWillUnmount=="function"&&Cb(f,o,g)),us(s,o,f);break;case 21:us(s,o,f);break;case 22:ln=(g=ln)||f.memoizedState!==null,us(s,o,f),ln=g;break;default:us(s,o,f)}}function Db(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null))){s=s.dehydrated;try{za(s)}catch(f){Rt(o,o.return,f)}}}function Rb(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null&&(s=s.dehydrated,s!==null))))try{za(s)}catch(f){Rt(o,o.return,f)}}function Bj(s){switch(s.tag){case 31:case 13:case 19:var o=s.stateNode;return o===null&&(o=s.stateNode=new Nb),o;case 22:return s=s.stateNode,o=s._retryCache,o===null&&(o=s._retryCache=new Nb),o;default:throw Error(r(435,s.tag))}}function Fc(s,o){var f=Bj(s);o.forEach(function(g){if(!f.has(g)){f.add(g);var k=qj.bind(null,s,g);g.then(k,k)}})}function Gn(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(Ks(Y.type)){Kt=Y.stateNode,Vn=!1;break e}break;case 5:Kt=Y.stateNode,Vn=!1;break e;case 3:case 4:Kt=Y.stateNode.containerInfo,Vn=!0;break e}Y=Y.return}if(Kt===null)throw Error(r(160));Lb(A,F,k),Kt=null,Vn=!1,A=k.alternate,A!==null&&(A.return=null),k.return=null}if(o.subtreeFlags&13886)for(o=o.child;o!==null;)Ob(o,s),o=o.sibling}var Er=null;function Ob(s,o){var f=s.alternate,g=s.flags;switch(s.tag){case 0:case 11:case 14:case 15:Gn(o,s),Wn(s),g&4&&(Hs(3,s,s.return),Vo(3,s),Hs(5,s,s.return));break;case 1:Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(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=Er;if(Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(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[yo]||A[Qe]||A.namespaceURI==="http://www.w3.org/2000/svg"||A.hasAttribute("itemprop"))&&(A=k.createElement(g),k.head.insertBefore(A,k.querySelector("head > title"))),En(A,g,f),A[Qe]=s,vn(A),g=A;break e;case"link":var F=Ov("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),En(A,g,f),k.head.appendChild(A);break;case"meta":if(F=Ov("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),En(A,g,f),k.head.appendChild(A);break;default:throw Error(r(468,g))}A[Qe]=s,vn(A),g=A}s.stateNode=g}else Iv(k,s.type,s.stateNode);else s.stateNode=Rv(k,g,s.memoizedProps);else A!==g?(A===null?f.stateNode!==null&&(f=f.stateNode,f.parentNode.removeChild(f)):A.count--,g===null?Iv(k,s.type,s.stateNode):Rv(k,g,s.memoizedProps)):g===null&&s.stateNode!==null&&_f(s,s.memoizedProps,f.memoizedProps)}break;case 27:Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(f,f.return)),f!==null&&g&4&&_f(s,s.memoizedProps,f.memoizedProps);break;case 5:if(Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(f,f.return)),s.flags&32){k=s.stateNode;try{ca(k,"")}catch(Ke){Rt(s,s.return,Ke)}}g&4&&s.stateNode!=null&&(k=s.memoizedProps,_f(s,k,f!==null?f.memoizedProps:k)),g&1024&&(Cf=!0);break;case 6:if(Gn(o,s),Wn(s),g&4){if(s.stateNode===null)throw Error(r(162));g=s.memoizedProps,f=s.stateNode;try{f.nodeValue=g}catch(Ke){Rt(s,s.return,Ke)}}break;case 3:if(iu=null,k=Er,Er=ru(o.containerInfo),Gn(o,s),Er=k,Wn(s),g&4&&f!==null&&f.memoizedState.isDehydrated)try{za(o.containerInfo)}catch(Ke){Rt(s,s.return,Ke)}Cf&&(Cf=!1,Ib(s));break;case 4:g=Er,Er=ru(s.stateNode.containerInfo),Gn(o,s),Wn(s),Er=g;break;case 12:Gn(o,s),Wn(s);break;case 31:Gn(o,s),Wn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,Fc(s,g)));break;case 13:Gn(o,s),Wn(s),s.child.flags&8192&&s.memoizedState!==null!=(f!==null&&f.memoizedState!==null)&&(Gc=Ie()),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,Fc(s,g)));break;case 22:k=s.memoizedState!==null;var le=f!==null&&f.memoizedState!==null,ge=cs,ke=ln;if(cs=ge||k,ln=ke||le,Gn(o,s),ln=ke,cs=ge,Wn(s),g&8192)e:for(o=s.stateNode,o._visibility=k?o._visibility&-2:o._visibility|1,k&&(f===null||le||cs||ln||Ri(s)),f=null,o=s;;){if(o.tag===5||o.tag===26){if(f===null){le=f=o;try{if(A=le.stateNode,k)F=A.style,typeof F.setProperty=="function"?F.setProperty("display","none","important"):F.display="none";else{Y=le.stateNode;var Ae=le.memoizedProps.style,xe=Ae!=null&&Ae.hasOwnProperty("display")?Ae.display:null;Y.style.display=xe==null||typeof xe=="boolean"?"":(""+xe).trim()}}catch(Ke){Rt(le,le.return,Ke)}}}else if(o.tag===6){if(f===null){le=o;try{le.stateNode.nodeValue=k?"":le.memoizedProps}catch(Ke){Rt(le,le.return,Ke)}}}else if(o.tag===18){if(f===null){le=o;try{var be=le.stateNode;k?Cv(be,!0):Cv(le.stateNode,!1)}catch(Ke){Rt(le,le.return,Ke)}}}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,Fc(s,f))));break;case 19:Gn(o,s),Wn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,Fc(s,g)));break;case 30:break;case 21:break;default:Gn(o,s),Wn(s)}}function Wn(s){var o=s.flags;if(o&2){try{for(var f,g=s.return;g!==null;){if(jb(g)){f=g;break}g=g.return}if(f==null)throw Error(r(160));switch(f.tag){case 27:var k=f.stateNode,A=Sf(s);Uc(s,A,k);break;case 5:var F=f.stateNode;f.flags&32&&(ca(F,""),f.flags&=-33);var Y=Sf(s);Uc(s,Y,F);break;case 3:case 4:var le=f.stateNode.containerInfo,ge=Sf(s);wf(s,ge,le);break;default:throw Error(r(161))}}catch(ke){Rt(s,s.return,ke)}s.flags&=-3}o&4096&&(s.flags&=-4097)}function Ib(s){if(s.subtreeFlags&1024)for(s=s.child;s!==null;){var o=s;Ib(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;)Tb(s,o.alternate,o),o=o.sibling}function Ri(s){for(s=s.child;s!==null;){var o=s;switch(o.tag){case 0:case 11:case 14:case 15:Hs(4,o,o.return),Ri(o);break;case 1:zr(o,o.return);var f=o.stateNode;typeof f.componentWillUnmount=="function"&&Cb(o,o.return,f),Ri(o);break;case 27:el(o.stateNode);case 26:case 5:zr(o,o.return),Ri(o);break;case 22:o.memoizedState===null&&Ri(o);break;case 30:Ri(o);break;default:Ri(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),Vo(4,A);break;case 1:if(hs(k,A,f),g=A,k=g.stateNode,typeof k.componentDidMount=="function")try{k.componentDidMount()}catch(ge){Rt(g,g.return,ge)}if(g=A,k=g.updateQueue,k!==null){var Y=g.stateNode;try{var le=k.shared.hiddenCallbacks;if(le!==null)for(k.shared.hiddenCallbacks=null,k=0;k<le.length;k++)hy(le[k],Y)}catch(ge){Rt(g,g.return,ge)}}f&&F&64&&wb(A),Go(A,A.return);break;case 27:Eb(A);case 26:case 5:hs(k,A,f),f&&g===null&&F&4&&kb(A),Go(A,A.return);break;case 12:hs(k,A,f);break;case 31:hs(k,A,f),f&&F&4&&Db(k,A);break;case 13:hs(k,A,f),f&&F&4&&Rb(k,A);break;case 22:A.memoizedState===null&&hs(k,A,f),Go(A,A.return);break;case 30:break;default:hs(k,A,f)}o=o.sibling}}function kf(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&&Lo(f))}function jf(s,o){s=null,o.alternate!==null&&(s=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==s&&(o.refCount++,s!=null&&Lo(s))}function Nr(s,o,f,g){if(o.subtreeFlags&10256)for(o=o.child;o!==null;)Mb(s,o,f,g),o=o.sibling}function Mb(s,o,f,g){var k=o.flags;switch(o.tag){case 0:case 11:case 15:Nr(s,o,f,g),k&2048&&Vo(9,o);break;case 1:Nr(s,o,f,g);break;case 3:Nr(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&&Lo(s)));break;case 12:if(k&2048){Nr(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(le){Rt(o,o.return,le)}}else Nr(s,o,f,g);break;case 31:Nr(s,o,f,g);break;case 13:Nr(s,o,f,g);break;case 23:break;case 22:A=o.stateNode,F=o.alternate,o.memoizedState!==null?A._visibility&2?Nr(s,o,f,g):Wo(s,o):A._visibility&2?Nr(s,o,f,g):(A._visibility|=2,Ta(s,o,f,g,(o.subtreeFlags&10256)!==0||!1)),k&2048&&kf(F,o);break;case 24:Nr(s,o,f,g),k&2048&&jf(o.alternate,o);break;default:Nr(s,o,f,g)}}function Ta(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,le=g,ge=F.flags;switch(F.tag){case 0:case 11:case 15:Ta(A,F,Y,le,k),Vo(8,F);break;case 23:break;case 22:var ke=F.stateNode;F.memoizedState!==null?ke._visibility&2?Ta(A,F,Y,le,k):Wo(A,F):(ke._visibility|=2,Ta(A,F,Y,le,k)),k&&ge&2048&&kf(F.alternate,F);break;case 24:Ta(A,F,Y,le,k),k&&ge&2048&&jf(F.alternate,F);break;default:Ta(A,F,Y,le,k)}o=o.sibling}}function Wo(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:Wo(f,g),k&2048&&kf(g.alternate,g);break;case 24:Wo(f,g),k&2048&&jf(g.alternate,g);break;default:Wo(f,g)}o=o.sibling}}var qo=8192;function Aa(s,o,f){if(s.subtreeFlags&qo)for(s=s.child;s!==null;)Pb(s,o,f),s=s.sibling}function Pb(s,o,f){switch(s.tag){case 26:Aa(s,o,f),s.flags&qo&&s.memoizedState!==null&&CE(f,Er,s.memoizedState,s.memoizedProps);break;case 5:Aa(s,o,f);break;case 3:case 4:var g=Er;Er=ru(s.stateNode.containerInfo),Aa(s,o,f),Er=g;break;case 22:s.memoizedState===null&&(g=s.alternate,g!==null&&g.memoizedState!==null?(g=qo,qo=16777216,Aa(s,o,f),qo=g):Aa(s,o,f));break;default:Aa(s,o,f)}}function Bb(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 Ko(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];_n=g,zb(g,s)}Bb(s)}if(s.subtreeFlags&10256)for(s=s.child;s!==null;)$b(s),s=s.sibling}function $b(s){switch(s.tag){case 0:case 11:case 15:Ko(s),s.flags&2048&&Hs(9,s,s.return);break;case 3:Ko(s);break;case 12:Ko(s);break;case 22:var o=s.stateNode;s.memoizedState!==null&&o._visibility&2&&(s.return===null||s.return.tag!==13)?(o._visibility&=-3,Vc(s)):Ko(s);break;default:Ko(s)}}function Vc(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];_n=g,zb(g,s)}Bb(s)}for(s=s.child;s!==null;){switch(o=s,o.tag){case 0:case 11:case 15:Hs(8,o,o.return),Vc(o);break;case 22:f=o.stateNode,f._visibility&2&&(f._visibility&=-3,Vc(o));break;default:Vc(o)}s=s.sibling}}function zb(s,o){for(;_n!==null;){var f=_n;switch(f.tag){case 0:case 11:case 15:Hs(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:Lo(f.memoizedState.cache)}if(g=f.child,g!==null)g.return=f,_n=g;else e:for(f=s;_n!==null;){g=_n;var k=g.sibling,A=g.return;if(Ab(g),g===f){_n=null;break e}if(k!==null){k.return=A,_n=k;break e}_n=A}}}var $j={getCacheForType:function(s){var o=kn(sn),f=o.data.get(s);return f===void 0&&(f=s(),o.data.set(s,f)),f},cacheSignal:function(){return kn(sn).controller.signal}},zj=typeof WeakMap=="function"?WeakMap:Map,Lt=0,$t=null,yt=null,wt=0,Dt=0,sr=null,Us=!1,La=!1,Ef=!1,fs=0,Jt=0,Fs=0,Oi=0,Nf=0,ir=0,Da=0,Yo=null,qn=null,Tf=!1,Gc=0,Hb=0,Wc=1/0,qc=null,Vs=null,pn=0,Gs=null,Ra=null,ms=0,Af=0,Lf=null,Ub=null,Xo=0,Df=null;function ar(){return(Lt&2)!==0&&wt!==0?wt&-wt:V.T!==null?Bf():Oe()}function Fb(){if(ir===0)if((wt&536870912)===0||kt){var s=ye;ye<<=1,(ye&3932160)===0&&(ye=262144),ir=s}else ir=536870912;return s=nr.current,s!==null&&(s.flags|=32),ir}function Kn(s,o,f){(s===$t&&(Dt===2||Dt===9)||s.cancelPendingCommit!==null)&&(Oa(s,0),Ws(s,wt,ir,!1)),Pr(s,f),((Lt&2)===0||s!==$t)&&(s===$t&&((Lt&2)===0&&(Oi|=f),Jt===4&&Ws(s,wt,ir,!1)),Hr(s))}function Vb(s,o,f){if((Lt&6)!==0)throw Error(r(327));var g=!f&&(o&127)===0&&(o&s.expiredLanes)===0||Pe(s,o),k=g?Fj(s,o):Of(s,o,!0),A=g;do{if(k===0){La&&!g&&Ws(s,o,0,!1);break}else{if(f=s.current.alternate,A&&!Hj(f)){k=Of(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=Yo;var le=Y.current.memoizedState.isDehydrated;if(le&&(Oa(Y,F).flags|=256),F=Of(Y,F,!1),F!==2){if(Ef&&!le){Y.errorRecoveryDisabledLanes|=A,Oi|=A,k=4;break e}A=qn,qn=k,A!==null&&(qn===null?qn=A:qn.push.apply(qn,A))}k=F}if(A=!1,k!==2)continue}}if(k===1){Oa(s,0),Ws(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:Ws(g,o,ir,!Us);break e;case 2:qn=null;break;case 3:case 5:break;default:throw Error(r(329))}if((o&62914560)===o&&(k=Gc+300-Ie(),10<k)){if(Ws(g,o,ir,!Us),fe(g,0,!0)!==0)break e;ms=o,g.timeoutHandle=_v(Gb.bind(null,g,f,qn,qc,Tf,o,ir,Oi,Da,Us,A,"Throttled",-0,0),k);break e}Gb(g,f,qn,qc,Tf,o,ir,Oi,Da,Us,A,null,-0,0)}}break}while(!0);Hr(s)}function Gb(s,o,f,g,k,A,F,Y,le,ge,ke,Ae,xe,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},Pb(o,A,Ae);var Ke=(A&62914560)===A?Gc-Ie():(A&4194048)===A?Hb-Ie():0;if(Ke=kE(Ae,Ke),Ke!==null){ms=A,s.cancelPendingCommit=Ke(Zb.bind(null,s,o,A,f,g,k,F,Y,le,ke,Ae,null,xe,be)),Ws(s,A,F,!ge);return}}Zb(s,o,A,f,g,k,F,Y,le)}function Hj(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(!er(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 Ws(s,o,f,g){o&=~Nf,o&=~Oi,s.suspendedLanes|=o,s.pingedLanes&=~o,g&&(s.warmLanes|=o),g=s.expirationTimes;for(var k=o;0<k;){var A=31-tt(k),F=1<<A;g[A]=-1,k&=~F}f!==0&&xi(s,f,o)}function Kc(){return(Lt&6)===0?(Qo(0),!1):!0}function Rf(){if(yt!==null){if(Dt===0)var s=yt.return;else s=yt,rs=ki=null,Kh(s),Ca=null,Ro=0,s=yt;for(;s!==null;)Sb(s.alternate,s),s=s.return;yt=null}}function Oa(s,o){var f=s.timeoutHandle;f!==-1&&(s.timeoutHandle=-1,oE(f)),f=s.cancelPendingCommit,f!==null&&(s.cancelPendingCommit=null,f()),ms=0,Rf(),$t=s,yt=f=ts(s.current,null),wt=o,Dt=0,sr=null,Us=!1,La=Pe(s,o),Ef=!1,Da=ir=Nf=Oi=Fs=Jt=0,qn=Yo=null,Tf=!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-tt(g),A=1<<k;o|=s[k],g&=~A}return fs=o,pc(),f}function Wb(s,o){ft=null,V.H=Ho,o===wa||o===wc?(o=ly(),Dt=3):o===Mh?(o=ly(),Dt=4):Dt=o===df?8:o!==null&&typeof o=="object"&&typeof o.then=="function"?6:1,sr=o,yt===null&&(Jt=1,Pc(s,fr(o,s.current)))}function qb(){var s=nr.current;return s===null?!0:(wt&4194048)===wt?xr===null:(wt&62914560)===wt||(wt&536870912)!==0?s===xr:!1}function Kb(){var s=V.H;return V.H=Ho,s===null?Ho:s}function Yb(){var s=V.A;return V.A=$j,s}function Yc(){Jt=4,Us||(wt&4194048)!==wt&&nr.current!==null||(La=!0),(Fs&134217727)===0&&(Oi&134217727)===0||$t===null||Ws($t,wt,ir,!1)}function Of(s,o,f){var g=Lt;Lt|=2;var k=Kb(),A=Yb();($t!==s||wt!==o)&&(qc=null,Oa(s,o)),o=!1;var F=Jt;e:do try{if(Dt!==0&&yt!==null){var Y=yt,le=sr;switch(Dt){case 8:Rf(),F=6;break e;case 3:case 2:case 9:case 6:nr.current===null&&(o=!0);var ge=Dt;if(Dt=0,sr=null,Ia(s,Y,le,ge),f&&La){F=0;break e}break;default:ge=Dt,Dt=0,sr=null,Ia(s,Y,le,ge)}}Uj(),F=Jt;break}catch(ke){Wb(s,ke)}while(!0);return o&&s.shellSuspendCounter++,rs=ki=null,Lt=g,V.H=k,V.A=A,yt===null&&($t=null,wt=0,pc()),F}function Uj(){for(;yt!==null;)Xb(yt)}function Fj(s,o){var f=Lt;Lt|=2;var g=Kb(),k=Yb();$t!==s||wt!==o?(qc=null,Wc=Ie()+500,Oa(s,o)):La=Pe(s,o);e:do try{if(Dt!==0&&yt!==null){o=yt;var A=sr;t:switch(Dt){case 1:Dt=0,sr=null,Ia(s,o,A,1);break;case 2:case 9:if(ay(A)){Dt=0,sr=null,Qb(o);break}o=function(){Dt!==2&&Dt!==9||$t!==s||(Dt=7),Hr(s)},A.then(o,o);break e;case 3:Dt=7;break e;case 4:Dt=5;break e;case 7:ay(A)?(Dt=0,sr=null,Qb(o)):(Dt=0,sr=null,Ia(s,o,A,7));break;case 5:var F=null;switch(yt.tag){case 26:F=yt.memoizedState;case 5:case 27:var Y=yt;if(F?Mv(F):Y.stateNode.complete){Dt=0,sr=null;var le=Y.sibling;if(le!==null)yt=le;else{var ge=Y.return;ge!==null?(yt=ge,Xc(ge)):yt=null}break t}}Dt=0,sr=null,Ia(s,o,A,5);break;case 6:Dt=0,sr=null,Ia(s,o,A,6);break;case 8:Rf(),Jt=6;break e;default:throw Error(r(462))}}Vj();break}catch(ke){Wb(s,ke)}while(!0);return rs=ki=null,V.H=g,V.A=k,Lt=f,yt!==null?0:($t=null,wt=0,pc(),Jt)}function Vj(){for(;yt!==null&&!lt();)Xb(yt)}function Xb(s){var o=vb(s.alternate,s,fs);s.memoizedProps=s.pendingProps,o===null?Xc(s):yt=o}function Qb(s){var o=s,f=o.alternate;switch(o.tag){case 15:case 0:o=mb(f,o,o.pendingProps,o.type,void 0,wt);break;case 11:o=mb(f,o,o.pendingProps,o.type.render,o.ref,wt);break;case 5:Kh(o);default:Sb(f,o),o=yt=Yx(o,fs),o=vb(f,o,fs)}s.memoizedProps=s.pendingProps,o===null?Xc(s):yt=o}function Ia(s,o,f,g){rs=ki=null,Kh(o),Ca=null,Ro=0;var k=o.return;try{if(Dj(s,k,o,f,wt)){Jt=1,Pc(s,fr(f,s.current)),yt=null;return}}catch(A){if(k!==null)throw yt=k,A;Jt=1,Pc(s,fr(f,s.current)),yt=null;return}o.flags&32768?(kt||g===1?s=!0:La||(wt&536870912)!==0?s=!1:(Us=s=!0,(g===2||g===9||g===3||g===6)&&(g=nr.current,g!==null&&g.tag===13&&(g.flags|=16384))),Jb(o,s)):Xc(o)}function Xc(s){var o=s;do{if((o.flags&32768)!==0){Jb(o,Us);return}s=o.return;var f=Ij(o.alternate,o,fs);if(f!==null){yt=f;return}if(o=o.sibling,o!==null){yt=o;return}yt=o=s}while(o!==null);Jt===0&&(Jt=5)}function Jb(s,o){do{var f=Mj(s.alternate,s);if(f!==null){f.flags&=32767,yt=f;return}if(f=s.return,f!==null&&(f.flags|=32768,f.subtreeFlags=0,f.deletions=null),!o&&(s=s.sibling,s!==null)){yt=s;return}yt=s=f}while(s!==null);Jt=6,yt=null}function Zb(s,o,f,g,k,A,F,Y,le){s.cancelPendingCommit=null;do Qc();while(pn!==0);if((Lt&6)!==0)throw Error(r(327));if(o!==null){if(o===s.current)throw Error(r(177));if(A=o.lanes|o.childLanes,A|=_h,Ns(s,f,A,F,Y,le),s===$t&&(yt=$t=null,wt=0),Ra=o,Gs=s,ms=f,Af=A,Lf=k,Ub=g,(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?(s.callbackNode=null,s.callbackPriority=0,Kj(se,function(){return sv(),null})):(s.callbackNode=null,s.callbackPriority=0),g=(o.flags&13878)!==0,(o.subtreeFlags&13878)!==0||g){g=V.T,V.T=null,k=Z.p,Z.p=2,F=Lt,Lt|=4;try{Pj(s,o,f)}finally{Lt=F,Z.p=k,V.T=g}}pn=1,ev(),tv(),nv()}}function ev(){if(pn===1){pn=0;var s=Gs,o=Ra,f=(o.flags&13878)!==0;if((o.subtreeFlags&13878)!==0||f){f=V.T,V.T=null;var g=Z.p;Z.p=2;var k=Lt;Lt|=4;try{Ob(o,s);var A=Wf,F=zx(s.containerInfo),Y=A.focusedElem,le=A.selectionRange;if(F!==Y&&Y&&Y.ownerDocument&&$x(Y.ownerDocument.documentElement,Y)){if(le!==null&&gh(Y)){var ge=le.start,ke=le.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,xe=Ae&&Ae.defaultView||window;if(xe.getSelection){var be=xe.getSelection(),Ke=Y.textContent.length,it=Math.min(le.start,Ke),Mt=le.end===void 0?it:Math.min(le.end,Ke);!be.extend&&it>Mt&&(F=Mt,Mt=it,it=F);var de=Bx(Y,it),ue=Bx(Y,Mt);if(de&&ue&&(be.rangeCount!==1||be.anchorNode!==de.node||be.anchorOffset!==de.offset||be.focusNode!==ue.node||be.focusOffset!==ue.offset)){var pe=Ae.createRange();pe.setStart(de.node,de.offset),be.removeAllRanges(),it>Mt?(be.addRange(pe),be.extend(ue.node,ue.offset)):(pe.setEnd(ue.node,ue.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 Ne=Ae[Y];Ne.element.scrollLeft=Ne.left,Ne.element.scrollTop=Ne.top}}cu=!!Gf,Wf=Gf=null}finally{Lt=k,Z.p=g,V.T=f}}s.current=o,pn=2}}function tv(){if(pn===2){pn=0;var s=Gs,o=Ra,f=(o.flags&8772)!==0;if((o.subtreeFlags&8772)!==0||f){f=V.T,V.T=null;var g=Z.p;Z.p=2;var k=Lt;Lt|=4;try{Tb(s,o.alternate,o)}finally{Lt=k,Z.p=g,V.T=f}}pn=3}}function nv(){if(pn===4||pn===3){pn=0,we();var s=Gs,o=Ra,f=ms,g=Ub;(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?pn=5:(pn=0,Ra=Gs=null,rv(s,s.pendingLanes));var k=s.pendingLanes;if(k===0&&(Vs=null),Ce(f),o=o.stateNode,Je&&typeof Je.onCommitFiberRoot=="function")try{Je.onCommitFiberRoot(ct,o,void 0,(o.current.flags&128)===128)}catch{}if(g!==null){o=V.T,k=Z.p,Z.p=2,V.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{V.T=o,Z.p=k}}(ms&3)!==0&&Qc(),Hr(s),k=s.pendingLanes,(f&261930)!==0&&(k&42)!==0?s===Df?Xo++:(Xo=0,Df=s):Xo=0,Qo(0)}}function rv(s,o){(s.pooledCacheLanes&=o)===0&&(o=s.pooledCache,o!=null&&(s.pooledCache=null,Lo(o)))}function Qc(){return ev(),tv(),nv(),sv()}function sv(){if(pn!==5)return!1;var s=Gs,o=Af;Af=0;var f=Ce(ms),g=V.T,k=Z.p;try{Z.p=32>f?32:f,V.T=null,f=Lf,Lf=null;var A=Gs,F=ms;if(pn=0,Ra=Gs=null,ms=0,(Lt&6)!==0)throw Error(r(331));var Y=Lt;if(Lt|=4,$b(A.current),Mb(A,A.current,F,f),Lt=Y,Qo(0,!1),Je&&typeof Je.onPostCommitFiberRoot=="function")try{Je.onPostCommitFiberRoot(ct,A)}catch{}return!0}finally{Z.p=k,V.T=g,rv(s,o)}}function iv(s,o,f){o=fr(f,o),o=uf(s.stateNode,o,2),s=Bs(s,o,2),s!==null&&(Pr(s,2),Hr(s))}function Rt(s,o,f){if(s.tag===3)iv(s,s,f);else for(;o!==null;){if(o.tag===3){iv(o,s,f);break}else if(o.tag===1){var g=o.stateNode;if(typeof o.type.getDerivedStateFromError=="function"||typeof g.componentDidCatch=="function"&&(Vs===null||!Vs.has(g))){s=fr(f,s),f=ab(2),g=Bs(o,f,2),g!==null&&(ob(f,g,o,s),Pr(g,2),Hr(g));break}}o=o.return}}function If(s,o,f){var g=s.pingCache;if(g===null){g=s.pingCache=new zj;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)||(Ef=!0,k.add(f),s=Gj.bind(null,s,o,f),o.then(s,s))}function Gj(s,o,f){var g=s.pingCache;g!==null&&g.delete(o),s.pingedLanes|=s.suspendedLanes&f,s.warmLanes&=~f,$t===s&&(wt&f)===f&&(Jt===4||Jt===3&&(wt&62914560)===wt&&300>Ie()-Gc?(Lt&2)===0&&Oa(s,0):Nf|=f,Da===wt&&(Da=0)),Hr(s)}function av(s,o){o===0&&(o=bn()),s=Si(s,o),s!==null&&(Pr(s,o),Hr(s))}function Wj(s){var o=s.memoizedState,f=0;o!==null&&(f=o.retryLane),av(s,f)}function qj(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),av(s,f)}function Kj(s,o){return je(s,o)}var Jc=null,Ma=null,Mf=!1,Zc=!1,Pf=!1,qs=0;function Hr(s){s!==Ma&&s.next===null&&(Ma===null?Jc=Ma=s:Ma=Ma.next=s),Zc=!0,Mf||(Mf=!0,Xj())}function Qo(s,o){if(!Pf&&Zc){Pf=!0;do for(var f=!1,g=Jc;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-tt(42|s)+1)-1,A&=k&~(F&~Y),A=A&201326741?A&201326741|1:A?A|2:0}A!==0&&(f=!0,uv(g,A))}else A=wt,A=fe(g,g===$t?A:0,g.cancelPendingCommit!==null||g.timeoutHandle!==-1),(A&3)===0||Pe(g,A)||(f=!0,uv(g,A));g=g.next}while(f);Pf=!1}}function Yj(){ov()}function ov(){Zc=Mf=!1;var s=0;qs!==0&&aE()&&(s=qs);for(var o=Ie(),f=null,g=Jc;g!==null;){var k=g.next,A=lv(g,o);A===0?(g.next=null,f===null?Jc=k:f.next=k,k===null&&(Ma=f)):(f=g,(s!==0||(A&3)!==0)&&(Zc=!0)),g=k}pn!==0&&pn!==5||Qo(s),qs!==0&&(qs=0)}function lv(s,o){for(var f=s.suspendedLanes,g=s.pingedLanes,k=s.expirationTimes,A=s.pendingLanes&-62914561;0<A;){var F=31-tt(A),Y=1<<F,le=k[F];le===-1?((Y&f)===0||(Y&g)!==0)&&(k[F]=St(Y,o)):le<=o&&(s.expiredLanes|=Y),A&=~Y}if(o=$t,f=wt,f=fe(s,s===o?f:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g=s.callbackNode,f===0||s===o&&(Dt===2||Dt===9)||s.cancelPendingCommit!==null)return g!==null&&g!==null&&Me(g),s.callbackNode=null,s.callbackPriority=0;if((f&3)===0||Pe(s,f)){if(o=f&-f,o===s.callbackPriority)return o;switch(g!==null&&Me(g),Ce(f)){case 2:case 8:f=ae;break;case 32:f=se;break;case 268435456:f=Ue;break;default:f=se}return g=cv.bind(null,s),f=je(f,g),s.callbackPriority=o,s.callbackNode=f,o}return g!==null&&g!==null&&Me(g),s.callbackPriority=2,s.callbackNode=null,2}function cv(s,o){if(pn!==0&&pn!==5)return s.callbackNode=null,s.callbackPriority=0,null;var f=s.callbackNode;if(Qc()&&s.callbackNode!==f)return null;var g=wt;return g=fe(s,s===$t?g:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g===0?null:(Vb(s,g,o),lv(s,Ie()),s.callbackNode!=null&&s.callbackNode===f?cv.bind(null,s):null)}function uv(s,o){if(Qc())return null;Vb(s,o,!0)}function Xj(){lE(function(){(Lt&6)!==0?je(te,Yj):ov()})}function Bf(){if(qs===0){var s=_a;s===0&&(s=Un,Un<<=1,(Un&261888)===0&&(Un=256)),qs=s}return qs}function dv(s){return s==null||typeof s=="symbol"||typeof s=="boolean"?null:typeof s=="function"?s:oc(""+s)}function hv(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 Qj(s,o,f,g,k){if(o==="submit"&&f&&f.stateNode===k){var A=dv((k[at]||null).action),F=g.submitter;F&&(o=(o=F[at]||null)?dv(o.formAction):F.getAttribute("formAction"),o!==null&&(A=o,F=null));var Y=new dc("action","action",null,g,k);s.push({event:Y,listeners:[{instance:null,listener:function(){if(g.defaultPrevented){if(qs!==0){var le=F?hv(k,F):new FormData(k);rf(f,{pending:!0,data:le,method:k.method,action:A},null,le)}}else typeof A=="function"&&(Y.preventDefault(),le=F?hv(k,F):new FormData(k),rf(f,{pending:!0,data:le,method:k.method,action:A},A,le))},currentTarget:k}]})}}for(var $f=0;$f<vh.length;$f++){var zf=vh[$f],Jj=zf.toLowerCase(),Zj=zf[0].toUpperCase()+zf.slice(1);jr(Jj,"on"+Zj)}jr(Fx,"onAnimationEnd"),jr(Vx,"onAnimationIteration"),jr(Gx,"onAnimationStart"),jr("dblclick","onDoubleClick"),jr("focusin","onFocus"),jr("focusout","onBlur"),jr(pj,"onTransitionRun"),jr(gj,"onTransitionStart"),jr(xj,"onTransitionCancel"),jr(Wx,"onTransitionEnd"),oa("onMouseEnter",["mouseout","mouseover"]),oa("onMouseLeave",["mouseout","mouseover"]),oa("onPointerEnter",["pointerout","pointerover"]),oa("onPointerLeave",["pointerout","pointerover"]),yi("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),yi("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),yi("onBeforeInput",["compositionend","keypress","textInput","paste"]),yi("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),yi("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),yi("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Jo="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(" "),eE=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Jo));function fv(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],le=Y.instance,ge=Y.currentTarget;if(Y=Y.listener,le!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){mc(ke)}k.currentTarget=null,A=le}else for(F=0;F<g.length;F++){if(Y=g[F],le=Y.instance,ge=Y.currentTarget,Y=Y.listener,le!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){mc(ke)}k.currentTarget=null,A=le}}}}function bt(s,o){var f=o[mn];f===void 0&&(f=o[mn]=new Set);var g=s+"__bubble";f.has(g)||(mv(o,s,2,!1),f.add(g))}function Hf(s,o,f){var g=0;o&&(g|=4),mv(f,s,g,o)}var eu="_reactListening"+Math.random().toString(36).slice(2);function Uf(s){if(!s[eu]){s[eu]=!0,ox.forEach(function(f){f!=="selectionchange"&&(eE.has(f)||Hf(f,!1,s),Hf(f,!0,s))});var o=s.nodeType===9?s:s.ownerDocument;o===null||o[eu]||(o[eu]=!0,Hf("selectionchange",!1,o))}}function mv(s,o,f,g){switch(Fv(o)){case 2:var k=NE;break;case 8:k=TE;break;default:k=rm}f=k.bind(null,o,f,s),k=void 0,!oh||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 Ff(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 le=F.tag;if((le===3||le===4)&&F.stateNode.containerInfo===k)return;F=F.return}for(;Y!==null;){if(F=sa(Y),F===null)return;if(le=F.tag,le===5||le===6||le===26||le===27){g=A=F;continue e}Y=Y.parentNode}}g=g.return}bx(function(){var ge=A,ke=ih(f),Ae=[];e:{var xe=qx.get(s);if(xe!==void 0){var be=dc,Ke=s;switch(s){case"keypress":if(cc(f)===0)break e;case"keydown":case"keyup":be=q2;break;case"focusin":Ke="focus",be=dh;break;case"focusout":Ke="blur",be=dh;break;case"beforeblur":case"afterblur":be=dh;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=Sx;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":be=I2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":be=X2;break;case Fx:case Vx:case Gx:be=B2;break;case Wx:be=J2;break;case"scroll":case"scrollend":be=R2;break;case"wheel":be=ej;break;case"copy":case"cut":case"paste":be=z2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":be=Cx;break;case"toggle":case"beforetoggle":be=nj}var it=(o&4)!==0,Mt=!it&&(s==="scroll"||s==="scrollend"),de=it?xe!==null?xe+"Capture":null:xe;it=[];for(var ue=ge,pe;ue!==null;){var Ne=ue;if(pe=Ne.stateNode,Ne=Ne.tag,Ne!==5&&Ne!==26&&Ne!==27||pe===null||de===null||(Ne=vo(ue,de),Ne!=null&&it.push(Zo(ue,Ne,pe))),Mt)break;ue=ue.return}0<it.length&&(xe=new be(xe,Ke,null,f,ke),Ae.push({event:xe,listeners:it}))}}if((o&7)===0){e:{if(xe=s==="mouseover"||s==="pointerover",be=s==="mouseout"||s==="pointerout",xe&&f!==sh&&(Ke=f.relatedTarget||f.fromElement)&&(sa(Ke)||Ke[Zt]))break e;if((be||xe)&&(xe=ke.window===ke?ke:(xe=ke.ownerDocument)?xe.defaultView||xe.parentWindow:window,be?(Ke=f.relatedTarget||f.toElement,be=ge,Ke=Ke?sa(Ke):null,Ke!==null&&(Mt=l(Ke),it=Ke.tag,Ke!==Mt||it!==5&&it!==27&&it!==6)&&(Ke=null)):(be=null,Ke=ge),be!==Ke)){if(it=Sx,Ne="onMouseLeave",de="onMouseEnter",ue="mouse",(s==="pointerout"||s==="pointerover")&&(it=Cx,Ne="onPointerLeave",de="onPointerEnter",ue="pointer"),Mt=be==null?xe:bo(be),pe=Ke==null?xe:bo(Ke),xe=new it(Ne,ue+"leave",be,f,ke),xe.target=Mt,xe.relatedTarget=pe,Ne=null,sa(ke)===ge&&(it=new it(de,ue+"enter",Ke,f,ke),it.target=pe,it.relatedTarget=Mt,Ne=it),Mt=Ne,be&&Ke)t:{for(it=tE,de=be,ue=Ke,pe=0,Ne=de;Ne;Ne=it(Ne))pe++;Ne=0;for(var et=ue;et;et=it(et))Ne++;for(;0<pe-Ne;)de=it(de),pe--;for(;0<Ne-pe;)ue=it(ue),Ne--;for(;pe--;){if(de===ue||ue!==null&&de===ue.alternate){it=de;break t}de=it(de),ue=it(ue)}it=null}else it=null;be!==null&&pv(Ae,xe,be,it,!1),Ke!==null&&Mt!==null&&pv(Ae,Mt,Ke,it,!0)}}e:{if(xe=ge?bo(ge):window,be=xe.nodeName&&xe.nodeName.toLowerCase(),be==="select"||be==="input"&&xe.type==="file")var Tt=Dx;else if(Ax(xe))if(Rx)Tt=hj;else{Tt=uj;var Xe=cj}else be=xe.nodeName,!be||be.toLowerCase()!=="input"||xe.type!=="checkbox"&&xe.type!=="radio"?ge&&rh(ge.elementType)&&(Tt=Dx):Tt=dj;if(Tt&&(Tt=Tt(s,ge))){Lx(Ae,Tt,f,ke);break e}Xe&&Xe(s,xe,ge),s==="focusout"&&ge&&xe.type==="number"&&ge.memoizedProps.value!=null&&nh(xe,"number",xe.value)}switch(Xe=ge?bo(ge):window,s){case"focusin":(Ax(Xe)||Xe.contentEditable==="true")&&(fa=Xe,xh=ge,No=null);break;case"focusout":No=xh=fa=null;break;case"mousedown":yh=!0;break;case"contextmenu":case"mouseup":case"dragend":yh=!1,Hx(Ae,f,ke);break;case"selectionchange":if(mj)break;case"keydown":case"keyup":Hx(Ae,f,ke)}var mt;if(fh)e:{switch(s){case"compositionstart":var Ct="onCompositionStart";break e;case"compositionend":Ct="onCompositionEnd";break e;case"compositionupdate":Ct="onCompositionUpdate";break e}Ct=void 0}else ha?Nx(s,f)&&(Ct="onCompositionEnd"):s==="keydown"&&f.keyCode===229&&(Ct="onCompositionStart");Ct&&(kx&&f.locale!=="ko"&&(ha||Ct!=="onCompositionStart"?Ct==="onCompositionEnd"&&ha&&(mt=vx()):(Ls=ke,lh="value"in Ls?Ls.value:Ls.textContent,ha=!0)),Xe=tu(ge,Ct),0<Xe.length&&(Ct=new wx(Ct,s,null,f,ke),Ae.push({event:Ct,listeners:Xe}),mt?Ct.data=mt:(mt=Tx(f),mt!==null&&(Ct.data=mt)))),(mt=sj?ij(s,f):aj(s,f))&&(Ct=tu(ge,"onBeforeInput"),0<Ct.length&&(Xe=new wx("onBeforeInput","beforeinput",null,f,ke),Ae.push({event:Xe,listeners:Ct}),Xe.data=mt)),Qj(Ae,s,ge,f,ke)}fv(Ae,o)})}function Zo(s,o,f){return{instance:s,listener:o,currentTarget:f}}function tu(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=vo(s,f),k!=null&&g.unshift(Zo(s,k,A)),k=vo(s,o),k!=null&&g.push(Zo(s,k,A))),s.tag===3)return g;s=s.return}return[]}function tE(s){if(s===null)return null;do s=s.return;while(s&&s.tag!==5&&s.tag!==27);return s||null}function pv(s,o,f,g,k){for(var A=o._reactName,F=[];f!==null&&f!==g;){var Y=f,le=Y.alternate,ge=Y.stateNode;if(Y=Y.tag,le!==null&&le===g)break;Y!==5&&Y!==26&&Y!==27||ge===null||(le=ge,k?(ge=vo(f,A),ge!=null&&F.unshift(Zo(f,ge,le))):k||(ge=vo(f,A),ge!=null&&F.push(Zo(f,ge,le)))),f=f.return}F.length!==0&&s.push({event:o,listeners:F})}var nE=/\r\n?/g,rE=/\u0000|\uFFFD/g;function gv(s){return(typeof s=="string"?s:""+s).replace(nE,`
50
- `).replace(rE,"")}function xv(s,o){return o=gv(o),gv(s)===o}function It(s,o,f,g,k,A){switch(f){case"children":typeof g=="string"?o==="body"||o==="textarea"&&g===""||ca(s,g):(typeof g=="number"||typeof g=="bigint")&&o!=="body"&&ca(s,""+g);break;case"className":ic(s,"class",g);break;case"tabIndex":ic(s,"tabindex",g);break;case"dir":case"role":case"viewBox":case"width":case"height":ic(s,f,g);break;case"style":xx(s,g,A);break;case"data":if(o!=="object"){ic(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=oc(""+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"&&It(s,o,"name",k.name,k,null),It(s,o,"formEncType",k.formEncType,k,null),It(s,o,"formMethod",k.formMethod,k,null),It(s,o,"formTarget",k.formTarget,k,null)):(It(s,o,"encType",k.encType,k,null),It(s,o,"method",k.method,k,null),It(s,o,"target",k.target,k,null)));if(g==null||typeof g=="symbol"||typeof g=="boolean"){s.removeAttribute(f);break}g=oc(""+g),s.setAttribute(f,g);break;case"onClick":g!=null&&(s.onclick=Zr);break;case"onScroll":g!=null&&bt("scroll",s);break;case"onScrollEnd":g!=null&&bt("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=oc(""+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":bt("beforetoggle",s),bt("toggle",s),sc(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":sc(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=L2.get(f)||f,sc(s,f,g))}}function Vf(s,o,f,g,k,A){switch(f){case"style":xx(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"?ca(s,g):(typeof g=="number"||typeof g=="bigint")&&ca(s,""+g);break;case"onScroll":g!=null&&bt("scroll",s);break;case"onScrollEnd":g!=null&&bt("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(!lx.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[at]||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,""):sc(s,f,g)}}}function En(s,o,f){switch(o){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":bt("error",s),bt("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:It(s,o,A,F,f,null)}}k&&It(s,o,"srcSet",f.srcSet,f,null),g&&It(s,o,"src",f.src,f,null);return;case"input":bt("invalid",s);var Y=A=F=k=null,le=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":le=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:It(s,o,g,ke,f,null)}}fx(s,A,Y,le,ge,F,k,!1);return;case"select":bt("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:It(s,o,k,Y,f,null)}o=A,f=F,s.multiple=!!g,o!=null?la(s,!!g,o,!1):f!=null&&la(s,!!g,f,!0);return;case"textarea":bt("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:It(s,o,F,Y,f,null)}px(s,g,k,A);return;case"option":for(le in f)if(f.hasOwnProperty(le)&&(g=f[le],g!=null))switch(le){case"selected":s.selected=g&&typeof g!="function"&&typeof g!="symbol";break;default:It(s,o,le,g,f,null)}return;case"dialog":bt("beforetoggle",s),bt("toggle",s),bt("cancel",s),bt("close",s);break;case"iframe":case"object":bt("load",s);break;case"video":case"audio":for(g=0;g<Jo.length;g++)bt(Jo[g],s);break;case"image":bt("error",s),bt("load",s);break;case"details":bt("toggle",s);break;case"embed":case"source":case"link":bt("error",s),bt("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:It(s,o,ge,g,f,null)}return;default:if(rh(o)){for(ke in f)f.hasOwnProperty(ke)&&(g=f[ke],g!==void 0&&Vf(s,o,ke,g,f,void 0));return}}for(Y in f)f.hasOwnProperty(Y)&&(g=f[Y],g!=null&&It(s,o,Y,g,f,null))}function sE(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,le=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":le=Ae;default:g.hasOwnProperty(be)||It(s,o,be,null,g,Ae)}}for(var xe in g){var be=g[xe];if(Ae=f[xe],g.hasOwnProperty(xe)&&(be!=null||Ae!=null))switch(xe){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&&It(s,o,xe,be,g,Ae)}}th(s,F,Y,le,ge,ke,A,k);return;case"select":be=F=Y=xe=null;for(A in f)if(le=f[A],f.hasOwnProperty(A)&&le!=null)switch(A){case"value":break;case"multiple":be=le;default:g.hasOwnProperty(A)||It(s,o,A,null,g,le)}for(k in g)if(A=g[k],le=f[k],g.hasOwnProperty(k)&&(A!=null||le!=null))switch(k){case"value":xe=A;break;case"defaultValue":Y=A;break;case"multiple":F=A;default:A!==le&&It(s,o,k,A,g,le)}o=Y,f=F,g=be,xe!=null?la(s,!!f,xe,!1):!!g!=!!f&&(o!=null?la(s,!!f,o,!0):la(s,!!f,f?[]:"",!1));return;case"textarea":be=xe=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:It(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":xe=k;break;case"defaultValue":be=k;break;case"children":break;case"dangerouslySetInnerHTML":if(k!=null)throw Error(r(91));break;default:k!==A&&It(s,o,F,k,g,A)}mx(s,xe,be);return;case"option":for(var Ke in f)if(xe=f[Ke],f.hasOwnProperty(Ke)&&xe!=null&&!g.hasOwnProperty(Ke))switch(Ke){case"selected":s.selected=!1;break;default:It(s,o,Ke,null,g,xe)}for(le in g)if(xe=g[le],be=f[le],g.hasOwnProperty(le)&&xe!==be&&(xe!=null||be!=null))switch(le){case"selected":s.selected=xe&&typeof xe!="function"&&typeof xe!="symbol";break;default:It(s,o,le,xe,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 it in f)xe=f[it],f.hasOwnProperty(it)&&xe!=null&&!g.hasOwnProperty(it)&&It(s,o,it,null,g,xe);for(ge in g)if(xe=g[ge],be=f[ge],g.hasOwnProperty(ge)&&xe!==be&&(xe!=null||be!=null))switch(ge){case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(r(137,o));break;default:It(s,o,ge,xe,g,be)}return;default:if(rh(o)){for(var Mt in f)xe=f[Mt],f.hasOwnProperty(Mt)&&xe!==void 0&&!g.hasOwnProperty(Mt)&&Vf(s,o,Mt,void 0,g,xe);for(ke in g)xe=g[ke],be=f[ke],!g.hasOwnProperty(ke)||xe===be||xe===void 0&&be===void 0||Vf(s,o,ke,xe,g,be);return}}for(var de in f)xe=f[de],f.hasOwnProperty(de)&&xe!=null&&!g.hasOwnProperty(de)&&It(s,o,de,null,g,xe);for(Ae in g)xe=g[Ae],be=f[Ae],!g.hasOwnProperty(Ae)||xe===be||xe==null&&be==null||It(s,o,Ae,xe,g,be)}function yv(s){switch(s){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function iE(){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&&yv(F)){for(F=0,Y=k.responseEnd,g+=1;g<f.length;g++){var le=f[g],ge=le.startTime;if(ge>Y)break;var ke=le.transferSize,Ae=le.initiatorType;ke&&yv(Ae)&&(le=le.responseEnd,F+=ke*(le<Y?1:(Y-ge)/(le-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 Gf=null,Wf=null;function nu(s){return s.nodeType===9?s:s.ownerDocument}function bv(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 vv(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 qf(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 Kf=null;function aE(){var s=window.event;return s&&s.type==="popstate"?s===Kf?!1:(Kf=s,!0):(Kf=null,!1)}var _v=typeof setTimeout=="function"?setTimeout:void 0,oE=typeof clearTimeout=="function"?clearTimeout:void 0,Sv=typeof Promise=="function"?Promise:void 0,lE=typeof queueMicrotask=="function"?queueMicrotask:typeof Sv<"u"?function(s){return Sv.resolve(null).then(s).catch(cE)}:_v;function cE(s){setTimeout(function(){throw s})}function Ks(s){return s==="head"}function wv(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),za(o);return}g--}else if(f==="$"||f==="$?"||f==="$~"||f==="$!"||f==="&")g++;else if(f==="html")el(s.ownerDocument.documentElement);else if(f==="head"){f=s.ownerDocument.head,el(f);for(var A=f.firstChild;A;){var F=A.nextSibling,Y=A.nodeName;A[yo]||Y==="SCRIPT"||Y==="STYLE"||Y==="LINK"&&A.rel.toLowerCase()==="stylesheet"||f.removeChild(A),A=F}}else f==="body"&&el(s.ownerDocument.body);f=k}while(f);za(o)}function Cv(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 Yf(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":Yf(f),Zd(f);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(f.rel.toLowerCase()==="stylesheet")continue}s.removeChild(f)}}function uE(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[yo])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=yr(s.nextSibling),s===null)break}return null}function dE(s,o,f){if(o==="")return null;for(;s.nodeType!==3;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!f||(s=yr(s.nextSibling),s===null))return null;return s}function kv(s,o){for(;s.nodeType!==8;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!o||(s=yr(s.nextSibling),s===null))return null;return s}function Xf(s){return s.data==="$?"||s.data==="$~"}function Qf(s){return s.data==="$!"||s.data==="$?"&&s.ownerDocument.readyState!=="loading"}function hE(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 yr(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 Jf=null;function jv(s){s=s.nextSibling;for(var o=0;s;){if(s.nodeType===8){var f=s.data;if(f==="/$"||f==="/&"){if(o===0)return yr(s.nextSibling);o--}else f!=="$"&&f!=="$!"&&f!=="$?"&&f!=="$~"&&f!=="&"||o++}s=s.nextSibling}return null}function Ev(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 Nv(s,o,f){switch(o=nu(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 el(s){for(var o=s.attributes;o.length;)s.removeAttributeNode(o[0]);Zd(s)}var br=new Map,Tv=new Set;function ru(s){return typeof s.getRootNode=="function"?s.getRootNode():s.nodeType===9?s:s.ownerDocument}var ps=Z.d;Z.d={f:fE,r:mE,D:pE,C:gE,L:xE,m:yE,X:vE,S:bE,M:_E};function fE(){var s=ps.f(),o=Kc();return s||o}function mE(s){var o=ia(s);o!==null&&o.tag===5&&o.type==="form"?Wy(o):ps.r(s)}var Pa=typeof document>"u"?null:document;function Av(s,o,f){var g=Pa;if(g&&typeof o=="string"&&o){var k=dr(o);k='link[rel="'+s+'"][href="'+k+'"]',typeof f=="string"&&(k+='[crossorigin="'+f+'"]'),Tv.has(k)||(Tv.add(k),s={rel:s,crossOrigin:f,href:o},g.querySelector(k)===null&&(o=g.createElement("link"),En(o,"link",s),vn(o),g.head.appendChild(o)))}}function pE(s){ps.D(s),Av("dns-prefetch",s,null)}function gE(s,o){ps.C(s,o),Av("preconnect",s,o)}function xE(s,o,f){ps.L(s,o,f);var g=Pa;if(g&&s&&o){var k='link[rel="preload"][as="'+dr(o)+'"]';o==="image"&&f&&f.imageSrcSet?(k+='[imagesrcset="'+dr(f.imageSrcSet)+'"]',typeof f.imageSizes=="string"&&(k+='[imagesizes="'+dr(f.imageSizes)+'"]')):k+='[href="'+dr(s)+'"]';var A=k;switch(o){case"style":A=Ba(s);break;case"script":A=$a(s)}br.has(A)||(s=m({rel:"preload",href:o==="image"&&f&&f.imageSrcSet?void 0:s,as:o},f),br.set(A,s),g.querySelector(k)!==null||o==="style"&&g.querySelector(tl(A))||o==="script"&&g.querySelector(nl(A))||(o=g.createElement("link"),En(o,"link",s),vn(o),g.head.appendChild(o)))}}function yE(s,o){ps.m(s,o);var f=Pa;if(f&&s){var g=o&&typeof o.as=="string"?o.as:"script",k='link[rel="modulepreload"][as="'+dr(g)+'"][href="'+dr(s)+'"]',A=k;switch(g){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":A=$a(s)}if(!br.has(A)&&(s=m({rel:"modulepreload",href:s},o),br.set(A,s),f.querySelector(k)===null)){switch(g){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(f.querySelector(nl(A)))return}g=f.createElement("link"),En(g,"link",s),vn(g),f.head.appendChild(g)}}}function bE(s,o,f){ps.S(s,o,f);var g=Pa;if(g&&s){var k=aa(g).hoistableStyles,A=Ba(s);o=o||"default";var F=k.get(A);if(!F){var Y={loading:0,preload:null};if(F=g.querySelector(tl(A)))Y.loading=5;else{s=m({rel:"stylesheet",href:s,"data-precedence":o},f),(f=br.get(A))&&Zf(s,f);var le=F=g.createElement("link");vn(le),En(le,"link",s),le._p=new Promise(function(ge,ke){le.onload=ge,le.onerror=ke}),le.addEventListener("load",function(){Y.loading|=1}),le.addEventListener("error",function(){Y.loading|=2}),Y.loading|=4,su(F,o,g)}F={type:"stylesheet",instance:F,count:1,state:Y},k.set(A,F)}}}function vE(s,o){ps.X(s,o);var f=Pa;if(f&&s){var g=aa(f).hoistableScripts,k=$a(s),A=g.get(k);A||(A=f.querySelector(nl(k)),A||(s=m({src:s,async:!0},o),(o=br.get(k))&&em(s,o),A=f.createElement("script"),vn(A),En(A,"link",s),f.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},g.set(k,A))}}function _E(s,o){ps.M(s,o);var f=Pa;if(f&&s){var g=aa(f).hoistableScripts,k=$a(s),A=g.get(k);A||(A=f.querySelector(nl(k)),A||(s=m({src:s,async:!0,type:"module"},o),(o=br.get(k))&&em(s,o),A=f.createElement("script"),vn(A),En(A,"link",s),f.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},g.set(k,A))}}function Lv(s,o,f,g){var k=(k=Q.current)?ru(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=Ba(f.href),f=aa(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=Ba(f.href);var A=aa(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(tl(s)))&&!A._p&&(F.instance=A,F.state.loading=5),br.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},br.set(s,f),A||SE(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=$a(f),f=aa(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 Ba(s){return'href="'+dr(s)+'"'}function tl(s){return'link[rel="stylesheet"]['+s+"]"}function Dv(s){return m({},s,{"data-precedence":s.precedence,precedence:null})}function SE(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}),En(o,"link",f),vn(o),s.head.appendChild(o))}function $a(s){return'[src="'+dr(s)+'"]'}function nl(s){return"script[async]"+s}function Rv(s,o,f){if(o.count++,o.instance===null)switch(o.type){case"style":var g=s.querySelector('style[data-href~="'+dr(f.href)+'"]');if(g)return o.instance=g,vn(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"),vn(g),En(g,"style",k),su(g,f.precedence,s),o.instance=g;case"stylesheet":k=Ba(f.href);var A=s.querySelector(tl(k));if(A)return o.state.loading|=4,o.instance=A,vn(A),A;g=Dv(f),(k=br.get(k))&&Zf(g,k),A=(s.ownerDocument||s).createElement("link"),vn(A);var F=A;return F._p=new Promise(function(Y,le){F.onload=Y,F.onerror=le}),En(A,"link",g),o.state.loading|=4,su(A,f.precedence,s),o.instance=A;case"script":return A=$a(f.src),(k=s.querySelector(nl(A)))?(o.instance=k,vn(k),k):(g=f,(k=br.get(A))&&(g=m({},f),em(g,k)),s=s.ownerDocument||s,k=s.createElement("script"),vn(k),En(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,su(g,f.precedence,s));return o.instance}function su(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 Zf(s,o){s.crossOrigin==null&&(s.crossOrigin=o.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=o.referrerPolicy),s.title==null&&(s.title=o.title)}function em(s,o){s.crossOrigin==null&&(s.crossOrigin=o.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=o.referrerPolicy),s.integrity==null&&(s.integrity=o.integrity)}var iu=null;function Ov(s,o,f){if(iu===null){var g=new Map,k=iu=new Map;k.set(f,g)}else k=iu,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[yo]||A[Qe]||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 Iv(s,o,f){s=s.ownerDocument||s,s.head.insertBefore(f,o==="title"?s.querySelector("head > title"):null)}function wE(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 Mv(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function CE(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=Ba(g.href),A=o.querySelector(tl(k));if(A){o=A._p,o!==null&&typeof o=="object"&&typeof o.then=="function"&&(s.count++,s=au.bind(s),o.then(s,s)),f.state.loading|=4,f.instance=A,vn(A);return}A=o.ownerDocument||o,g=Dv(g),(k=br.get(k))&&Zf(g,k),A=A.createElement("link"),vn(A);var F=A;F._p=new Promise(function(Y,le){F.onload=Y,F.onerror=le}),En(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=au.bind(s),o.addEventListener("load",f),o.addEventListener("error",f))}}var tm=0;function kE(s,o){return s.stylesheets&&s.count===0&&lu(s,s.stylesheets),0<s.count||0<s.imgCount?function(f){var g=setTimeout(function(){if(s.stylesheets&&lu(s,s.stylesheets),s.unsuspend){var A=s.unsuspend;s.unsuspend=null,A()}},6e4+o);0<s.imgBytes&&tm===0&&(tm=62500*iE());var k=setTimeout(function(){if(s.waitingForImages=!1,s.count===0&&(s.stylesheets&&lu(s,s.stylesheets),s.unsuspend)){var A=s.unsuspend;s.unsuspend=null,A()}},(s.imgBytes>tm?50:800)+o);return s.unsuspend=f,function(){s.unsuspend=null,clearTimeout(g),clearTimeout(k)}}:null}function au(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)lu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var ou=null;function lu(s,o){s.stylesheets=null,s.unsuspend!==null&&(s.count++,ou=new Map,o.forEach(jE,s),ou=null,au.call(s))}function jE(s,o){if(!(o.state.loading&4)){var f=ou.get(s);if(f)var g=f.get(null);else{f=new Map,ou.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=au.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 rl={$$typeof:b,Provider:null,Consumer:null,_currentValue:X,_currentValue2:X,_threadCount:0};function EE(s,o,f,g,k,A,F,Y,le){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=fn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=fn(0),this.hiddenUpdates=fn(null),this.identifierPrefix=g,this.onUncaughtError=k,this.onCaughtError=A,this.onRecoverableError=F,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=le,this.incompleteTransitions=new Map}function Pv(s,o,f,g,k,A,F,Y,le,ge,ke,Ae){return s=new EE(s,o,f,F,le,ge,ke,Ae,Y),o=1,A===!0&&(o|=24),A=tr(3,null,null,o),s.current=A,A.stateNode=s,o=Rh(),o.refCount++,s.pooledCache=o,o.refCount++,A.memoizedState={element:g,isDehydrated:f,cache:o},Ph(A),s}function Bv(s){return s?(s=ga,s):ga}function $v(s,o,f,g,k,A){k=Bv(k),g.context===null?g.context=k:g.pendingContext=k,g=Ps(o),g.payload={element:f},A=A===void 0?null:A,A!==null&&(g.callback=A),f=Bs(s,g,o),f!==null&&(Kn(f,s,o),Io(f,s,o))}function zv(s,o){if(s=s.memoizedState,s!==null&&s.dehydrated!==null){var f=s.retryLane;s.retryLane=f!==0&&f<o?f:o}}function nm(s,o){zv(s,o),(s=s.alternate)&&zv(s,o)}function Hv(s){if(s.tag===13||s.tag===31){var o=Si(s,67108864);o!==null&&Kn(o,s,67108864),nm(s,67108864)}}function Uv(s){if(s.tag===13||s.tag===31){var o=ar();o=Se(o);var f=Si(s,o);f!==null&&Kn(f,s,o),nm(s,o)}}var cu=!0;function NE(s,o,f,g){var k=V.T;V.T=null;var A=Z.p;try{Z.p=2,rm(s,o,f,g)}finally{Z.p=A,V.T=k}}function TE(s,o,f,g){var k=V.T;V.T=null;var A=Z.p;try{Z.p=8,rm(s,o,f,g)}finally{Z.p=A,V.T=k}}function rm(s,o,f,g){if(cu){var k=sm(g);if(k===null)Ff(s,o,g,uu,f),Vv(s,g);else if(LE(k,s,o,f,g))g.stopPropagation();else if(Vv(s,g),o&4&&-1<AE.indexOf(s)){for(;k!==null;){var A=ia(k);if(A!==null)switch(A.tag){case 3:if(A=A.stateNode,A.current.memoizedState.isDehydrated){var F=oe(A.pendingLanes);if(F!==0){var Y=A;for(Y.pendingLanes|=2,Y.entangledLanes|=2;F;){var le=1<<31-tt(F);Y.entanglements[1]|=le,F&=~le}Hr(A),(Lt&6)===0&&(Wc=Ie()+500,Qo(0))}}break;case 31:case 13:Y=Si(A,2),Y!==null&&Kn(Y,A,2),Kc(),nm(A,2)}if(A=sm(g),A===null&&Ff(s,o,g,uu,f),A===k)break;k=A}k!==null&&g.stopPropagation()}else Ff(s,o,g,null,f)}}function sm(s){return s=ih(s),im(s)}var uu=null;function im(s){if(uu=null,s=sa(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 uu=s,null}function Fv(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(qe()){case te:return 2;case ae:return 8;case se:case me:return 32;case Ue:return 268435456;default:return 32}default:return 32}}var am=!1,Ys=null,Xs=null,Qs=null,sl=new Map,il=new Map,Js=[],AE="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 Vv(s,o){switch(s){case"focusin":case"focusout":Ys=null;break;case"dragenter":case"dragleave":Xs=null;break;case"mouseover":case"mouseout":Qs=null;break;case"pointerover":case"pointerout":sl.delete(o.pointerId);break;case"gotpointercapture":case"lostpointercapture":il.delete(o.pointerId)}}function al(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=ia(o),o!==null&&Hv(o)),s):(s.eventSystemFlags|=g,o=s.targetContainers,k!==null&&o.indexOf(k)===-1&&o.push(k),s)}function LE(s,o,f,g,k){switch(o){case"focusin":return Ys=al(Ys,s,o,f,g,k),!0;case"dragenter":return Xs=al(Xs,s,o,f,g,k),!0;case"mouseover":return Qs=al(Qs,s,o,f,g,k),!0;case"pointerover":var A=k.pointerId;return sl.set(A,al(sl.get(A)||null,s,o,f,g,k)),!0;case"gotpointercapture":return A=k.pointerId,il.set(A,al(il.get(A)||null,s,o,f,g,k)),!0}return!1}function Gv(s){var o=sa(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,We(s.priority,function(){Uv(f)});return}}else if(o===31){if(o=c(f),o!==null){s.blockedOn=o,We(s.priority,function(){Uv(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 du(s){if(s.blockedOn!==null)return!1;for(var o=s.targetContainers;0<o.length;){var f=sm(s.nativeEvent);if(f===null){f=s.nativeEvent;var g=new f.constructor(f.type,f);sh=g,f.target.dispatchEvent(g),sh=null}else return o=ia(f),o!==null&&Hv(o),s.blockedOn=f,!1;o.shift()}return!0}function Wv(s,o,f){du(s)&&f.delete(o)}function DE(){am=!1,Ys!==null&&du(Ys)&&(Ys=null),Xs!==null&&du(Xs)&&(Xs=null),Qs!==null&&du(Qs)&&(Qs=null),sl.forEach(Wv),il.forEach(Wv)}function hu(s,o){s.blockedOn===o&&(s.blockedOn=null,am||(am=!0,e.unstable_scheduleCallback(e.unstable_NormalPriority,DE)))}var fu=null;function qv(s){fu!==s&&(fu=s,e.unstable_scheduleCallback(e.unstable_NormalPriority,function(){fu===s&&(fu=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(im(g||f)===null)continue;break}var A=ia(f);A!==null&&(s.splice(o,3),o-=3,rf(A,{pending:!0,data:k,method:f.method,action:g},g,k))}}))}function za(s){function o(le){return hu(le,s)}Ys!==null&&hu(Ys,s),Xs!==null&&hu(Xs,s),Qs!==null&&hu(Qs,s),sl.forEach(o),il.forEach(o);for(var f=0;f<Js.length;f++){var g=Js[f];g.blockedOn===s&&(g.blockedOn=null)}for(;0<Js.length&&(f=Js[0],f.blockedOn===null);)Gv(f),f.blockedOn===null&&Js.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[at]||null;if(typeof A=="function")F||qv(f);else if(F){var Y=null;if(A&&A.hasAttribute("formAction")){if(k=A,F=A[at]||null)Y=F.formAction;else if(im(k)!==null)continue}else Y=F.action;typeof Y=="function"?f[g+1]=Y:(f.splice(g,3),g-=3),qv(f)}}}function Kv(){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 om(s){this._internalRoot=s}mu.prototype.render=om.prototype.render=function(s){var o=this._internalRoot;if(o===null)throw Error(r(409));var f=o.current,g=ar();$v(f,g,s,o,null,null)},mu.prototype.unmount=om.prototype.unmount=function(){var s=this._internalRoot;if(s!==null){this._internalRoot=null;var o=s.containerInfo;$v(s.current,2,null,s,null,null),Kc(),o[Zt]=null}};function mu(s){this._internalRoot=s}mu.prototype.unstable_scheduleHydration=function(s){if(s){var o=Oe();s={blockedOn:null,target:s,priority:o};for(var f=0;f<Js.length&&o!==0&&o<Js[f].priority;f++);Js.splice(f,0,s),f===0&&Gv(s)}};var Yv=t.version;if(Yv!=="19.2.4")throw Error(r(527,Yv,"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 RE={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:V,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var pu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!pu.isDisabled&&pu.supportsFiber)try{ct=pu.inject(RE),Je=pu}catch{}}return ll.createRoot=function(s,o){if(!a(s))throw Error(r(299));var f=!1,g="",k=nb,A=rb,F=sb;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=Pv(s,1,!1,null,null,f,g,null,k,A,F,Kv),s[Zt]=o.current,Uf(s),new om(o)},ll.hydrateRoot=function(s,o,f){if(!a(s))throw Error(r(299));var g=!1,k="",A=nb,F=rb,Y=sb,le=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&&(le=f.formState)),o=Pv(s,1,!0,o,f??null,g,k,le,A,F,Y,Kv),o.context=Bv(null),f=o.current,g=ar(),g=Se(g),k=Ps(g),k.callback=null,Bs(f,k,g),f=g,o.current.lanes=f,Pr(o,f),Hr(o),s[Zt]=o.current,Uf(s),new mu(o)},ll.version="19.2.4",ll}var o_;function KE(){if(o_)return hm.exports;o_=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(),hm.exports=qE(),hm.exports}var YE=KE();const XE=_d(YE);function QE(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 gm={exports:{}},xm={};/**
49
+ `+g.stack}}var ot=Object.prototype.hasOwnProperty,je=e.unstable_scheduleCallback,Me=e.unstable_cancelCallback,lt=e.unstable_shouldYield,we=e.unstable_requestPaint,Ie=e.unstable_now,qe=e.unstable_getCurrentPriorityLevel,te=e.unstable_ImmediatePriority,ae=e.unstable_UserBlockingPriority,se=e.unstable_NormalPriority,me=e.unstable_LowPriority,Ue=e.unstable_IdlePriority,He=e.log,Ye=e.unstable_setDisableYieldValue,ct=null,Je=null;function Ze(s){if(typeof He=="function"&&Ye(s),Je&&typeof Je.setStrictMode=="function")try{Je.setStrictMode(ct,s)}catch{}}var tt=Math.clz32?Math.clz32:rn,Nt=Math.log,dt=Math.LN2;function rn(s){return s>>>=0,s===0?32:31-(Nt(s)/dt|0)|0}var Un=256,ye=262144,Ge=4194304;function oe(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 fe(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=oe(g):(F&=Y,F!==0?k=oe(F):f||(f=Y&~s,f!==0&&(k=oe(f))))):(Y=g&~A,Y!==0?k=oe(Y):F!==0?k=oe(F):f||(f=g&~s,f!==0&&(k=oe(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 Pe(s,o){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&o)===0}function St(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 bn(){var s=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),s}function fn(s){for(var o=[],f=0;31>f;f++)o.push(s);return o}function Pr(s,o){s.pendingLanes|=o,o!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function Ns(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,le=s.expirationTimes,ge=s.hiddenUpdates;for(f=F&~f;0<f;){var ke=31-tt(f),Ae=1<<ke;Y[ke]=0,le[ke]=-1;var xe=ge[ke];if(xe!==null)for(ge[ke]=null,ke=0;ke<xe.length;ke++){var be=xe[ke];be!==null&&(be.lane&=-536870913)}f&=~Ae}g!==0&&xi(s,g,0),A!==0&&k===0&&s.tag!==0&&(s.suspendedLanes|=A&~(F&~o))}function xi(s,o,f){s.pendingLanes|=o,s.suspendedLanes&=~o;var g=31-tt(o);s.entangledLanes|=o,s.entanglements[g]=s.entanglements[g]|1073741824|f&261930}function Ts(s,o){var f=s.entangledLanes|=o;for(s=s.entanglements;f;){var g=31-tt(f),k=1<<g;k&o|s[g]&o&&(s[g]|=o),f&=~k}}function As(s,o){var f=o&-o;return f=(f&42)!==0?1:Se(f),(f&(s.suspendedLanes|o))!==0?0:f}function Se(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 Ce(s){return s&=-s,2<s?8<s?(s&134217727)!==0?32:268435456:8:2}function Oe(){var s=Z.p;return s!==0?s:(s=window.event,s===void 0?32:Fv(s.type))}function We(s,o){var f=Z.p;try{return Z.p=s,o()}finally{Z.p=f}}var Ve=Math.random().toString(36).slice(2),Qe="__reactFiber$"+Ve,at="__reactProps$"+Ve,Zt="__reactContainer$"+Ve,mn="__reactEvents$"+Ve,Zn="__reactListeners$"+Ve,kj="__reactHandles$"+Ve,ax="__reactResources$"+Ve,yo="__reactMarker$"+Ve;function Zd(s){delete s[Qe],delete s[at],delete s[mn],delete s[Zn],delete s[kj]}function sa(s){var o=s[Qe];if(o)return o;for(var f=s.parentNode;f;){if(o=f[Zt]||f[Qe]){if(f=o.alternate,o.child!==null||f!==null&&f.child!==null)for(s=Ev(s);s!==null;){if(f=s[Qe])return f;s=Ev(s)}return o}s=f,f=s.parentNode}return null}function ia(s){if(s=s[Qe]||s[Zt]){var o=s.tag;if(o===5||o===6||o===13||o===31||o===26||o===27||o===3)return s}return null}function bo(s){var o=s.tag;if(o===5||o===26||o===27||o===6)return s.stateNode;throw Error(r(33))}function aa(s){var o=s[ax];return o||(o=s[ax]={hoistableStyles:new Map,hoistableScripts:new Map}),o}function vn(s){s[yo]=!0}var ox=new Set,lx={};function yi(s,o){oa(s,o),oa(s+"Capture",o)}function oa(s,o){for(lx[s]=o,s=0;s<o.length;s++)ox.add(o[s])}var jj=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]*$"),cx={},ux={};function Ej(s){return ot.call(ux,s)?!0:ot.call(cx,s)?!1:jj.test(s)?ux[s]=!0:(cx[s]=!0,!1)}function sc(s,o,f){if(Ej(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 ic(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 ur(s){switch(typeof s){case"bigint":case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function dx(s){var o=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(o==="checkbox"||o==="radio")}function Nj(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 eh(s){if(!s._valueTracker){var o=dx(s)?"checked":"value";s._valueTracker=Nj(s,o,""+s[o])}}function hx(s){if(!s)return!1;var o=s._valueTracker;if(!o)return!0;var f=o.getValue(),g="";return s&&(g=dx(s)?s.checked?"true":"false":s.value),s=g,s!==f?(o.setValue(s),!0):!1}function ac(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 Tj=/[\n"\\]/g;function dr(s){return s.replace(Tj,function(o){return"\\"+o.charCodeAt(0).toString(16)+" "})}function th(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=""+ur(o)):s.value!==""+ur(o)&&(s.value=""+ur(o)):F!=="submit"&&F!=="reset"||s.removeAttribute("value"),o!=null?nh(s,F,ur(o)):f!=null?nh(s,F,ur(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=""+ur(Y):s.removeAttribute("name")}function fx(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)){eh(s);return}f=f!=null?""+ur(f):"",o=o!=null?""+ur(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),eh(s)}function nh(s,o,f){o==="number"&&ac(s.ownerDocument)===s||s.defaultValue===""+f||(s.defaultValue=""+f)}function la(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=""+ur(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 mx(s,o,f){if(o!=null&&(o=""+ur(o),o!==s.value&&(s.value=o),f==null)){s.defaultValue!==o&&(s.defaultValue=o);return}s.defaultValue=f!=null?""+ur(f):""}function px(s,o,f,g){if(o==null){if(g!=null){if(f!=null)throw Error(r(92));if(G(g)){if(1<g.length)throw Error(r(93));g=g[0]}f=g}f==null&&(f=""),o=f}f=ur(o),s.defaultValue=f,g=s.textContent,g===f&&g!==""&&g!==null&&(s.value=g),eh(s)}function ca(s,o){if(o){var f=s.firstChild;if(f&&f===s.lastChild&&f.nodeType===3){f.nodeValue=o;return}}s.textContent=o}var Aj=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 gx(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||Aj.has(o)?o==="float"?s.cssFloat=f:s[o]=(""+f).trim():s[o]=f+"px"}function xx(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&&gx(s,k,g)}else for(var A in o)o.hasOwnProperty(A)&&gx(s,A,o[A])}function rh(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 Lj=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"]]),Dj=/^[\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 oc(s){return Dj.test(""+s)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":s}function Zr(){}var sh=null;function ih(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var ua=null,da=null;function yx(s){var o=ia(s);if(o&&(s=o.stateNode)){var f=s[at]||null;e:switch(s=o.stateNode,o.type){case"input":if(th(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="'+dr(""+o)+'"][type="radio"]'),o=0;o<f.length;o++){var g=f[o];if(g!==s&&g.form===s.form){var k=g[at]||null;if(!k)throw Error(r(90));th(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&&hx(g)}break e;case"textarea":mx(s,f.value,f.defaultValue);break e;case"select":o=f.value,o!=null&&la(s,!!f.multiple,o,!1)}}}var ah=!1;function bx(s,o,f){if(ah)return s(o,f);ah=!0;try{var g=s(o);return g}finally{if(ah=!1,(ua!==null||da!==null)&&(Kc(),ua&&(o=ua,s=da,da=ua=null,yx(o),s)))for(o=0;o<s.length;o++)yx(s[o])}}function vo(s,o){var f=s.stateNode;if(f===null)return null;var g=f[at]||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"),oh=!1;if(es)try{var _o={};Object.defineProperty(_o,"passive",{get:function(){oh=!0}}),window.addEventListener("test",_o,_o),window.removeEventListener("test",_o,_o)}catch{oh=!1}var Ls=null,lh=null,lc=null;function vx(){if(lc)return lc;var s,o=lh,f=o.length,g,k="value"in Ls?Ls.value:Ls.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 lc=k.slice(s,1<g?1-g:void 0)}function cc(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 uc(){return!0}function _x(){return!1}function Fn(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)?uc:_x,this.isPropagationStopped=_x,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=uc)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=uc)},persist:function(){},isPersistent:uc}),o}var bi={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(s){return s.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},dc=Fn(bi),So=m({},bi,{view:0,detail:0}),Rj=Fn(So),ch,uh,wo,hc=m({},So,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:hh,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!==wo&&(wo&&s.type==="mousemove"?(ch=s.screenX-wo.screenX,uh=s.screenY-wo.screenY):uh=ch=0,wo=s),ch)},movementY:function(s){return"movementY"in s?s.movementY:uh}}),Sx=Fn(hc),Oj=m({},hc,{dataTransfer:0}),Ij=Fn(Oj),Mj=m({},So,{relatedTarget:0}),dh=Fn(Mj),Pj=m({},bi,{animationName:0,elapsedTime:0,pseudoElement:0}),Bj=Fn(Pj),$j=m({},bi,{clipboardData:function(s){return"clipboardData"in s?s.clipboardData:window.clipboardData}}),zj=Fn($j),Hj=m({},bi,{data:0}),wx=Fn(Hj),Uj={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Fj={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"},Vj={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Gj(s){var o=this.nativeEvent;return o.getModifierState?o.getModifierState(s):(s=Vj[s])?!!o[s]:!1}function hh(){return Gj}var Wj=m({},So,{key:function(s){if(s.key){var o=Uj[s.key]||s.key;if(o!=="Unidentified")return o}return s.type==="keypress"?(s=cc(s),s===13?"Enter":String.fromCharCode(s)):s.type==="keydown"||s.type==="keyup"?Fj[s.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:hh,charCode:function(s){return s.type==="keypress"?cc(s):0},keyCode:function(s){return s.type==="keydown"||s.type==="keyup"?s.keyCode:0},which:function(s){return s.type==="keypress"?cc(s):s.type==="keydown"||s.type==="keyup"?s.keyCode:0}}),qj=Fn(Wj),Kj=m({},hc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Cx=Fn(Kj),Yj=m({},So,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:hh}),Xj=Fn(Yj),Qj=m({},bi,{propertyName:0,elapsedTime:0,pseudoElement:0}),Jj=Fn(Qj),Zj=m({},hc,{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}),e2=Fn(Zj),t2=m({},bi,{newState:0,oldState:0}),n2=Fn(t2),r2=[9,13,27,32],fh=es&&"CompositionEvent"in window,Co=null;es&&"documentMode"in document&&(Co=document.documentMode);var s2=es&&"TextEvent"in window&&!Co,kx=es&&(!fh||Co&&8<Co&&11>=Co),jx=" ",Ex=!1;function Nx(s,o){switch(s){case"keyup":return r2.indexOf(o.keyCode)!==-1;case"keydown":return o.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Tx(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var ha=!1;function i2(s,o){switch(s){case"compositionend":return Tx(o);case"keypress":return o.which!==32?null:(Ex=!0,jx);case"textInput":return s=o.data,s===jx&&Ex?null:s;default:return null}}function a2(s,o){if(ha)return s==="compositionend"||!fh&&Nx(s,o)?(s=vx(),lc=lh=Ls=null,ha=!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 kx&&o.locale!=="ko"?null:o.data;default:return null}}var o2={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 Ax(s){var o=s&&s.nodeName&&s.nodeName.toLowerCase();return o==="input"?!!o2[s.type]:o==="textarea"}function Lx(s,o,f,g){ua?da?da.push(g):da=[g]:ua=g,o=tu(o,"onChange"),0<o.length&&(f=new dc("onChange","change",null,f,g),s.push({event:f,listeners:o}))}var ko=null,jo=null;function l2(s){fv(s,0)}function fc(s){var o=bo(s);if(hx(o))return s}function Dx(s,o){if(s==="change")return o}var Rx=!1;if(es){var mh;if(es){var ph="oninput"in document;if(!ph){var Ox=document.createElement("div");Ox.setAttribute("oninput","return;"),ph=typeof Ox.oninput=="function"}mh=ph}else mh=!1;Rx=mh&&(!document.documentMode||9<document.documentMode)}function Ix(){ko&&(ko.detachEvent("onpropertychange",Mx),jo=ko=null)}function Mx(s){if(s.propertyName==="value"&&fc(jo)){var o=[];Lx(o,jo,s,ih(s)),bx(l2,o)}}function c2(s,o,f){s==="focusin"?(Ix(),ko=o,jo=f,ko.attachEvent("onpropertychange",Mx)):s==="focusout"&&Ix()}function u2(s){if(s==="selectionchange"||s==="keyup"||s==="keydown")return fc(jo)}function d2(s,o){if(s==="click")return fc(o)}function h2(s,o){if(s==="input"||s==="change")return fc(o)}function f2(s,o){return s===o&&(s!==0||1/s===1/o)||s!==s&&o!==o}var er=typeof Object.is=="function"?Object.is:f2;function Eo(s,o){if(er(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(!ot.call(o,k)||!er(s[k],o[k]))return!1}return!0}function Px(s){for(;s&&s.firstChild;)s=s.firstChild;return s}function Bx(s,o){var f=Px(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=Px(f)}}function $x(s,o){return s&&o?s===o?!0:s&&s.nodeType===3?!1:o&&o.nodeType===3?$x(s,o.parentNode):"contains"in s?s.contains(o):s.compareDocumentPosition?!!(s.compareDocumentPosition(o)&16):!1:!1}function zx(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var o=ac(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=ac(s.document)}return o}function gh(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 m2=es&&"documentMode"in document&&11>=document.documentMode,fa=null,xh=null,No=null,yh=!1;function Hx(s,o,f){var g=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;yh||fa==null||fa!==ac(g)||(g=fa,"selectionStart"in g&&gh(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}),No&&Eo(No,g)||(No=g,g=tu(xh,"onSelect"),0<g.length&&(o=new dc("onSelect","select",null,o,f),s.push({event:o,listeners:g}),o.target=fa)))}function vi(s,o){var f={};return f[s.toLowerCase()]=o.toLowerCase(),f["Webkit"+s]="webkit"+o,f["Moz"+s]="moz"+o,f}var ma={animationend:vi("Animation","AnimationEnd"),animationiteration:vi("Animation","AnimationIteration"),animationstart:vi("Animation","AnimationStart"),transitionrun:vi("Transition","TransitionRun"),transitionstart:vi("Transition","TransitionStart"),transitioncancel:vi("Transition","TransitionCancel"),transitionend:vi("Transition","TransitionEnd")},bh={},Ux={};es&&(Ux=document.createElement("div").style,"AnimationEvent"in window||(delete ma.animationend.animation,delete ma.animationiteration.animation,delete ma.animationstart.animation),"TransitionEvent"in window||delete ma.transitionend.transition);function _i(s){if(bh[s])return bh[s];if(!ma[s])return s;var o=ma[s],f;for(f in o)if(o.hasOwnProperty(f)&&f in Ux)return bh[s]=o[f];return s}var Fx=_i("animationend"),Vx=_i("animationiteration"),Gx=_i("animationstart"),p2=_i("transitionrun"),g2=_i("transitionstart"),x2=_i("transitioncancel"),Wx=_i("transitionend"),qx=new Map,vh="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(" ");vh.push("scrollEnd");function jr(s,o){qx.set(s,o),yi(o,[s])}var mc=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)},hr=[],pa=0,_h=0;function pc(){for(var s=pa,o=_h=pa=0;o<s;){var f=hr[o];hr[o++]=null;var g=hr[o];hr[o++]=null;var k=hr[o];hr[o++]=null;var A=hr[o];if(hr[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&&Kx(f,k,A)}}function gc(s,o,f,g){hr[pa++]=s,hr[pa++]=o,hr[pa++]=f,hr[pa++]=g,_h|=g,s.lanes|=g,s=s.alternate,s!==null&&(s.lanes|=g)}function Sh(s,o,f,g){return gc(s,o,f,g),xc(s)}function Si(s,o){return gc(s,null,null,o),xc(s)}function Kx(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-tt(f),s=A.hiddenUpdates,g=s[k],g===null?s[k]=[o]:g.push(o),o.lane=f|536870912),A):null}function xc(s){if(50<Xo)throw Xo=0,Df=null,Error(r(185));for(var o=s.return;o!==null;)s=o,o=s.return;return s.tag===3?s.stateNode:null}var ga={};function y2(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 tr(s,o,f,g){return new y2(s,o,f,g)}function wh(s){return s=s.prototype,!(!s||!s.isReactComponent)}function ts(s,o){var f=s.alternate;return f===null?(f=tr(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 Yx(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 yc(s,o,f,g,k,A){var F=0;if(g=s,typeof s=="function")wh(s)&&(F=1);else if(typeof s=="string")F=wE(s,f,ne.current)?26:s==="html"||s==="head"||s==="body"?27:5;else e:switch(s){case O:return s=tr(31,f,o,k),s.elementType=O,s.lanes=A,s;case C:return wi(f.children,k,A,o);case _:F=8,k|=24;break;case S:return s=tr(12,f,o,k|2),s.elementType=S,s.lanes=A,s;case N:return s=tr(13,f,o,k),s.elementType=N,s.lanes=A,s;case T:return s=tr(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 j: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=tr(F,f,o,k),o.elementType=s,o.type=g,o.lanes=A,o}function wi(s,o,f,g){return s=tr(7,s,g,o),s.lanes=f,s}function Ch(s,o,f){return s=tr(6,s,null,o),s.lanes=f,s}function Xx(s){var o=tr(18,null,null,0);return o.stateNode=s,o}function kh(s,o,f){return o=tr(4,s.children!==null?s.children:[],s.key,o),o.lanes=f,o.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},o}var Qx=new WeakMap;function fr(s,o){if(typeof s=="object"&&s!==null){var f=Qx.get(s);return f!==void 0?f:(o={value:s,source:o,stack:st(o)},Qx.set(s,o),o)}return{value:s,source:o,stack:st(o)}}var xa=[],ya=0,bc=null,To=0,mr=[],pr=0,Ds=null,Br=1,$r="";function ns(s,o){xa[ya++]=To,xa[ya++]=bc,bc=s,To=o}function Jx(s,o,f){mr[pr++]=Br,mr[pr++]=$r,mr[pr++]=Ds,Ds=s;var g=Br;s=$r;var k=32-tt(g)-1;g&=~(1<<k),f+=1;var A=32-tt(o)+k;if(30<A){var F=k-k%5;A=(g&(1<<F)-1).toString(32),g>>=F,k-=F,Br=1<<32-tt(o)+k|f<<k|g,$r=A+s}else Br=1<<A|f<<k|g,$r=s}function jh(s){s.return!==null&&(ns(s,1),Jx(s,1,0))}function Eh(s){for(;s===bc;)bc=xa[--ya],xa[ya]=null,To=xa[--ya],xa[ya]=null;for(;s===Ds;)Ds=mr[--pr],mr[pr]=null,$r=mr[--pr],mr[pr]=null,Br=mr[--pr],mr[pr]=null}function Zx(s,o){mr[pr++]=Br,mr[pr++]=$r,mr[pr++]=Ds,Br=o.id,$r=o.overflow,Ds=s}var Cn=null,Wt=null,kt=!1,Rs=null,gr=!1,Nh=Error(r(519));function Os(s){var o=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ao(fr(o,s)),Nh}function ey(s){var o=s.stateNode,f=s.type,g=s.memoizedProps;switch(o[Qe]=s,o[at]=g,f){case"dialog":bt("cancel",o),bt("close",o);break;case"iframe":case"object":case"embed":bt("load",o);break;case"video":case"audio":for(f=0;f<Jo.length;f++)bt(Jo[f],o);break;case"source":bt("error",o);break;case"img":case"image":case"link":bt("error",o),bt("load",o);break;case"details":bt("toggle",o);break;case"input":bt("invalid",o),fx(o,g.value,g.defaultValue,g.checked,g.defaultChecked,g.type,g.name,!0);break;case"select":bt("invalid",o);break;case"textarea":bt("invalid",o),px(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||xv(o.textContent,f)?(g.popover!=null&&(bt("beforetoggle",o),bt("toggle",o)),g.onScroll!=null&&bt("scroll",o),g.onScrollEnd!=null&&bt("scrollend",o),g.onClick!=null&&(o.onclick=Zr),o=!0):o=!1,o||Os(s,!0)}function ty(s){for(Cn=s.return;Cn;)switch(Cn.tag){case 5:case 31:case 13:gr=!1;return;case 27:case 3:gr=!0;return;default:Cn=Cn.return}}function ba(s){if(s!==Cn)return!1;if(!kt)return ty(s),kt=!0,!1;var o=s.tag,f;if((f=o!==3&&o!==27)&&((f=o===5)&&(f=s.type,f=!(f!=="form"&&f!=="button")||qf(s.type,s.memoizedProps)),f=!f),f&&Wt&&Os(s),ty(s),o===13){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Wt=jv(s)}else if(o===31){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(317));Wt=jv(s)}else o===27?(o=Wt,Ks(s.type)?(s=Jf,Jf=null,Wt=s):Wt=o):Wt=Cn?yr(s.stateNode.nextSibling):null;return!0}function Ci(){Wt=Cn=null,kt=!1}function Th(){var s=Rs;return s!==null&&(qn===null?qn=s:qn.push.apply(qn,s),Rs=null),s}function Ao(s){Rs===null?Rs=[s]:Rs.push(s)}var Ah=B(null),ki=null,rs=null;function Is(s,o,f){z(Ah,o._currentValue),o._currentValue=f}function ss(s){s._currentValue=Ah.current,q(Ah)}function Lh(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 Dh(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 le=0;le<o.length;le++)if(Y.context===o[le]){A.lanes|=f,Y=A.alternate,Y!==null&&(Y.lanes|=f),Lh(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),Lh(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 va(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;er(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(rl):s=[rl])}k=k.return}s!==null&&Dh(o,s,f,g),o.flags|=262144}function vc(s){for(s=s.firstContext;s!==null;){if(!er(s.context._currentValue,s.memoizedValue))return!0;s=s.next}return!1}function ji(s){ki=s,rs=null,s=s.dependencies,s!==null&&(s.firstContext=null)}function kn(s){return ny(ki,s)}function _c(s,o){return ki===null&&ji(s),ny(s,o)}function ny(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 b2=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()})}},v2=e.unstable_scheduleCallback,_2=e.unstable_NormalPriority,sn={$$typeof:b,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Rh(){return{controller:new b2,data:new Map,refCount:0}}function Lo(s){s.refCount--,s.refCount===0&&v2(_2,function(){s.controller.abort()})}var Do=null,Oh=0,_a=0,Sa=null;function S2(s,o){if(Do===null){var f=Do=[];Oh=0,_a=Bf(),Sa={status:"pending",value:void 0,then:function(g){f.push(g)}}}return Oh++,o.then(ry,ry),o}function ry(){if(--Oh===0&&Do!==null){Sa!==null&&(Sa.status="fulfilled");var s=Do;Do=null,_a=0,Sa=null;for(var o=0;o<s.length;o++)(0,s[o])()}}function w2(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 sy=V.S;V.S=function(s,o){Hb=Ie(),typeof o=="object"&&o!==null&&typeof o.then=="function"&&S2(s,o),sy!==null&&sy(s,o)};var Ei=B(null);function Ih(){var s=Ei.current;return s!==null?s:$t.pooledCache}function Sc(s,o){o===null?z(Ei,Ei.current):z(Ei,o.pool)}function iy(){var s=Ih();return s===null?null:{parent:sn._currentValue,pool:s}}var wa=Error(r(460)),Mh=Error(r(474)),wc=Error(r(542)),Cc={then:function(){}};function ay(s){return s=s.status,s==="fulfilled"||s==="rejected"}function oy(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,cy(s),s;default:if(typeof o.status=="string")o.then(Zr,Zr);else{if(s=$t,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,cy(s),s}throw Ti=o,wa}}function Ni(s){try{var o=s._init;return o(s._payload)}catch(f){throw f!==null&&typeof f=="object"&&typeof f.then=="function"?(Ti=f,wa):f}}var Ti=null;function ly(){if(Ti===null)throw Error(r(459));var s=Ti;return Ti=null,s}function cy(s){if(s===wa||s===wc)throw Error(r(483))}var Ca=null,Ro=0;function kc(s){var o=Ro;return Ro+=1,Ca===null&&(Ca=[]),oy(Ca,s,o)}function Oo(s,o){o=o.props.ref,s.ref=o!==void 0?o:null}function jc(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 uy(s){function o(de,ue){if(s){var pe=de.deletions;pe===null?(de.deletions=[ue],de.flags|=16):pe.push(ue)}}function f(de,ue){if(!s)return null;for(;ue!==null;)o(de,ue),ue=ue.sibling;return null}function g(de){for(var ue=new Map;de!==null;)de.key!==null?ue.set(de.key,de):ue.set(de.index,de),de=de.sibling;return ue}function k(de,ue){return de=ts(de,ue),de.index=0,de.sibling=null,de}function A(de,ue,pe){return de.index=pe,s?(pe=de.alternate,pe!==null?(pe=pe.index,pe<ue?(de.flags|=67108866,ue):pe):(de.flags|=67108866,ue)):(de.flags|=1048576,ue)}function F(de){return s&&de.alternate===null&&(de.flags|=67108866),de}function Y(de,ue,pe,Ne){return ue===null||ue.tag!==6?(ue=Ch(pe,de.mode,Ne),ue.return=de,ue):(ue=k(ue,pe),ue.return=de,ue)}function le(de,ue,pe,Ne){var et=pe.type;return et===C?ke(de,ue,pe.props.children,Ne,pe.key):ue!==null&&(ue.elementType===et||typeof et=="object"&&et!==null&&et.$$typeof===L&&Ni(et)===ue.type)?(ue=k(ue,pe.props),Oo(ue,pe),ue.return=de,ue):(ue=yc(pe.type,pe.key,pe.props,null,de.mode,Ne),Oo(ue,pe),ue.return=de,ue)}function ge(de,ue,pe,Ne){return ue===null||ue.tag!==4||ue.stateNode.containerInfo!==pe.containerInfo||ue.stateNode.implementation!==pe.implementation?(ue=kh(pe,de.mode,Ne),ue.return=de,ue):(ue=k(ue,pe.children||[]),ue.return=de,ue)}function ke(de,ue,pe,Ne,et){return ue===null||ue.tag!==7?(ue=wi(pe,de.mode,Ne,et),ue.return=de,ue):(ue=k(ue,pe),ue.return=de,ue)}function Ae(de,ue,pe){if(typeof ue=="string"&&ue!==""||typeof ue=="number"||typeof ue=="bigint")return ue=Ch(""+ue,de.mode,pe),ue.return=de,ue;if(typeof ue=="object"&&ue!==null){switch(ue.$$typeof){case y:return pe=yc(ue.type,ue.key,ue.props,null,de.mode,pe),Oo(pe,ue),pe.return=de,pe;case w:return ue=kh(ue,de.mode,pe),ue.return=de,ue;case L:return ue=Ni(ue),Ae(de,ue,pe)}if(G(ue)||U(ue))return ue=wi(ue,de.mode,pe,null),ue.return=de,ue;if(typeof ue.then=="function")return Ae(de,kc(ue),pe);if(ue.$$typeof===b)return Ae(de,_c(de,ue),pe);jc(de,ue)}return null}function xe(de,ue,pe,Ne){var et=ue!==null?ue.key:null;if(typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint")return et!==null?null:Y(de,ue,""+pe,Ne);if(typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case y:return pe.key===et?le(de,ue,pe,Ne):null;case w:return pe.key===et?ge(de,ue,pe,Ne):null;case L:return pe=Ni(pe),xe(de,ue,pe,Ne)}if(G(pe)||U(pe))return et!==null?null:ke(de,ue,pe,Ne,null);if(typeof pe.then=="function")return xe(de,ue,kc(pe),Ne);if(pe.$$typeof===b)return xe(de,ue,_c(de,pe),Ne);jc(de,pe)}return null}function be(de,ue,pe,Ne,et){if(typeof Ne=="string"&&Ne!==""||typeof Ne=="number"||typeof Ne=="bigint")return de=de.get(pe)||null,Y(ue,de,""+Ne,et);if(typeof Ne=="object"&&Ne!==null){switch(Ne.$$typeof){case y:return de=de.get(Ne.key===null?pe:Ne.key)||null,le(ue,de,Ne,et);case w:return de=de.get(Ne.key===null?pe:Ne.key)||null,ge(ue,de,Ne,et);case L:return Ne=Ni(Ne),be(de,ue,pe,Ne,et)}if(G(Ne)||U(Ne))return de=de.get(pe)||null,ke(ue,de,Ne,et,null);if(typeof Ne.then=="function")return be(de,ue,pe,kc(Ne),et);if(Ne.$$typeof===b)return be(de,ue,pe,_c(ue,Ne),et);jc(ue,Ne)}return null}function Ke(de,ue,pe,Ne){for(var et=null,Tt=null,Xe=ue,mt=ue=0,Ct=null;Xe!==null&&mt<pe.length;mt++){Xe.index>mt?(Ct=Xe,Xe=null):Ct=Xe.sibling;var At=xe(de,Xe,pe[mt],Ne);if(At===null){Xe===null&&(Xe=Ct);break}s&&Xe&&At.alternate===null&&o(de,Xe),ue=A(At,ue,mt),Tt===null?et=At:Tt.sibling=At,Tt=At,Xe=Ct}if(mt===pe.length)return f(de,Xe),kt&&ns(de,mt),et;if(Xe===null){for(;mt<pe.length;mt++)Xe=Ae(de,pe[mt],Ne),Xe!==null&&(ue=A(Xe,ue,mt),Tt===null?et=Xe:Tt.sibling=Xe,Tt=Xe);return kt&&ns(de,mt),et}for(Xe=g(Xe);mt<pe.length;mt++)Ct=be(Xe,de,mt,pe[mt],Ne),Ct!==null&&(s&&Ct.alternate!==null&&Xe.delete(Ct.key===null?mt:Ct.key),ue=A(Ct,ue,mt),Tt===null?et=Ct:Tt.sibling=Ct,Tt=Ct);return s&&Xe.forEach(function(Zs){return o(de,Zs)}),kt&&ns(de,mt),et}function it(de,ue,pe,Ne){if(pe==null)throw Error(r(151));for(var et=null,Tt=null,Xe=ue,mt=ue=0,Ct=null,At=pe.next();Xe!==null&&!At.done;mt++,At=pe.next()){Xe.index>mt?(Ct=Xe,Xe=null):Ct=Xe.sibling;var Zs=xe(de,Xe,At.value,Ne);if(Zs===null){Xe===null&&(Xe=Ct);break}s&&Xe&&Zs.alternate===null&&o(de,Xe),ue=A(Zs,ue,mt),Tt===null?et=Zs:Tt.sibling=Zs,Tt=Zs,Xe=Ct}if(At.done)return f(de,Xe),kt&&ns(de,mt),et;if(Xe===null){for(;!At.done;mt++,At=pe.next())At=Ae(de,At.value,Ne),At!==null&&(ue=A(At,ue,mt),Tt===null?et=At:Tt.sibling=At,Tt=At);return kt&&ns(de,mt),et}for(Xe=g(Xe);!At.done;mt++,At=pe.next())At=be(Xe,de,mt,At.value,Ne),At!==null&&(s&&At.alternate!==null&&Xe.delete(At.key===null?mt:At.key),ue=A(At,ue,mt),Tt===null?et=At:Tt.sibling=At,Tt=At);return s&&Xe.forEach(function(OE){return o(de,OE)}),kt&&ns(de,mt),et}function Pt(de,ue,pe,Ne){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 et=pe.key;ue!==null;){if(ue.key===et){if(et=pe.type,et===C){if(ue.tag===7){f(de,ue.sibling),Ne=k(ue,pe.props.children),Ne.return=de,de=Ne;break e}}else if(ue.elementType===et||typeof et=="object"&&et!==null&&et.$$typeof===L&&Ni(et)===ue.type){f(de,ue.sibling),Ne=k(ue,pe.props),Oo(Ne,pe),Ne.return=de,de=Ne;break e}f(de,ue);break}else o(de,ue);ue=ue.sibling}pe.type===C?(Ne=wi(pe.props.children,de.mode,Ne,pe.key),Ne.return=de,de=Ne):(Ne=yc(pe.type,pe.key,pe.props,null,de.mode,Ne),Oo(Ne,pe),Ne.return=de,de=Ne)}return F(de);case w:e:{for(et=pe.key;ue!==null;){if(ue.key===et)if(ue.tag===4&&ue.stateNode.containerInfo===pe.containerInfo&&ue.stateNode.implementation===pe.implementation){f(de,ue.sibling),Ne=k(ue,pe.children||[]),Ne.return=de,de=Ne;break e}else{f(de,ue);break}else o(de,ue);ue=ue.sibling}Ne=kh(pe,de.mode,Ne),Ne.return=de,de=Ne}return F(de);case L:return pe=Ni(pe),Pt(de,ue,pe,Ne)}if(G(pe))return Ke(de,ue,pe,Ne);if(U(pe)){if(et=U(pe),typeof et!="function")throw Error(r(150));return pe=et.call(pe),it(de,ue,pe,Ne)}if(typeof pe.then=="function")return Pt(de,ue,kc(pe),Ne);if(pe.$$typeof===b)return Pt(de,ue,_c(de,pe),Ne);jc(de,pe)}return typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint"?(pe=""+pe,ue!==null&&ue.tag===6?(f(de,ue.sibling),Ne=k(ue,pe),Ne.return=de,de=Ne):(f(de,ue),Ne=Ch(pe,de.mode,Ne),Ne.return=de,de=Ne),F(de)):f(de,ue)}return function(de,ue,pe,Ne){try{Ro=0;var et=Pt(de,ue,pe,Ne);return Ca=null,et}catch(Xe){if(Xe===wa||Xe===wc)throw Xe;var Tt=tr(29,Xe,null,de.mode);return Tt.lanes=Ne,Tt.return=de,Tt}finally{}}}var Ai=uy(!0),dy=uy(!1),Ms=!1;function Ph(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Bh(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 Ps(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function Bs(s,o,f){var g=s.updateQueue;if(g===null)return null;if(g=g.shared,(Lt&2)!==0){var k=g.pending;return k===null?o.next=o:(o.next=k.next,k.next=o),g.pending=o,o=xc(s),Kx(s,null,f),o}return gc(s,g,o,f),xc(s)}function Io(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,Ts(s,f)}}function $h(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 zh=!1;function Mo(){if(zh){var s=Sa;if(s!==null)throw s}}function Po(s,o,f,g){zh=!1;var k=s.updateQueue;Ms=!1;var A=k.firstBaseUpdate,F=k.lastBaseUpdate,Y=k.shared.pending;if(Y!==null){k.shared.pending=null;var le=Y,ge=le.next;le.next=null,F===null?A=ge:F.next=ge,F=le;var ke=s.alternate;ke!==null&&(ke=ke.updateQueue,Y=ke.lastBaseUpdate,Y!==F&&(Y===null?ke.firstBaseUpdate=ge:Y.next=ge,ke.lastBaseUpdate=le))}if(A!==null){var Ae=k.baseState;F=0,ke=ge=le=null,Y=A;do{var xe=Y.lane&-536870913,be=xe!==Y.lane;if(be?(wt&xe)===xe:(g&xe)===xe){xe!==0&&xe===_a&&(zh=!0),ke!==null&&(ke=ke.next={lane:0,tag:Y.tag,payload:Y.payload,callback:null,next:null});e:{var Ke=s,it=Y;xe=o;var Pt=f;switch(it.tag){case 1:if(Ke=it.payload,typeof Ke=="function"){Ae=Ke.call(Pt,Ae,xe);break e}Ae=Ke;break e;case 3:Ke.flags=Ke.flags&-65537|128;case 0:if(Ke=it.payload,xe=typeof Ke=="function"?Ke.call(Pt,Ae,xe):Ke,xe==null)break e;Ae=m({},Ae,xe);break e;case 2:Ms=!0}}xe=Y.callback,xe!==null&&(s.flags|=64,be&&(s.flags|=8192),be=k.callbacks,be===null?k.callbacks=[xe]:be.push(xe))}else be={lane:xe,tag:Y.tag,payload:Y.payload,callback:Y.callback,next:null},ke===null?(ge=ke=be,le=Ae):ke=ke.next=be,F|=xe;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&&(le=Ae),k.baseState=le,k.firstBaseUpdate=ge,k.lastBaseUpdate=ke,A===null&&(k.shared.lanes=0),Fs|=F,s.lanes=F,s.memoizedState=Ae}}function hy(s,o){if(typeof s!="function")throw Error(r(191,s));s.call(o)}function fy(s,o){var f=s.callbacks;if(f!==null)for(s.callbacks=null,s=0;s<f.length;s++)hy(f[s],o)}var ka=B(null),Ec=B(0);function my(s,o){s=fs,z(Ec,s),z(ka,o),fs=s|o.baseLanes}function Hh(){z(Ec,fs),z(ka,ka.current)}function Uh(){fs=Ec.current,q(ka),q(Ec)}var nr=B(null),xr=null;function $s(s){var o=s.alternate;z(en,en.current&1),z(nr,s),xr===null&&(o===null||ka.current!==null||o.memoizedState!==null)&&(xr=s)}function Fh(s){z(en,en.current),z(nr,s),xr===null&&(xr=s)}function py(s){s.tag===22?(z(en,en.current),z(nr,s),xr===null&&(xr=s)):zs()}function zs(){z(en,en.current),z(nr,nr.current)}function rr(s){q(nr),xr===s&&(xr=null),q(en)}var en=B(0);function Nc(s){for(var o=s;o!==null;){if(o.tag===13){var f=o.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||Xf(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,ft=null,It=null,an=null,Tc=!1,ja=!1,Li=!1,Ac=0,Bo=0,Ea=null,C2=0;function Qt(){throw Error(r(321))}function Vh(s,o){if(o===null)return!1;for(var f=0;f<o.length&&f<s.length;f++)if(!er(s[f],o[f]))return!1;return!0}function Gh(s,o,f,g,k,A){return is=A,ft=o,o.memoizedState=null,o.updateQueue=null,o.lanes=0,V.H=s===null||s.memoizedState===null?Jy:of,Li=!1,A=f(g,k),Li=!1,ja&&(A=xy(o,f,g,k)),gy(s),A}function gy(s){V.H=Ho;var o=It!==null&&It.next!==null;if(is=0,an=It=ft=null,Tc=!1,Bo=0,Ea=null,o)throw Error(r(300));s===null||on||(s=s.dependencies,s!==null&&vc(s)&&(on=!0))}function xy(s,o,f,g){ft=s;var k=0;do{if(ja&&(Ea=null),Bo=0,ja=!1,25<=k)throw Error(r(301));if(k+=1,an=It=null,s.updateQueue!=null){var A=s.updateQueue;A.lastEffect=null,A.events=null,A.stores=null,A.memoCache!=null&&(A.memoCache.index=0)}V.H=Zy,A=o(f,g)}while(ja);return A}function k2(){var s=V.H,o=s.useState()[0];return o=typeof o.then=="function"?$o(o):o,s=s.useState()[0],(It!==null?It.memoizedState:null)!==s&&(ft.flags|=1024),o}function Wh(){var s=Ac!==0;return Ac=0,s}function qh(s,o,f){o.updateQueue=s.updateQueue,o.flags&=-2053,s.lanes&=~f}function Kh(s){if(Tc){for(s=s.memoizedState;s!==null;){var o=s.queue;o!==null&&(o.pending=null),s=s.next}Tc=!1}is=0,an=It=ft=null,ja=!1,Bo=Ac=0,Ea=null}function Pn(){var s={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return an===null?ft.memoizedState=an=s:an=an.next=s,an}function tn(){if(It===null){var s=ft.alternate;s=s!==null?s.memoizedState:null}else s=It.next;var o=an===null?ft.memoizedState:an.next;if(o!==null)an=o,It=s;else{if(s===null)throw ft.alternate===null?Error(r(467)):Error(r(310));It=s,s={memoizedState:It.memoizedState,baseState:It.baseState,baseQueue:It.baseQueue,queue:It.queue,next:null},an===null?ft.memoizedState=an=s:an=an.next=s}return an}function Lc(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function $o(s){var o=Bo;return Bo+=1,Ea===null&&(Ea=[]),s=oy(Ea,s,o),o=ft,(an===null?o.memoizedState:an.next)===null&&(o=o.alternate,V.H=o===null||o.memoizedState===null?Jy:of),s}function Dc(s){if(s!==null&&typeof s=="object"){if(typeof s.then=="function")return $o(s);if(s.$$typeof===b)return kn(s)}throw Error(r(438,String(s)))}function Yh(s){var o=null,f=ft.updateQueue;if(f!==null&&(o=f.memoCache),o==null){var g=ft.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=Lc(),ft.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]=M;return o.index++,f}function as(s,o){return typeof o=="function"?o(s):o}function Rc(s){var o=tn();return Xh(o,It,s)}function Xh(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,le=null,ge=o,ke=!1;do{var Ae=ge.lane&-536870913;if(Ae!==ge.lane?(wt&Ae)===Ae:(is&Ae)===Ae){var xe=ge.revertLane;if(xe===0)le!==null&&(le=le.next={lane:0,revertLane:0,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null}),Ae===_a&&(ke=!0);else if((is&xe)===xe){ge=ge.next,xe===_a&&(ke=!0);continue}else Ae={lane:0,revertLane:ge.revertLane,gesture:null,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},le===null?(Y=le=Ae,F=A):le=le.next=Ae,ft.lanes|=xe,Fs|=xe;Ae=ge.action,Li&&f(A,Ae),A=ge.hasEagerState?ge.eagerState:f(A,Ae)}else xe={lane:Ae,revertLane:ge.revertLane,gesture:ge.gesture,action:ge.action,hasEagerState:ge.hasEagerState,eagerState:ge.eagerState,next:null},le===null?(Y=le=xe,F=A):le=le.next=xe,ft.lanes|=Ae,Fs|=Ae;ge=ge.next}while(ge!==null&&ge!==o);if(le===null?F=A:le.next=Y,!er(A,s.memoizedState)&&(on=!0,ke&&(f=Sa,f!==null)))throw f;s.memoizedState=A,s.baseState=F,s.baseQueue=le,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);er(A,o.memoizedState)||(on=!0),o.memoizedState=A,o.baseQueue===null&&(o.baseState=A),f.lastRenderedState=A}return[A,g]}function yy(s,o,f){var g=ft,k=tn(),A=kt;if(A){if(f===void 0)throw Error(r(407));f=f()}else f=o();var F=!er((It||k).memoizedState,f);if(F&&(k.memoizedState=f,on=!0),k=k.queue,ef(_y.bind(null,g,k,s),[s]),k.getSnapshot!==o||F||an!==null&&an.memoizedState.tag&1){if(g.flags|=2048,Na(9,{destroy:void 0},vy.bind(null,g,k,f,o),null),$t===null)throw Error(r(349));A||(is&127)!==0||by(g,o,f)}return f}function by(s,o,f){s.flags|=16384,s={getSnapshot:o,value:f},o=ft.updateQueue,o===null?(o=Lc(),ft.updateQueue=o,o.stores=[s]):(f=o.stores,f===null?o.stores=[s]:f.push(s))}function vy(s,o,f,g){o.value=f,o.getSnapshot=g,Sy(o)&&wy(s)}function _y(s,o,f){return f(function(){Sy(o)&&wy(s)})}function Sy(s){var o=s.getSnapshot;s=s.value;try{var f=o();return!er(s,f)}catch{return!0}}function wy(s){var o=Si(s,2);o!==null&&Kn(o,s,2)}function Jh(s){var o=Pn();if(typeof s=="function"){var f=s;if(s=f(),Li){Ze(!0);try{f()}finally{Ze(!1)}}}return o.memoizedState=o.baseState=s,o.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:as,lastRenderedState:s},o}function Cy(s,o,f,g){return s.baseState=f,Xh(s,It,typeof g=="function"?g:as)}function j2(s,o,f,g,k){if(Mc(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)}};V.T!==null?f(!0):A.isTransition=!1,g(A),f=o.pending,f===null?(A.next=o.pending=A,ky(o,A)):(A.next=f.next,o.pending=f.next=A)}}function ky(s,o){var f=o.action,g=o.payload,k=s.state;if(o.isTransition){var A=V.T,F={};V.T=F;try{var Y=f(k,g),le=V.S;le!==null&&le(F,Y),jy(s,o,Y)}catch(ge){Zh(s,o,ge)}finally{A!==null&&F.types!==null&&(A.types=F.types),V.T=A}}else try{A=f(k,g),jy(s,o,A)}catch(ge){Zh(s,o,ge)}}function jy(s,o,f){f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(function(g){Ey(s,o,g)},function(g){return Zh(s,o,g)}):Ey(s,o,f)}function Ey(s,o,f){o.status="fulfilled",o.value=f,Ny(o),s.state=f,o=s.pending,o!==null&&(f=o.next,f===o?s.pending=null:(f=f.next,o.next=f,ky(s,f)))}function Zh(s,o,f){var g=s.pending;if(s.pending=null,g!==null){g=g.next;do o.status="rejected",o.reason=f,Ny(o),o=o.next;while(o!==g)}s.action=null}function Ny(s){s=s.listeners;for(var o=0;o<s.length;o++)(0,s[o])()}function Ty(s,o){return o}function Ay(s,o){if(kt){var f=$t.formState;if(f!==null){e:{var g=ft;if(kt){if(Wt){t:{for(var k=Wt,A=gr;k.nodeType!==8;){if(!A){k=null;break t}if(k=yr(k.nextSibling),k===null){k=null;break t}}A=k.data,k=A==="F!"||A==="F"?k:null}if(k){Wt=yr(k.nextSibling),g=k.data==="F!";break e}}Os(g)}g=!1}g&&(o=f[0])}}return f=Pn(),f.memoizedState=f.baseState=o,g={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ty,lastRenderedState:o},f.queue=g,f=Yy.bind(null,ft,g),g.dispatch=f,g=Jh(!1),A=af.bind(null,ft,!1,g.queue),g=Pn(),k={state:o,dispatch:null,action:s,pending:null},g.queue=k,f=j2.bind(null,ft,k,A,f),k.dispatch=f,g.memoizedState=s,[o,f,!1]}function Ly(s){var o=tn();return Dy(o,It,s)}function Dy(s,o,f){if(o=Xh(s,o,Ty)[0],s=Rc(as)[0],typeof o=="object"&&o!==null&&typeof o.then=="function")try{var g=$o(o)}catch(F){throw F===wa?wc:F}else g=o;o=tn();var k=o.queue,A=k.dispatch;return f!==o.memoizedState&&(ft.flags|=2048,Na(9,{destroy:void 0},E2.bind(null,k,f),null)),[g,A,s]}function E2(s,o){s.action=o}function Ry(s){var o=tn(),f=It;if(f!==null)return Dy(o,f,s);tn(),o=o.memoizedState,f=tn();var g=f.queue.dispatch;return f.memoizedState=s,[o,g,!1]}function Na(s,o,f,g){return s={tag:s,create:f,deps:g,inst:o,next:null},o=ft.updateQueue,o===null&&(o=Lc(),ft.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 Oy(){return tn().memoizedState}function Oc(s,o,f,g){var k=Pn();ft.flags|=s,k.memoizedState=Na(1|o,{destroy:void 0},f,g===void 0?null:g)}function Ic(s,o,f,g){var k=tn();g=g===void 0?null:g;var A=k.memoizedState.inst;It!==null&&g!==null&&Vh(g,It.memoizedState.deps)?k.memoizedState=Na(o,A,f,g):(ft.flags|=s,k.memoizedState=Na(1|o,A,f,g))}function Iy(s,o){Oc(8390656,8,s,o)}function ef(s,o){Ic(2048,8,s,o)}function N2(s){ft.flags|=4;var o=ft.updateQueue;if(o===null)o=Lc(),ft.updateQueue=o,o.events=[s];else{var f=o.events;f===null?o.events=[s]:f.push(s)}}function My(s){var o=tn().memoizedState;return N2({ref:o,nextImpl:s}),function(){if((Lt&2)!==0)throw Error(r(440));return o.impl.apply(void 0,arguments)}}function Py(s,o){return Ic(4,2,s,o)}function By(s,o){return Ic(4,4,s,o)}function $y(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 zy(s,o,f){f=f!=null?f.concat([s]):null,Ic(4,4,$y.bind(null,o,s),f)}function tf(){}function Hy(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;return o!==null&&Vh(o,g[1])?g[0]:(f.memoizedState=[s,o],s)}function Uy(s,o){var f=tn();o=o===void 0?null:o;var g=f.memoizedState;if(o!==null&&Vh(o,g[1]))return g[0];if(g=s(),Li){Ze(!0);try{s()}finally{Ze(!1)}}return f.memoizedState=[g,o],g}function nf(s,o,f){return f===void 0||(is&1073741824)!==0&&(wt&261930)===0?s.memoizedState=o:(s.memoizedState=f,s=Fb(),ft.lanes|=s,Fs|=s,f)}function Fy(s,o,f,g){return er(f,o)?f:ka.current!==null?(s=nf(s,f,g),er(s,o)||(on=!0),s):(is&42)===0||(is&1073741824)!==0&&(wt&261930)===0?(on=!0,s.memoizedState=f):(s=Fb(),ft.lanes|=s,Fs|=s,o)}function Vy(s,o,f,g,k){var A=Z.p;Z.p=A!==0&&8>A?A:8;var F=V.T,Y={};V.T=Y,af(s,!1,o,f);try{var le=k(),ge=V.S;if(ge!==null&&ge(Y,le),le!==null&&typeof le=="object"&&typeof le.then=="function"){var ke=w2(le,g);zo(s,o,ke,ar(s))}else zo(s,o,g,ar(s))}catch(Ae){zo(s,o,{then:function(){},status:"rejected",reason:Ae},ar())}finally{Z.p=A,F!==null&&Y.types!==null&&(F.types=Y.types),V.T=F}}function T2(){}function rf(s,o,f,g){if(s.tag!==5)throw Error(r(476));var k=Gy(s).queue;Vy(s,k,o,X,f===null?T2:function(){return Wy(s),f(g)})}function Gy(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 Wy(s){var o=Gy(s);o.next===null&&(o=s.alternate.memoizedState),zo(s,o.next.queue,{},ar())}function sf(){return kn(rl)}function qy(){return tn().memoizedState}function Ky(){return tn().memoizedState}function A2(s){for(var o=s.return;o!==null;){switch(o.tag){case 24:case 3:var f=ar();s=Ps(f);var g=Bs(o,s,f);g!==null&&(Kn(g,o,f),Io(g,o,f)),o={cache:Rh()},s.payload=o;return}o=o.return}}function L2(s,o,f){var g=ar();f={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null},Mc(s)?Xy(o,f):(f=Sh(s,o,f,g),f!==null&&(Kn(f,s,g),Qy(f,o,g)))}function Yy(s,o,f){var g=ar();zo(s,o,f,g)}function zo(s,o,f,g){var k={lane:g,revertLane:0,gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null};if(Mc(s))Xy(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,er(Y,F))return gc(s,o,k,0),$t===null&&pc(),!1}catch{}finally{}if(f=Sh(s,o,k,g),f!==null)return Kn(f,s,g),Qy(f,o,g),!0}return!1}function af(s,o,f,g){if(g={lane:2,revertLane:Bf(),gesture:null,action:g,hasEagerState:!1,eagerState:null,next:null},Mc(s)){if(o)throw Error(r(479))}else o=Sh(s,f,g,2),o!==null&&Kn(o,s,2)}function Mc(s){var o=s.alternate;return s===ft||o!==null&&o===ft}function Xy(s,o){ja=Tc=!0;var f=s.pending;f===null?o.next=o:(o.next=f.next,f.next=o),s.pending=o}function Qy(s,o,f){if((f&4194048)!==0){var g=o.lanes;g&=s.pendingLanes,f|=g,o.lanes=f,Ts(s,f)}}var Ho={readContext:kn,use:Dc,useCallback:Qt,useContext:Qt,useEffect:Qt,useImperativeHandle:Qt,useLayoutEffect:Qt,useInsertionEffect:Qt,useMemo:Qt,useReducer:Qt,useRef:Qt,useState:Qt,useDebugValue:Qt,useDeferredValue:Qt,useTransition:Qt,useSyncExternalStore:Qt,useId:Qt,useHostTransitionStatus:Qt,useFormState:Qt,useActionState:Qt,useOptimistic:Qt,useMemoCache:Qt,useCacheRefresh:Qt};Ho.useEffectEvent=Qt;var Jy={readContext:kn,use:Dc,useCallback:function(s,o){return Pn().memoizedState=[s,o===void 0?null:o],s},useContext:kn,useEffect:Iy,useImperativeHandle:function(s,o,f){f=f!=null?f.concat([s]):null,Oc(4194308,4,$y.bind(null,o,s),f)},useLayoutEffect:function(s,o){return Oc(4194308,4,s,o)},useInsertionEffect:function(s,o){Oc(4,2,s,o)},useMemo:function(s,o){var f=Pn();o=o===void 0?null:o;var g=s();if(Li){Ze(!0);try{s()}finally{Ze(!1)}}return f.memoizedState=[g,o],g},useReducer:function(s,o,f){var g=Pn();if(f!==void 0){var k=f(o);if(Li){Ze(!0);try{f(o)}finally{Ze(!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=L2.bind(null,ft,s),[g.memoizedState,s]},useRef:function(s){var o=Pn();return s={current:s},o.memoizedState=s},useState:function(s){s=Jh(s);var o=s.queue,f=Yy.bind(null,ft,o);return o.dispatch=f,[s.memoizedState,f]},useDebugValue:tf,useDeferredValue:function(s,o){var f=Pn();return nf(f,s,o)},useTransition:function(){var s=Jh(!1);return s=Vy.bind(null,ft,s.queue,!0,!1),Pn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,o,f){var g=ft,k=Pn();if(kt){if(f===void 0)throw Error(r(407));f=f()}else{if(f=o(),$t===null)throw Error(r(349));(wt&127)!==0||by(g,o,f)}k.memoizedState=f;var A={value:f,getSnapshot:o};return k.queue=A,Iy(_y.bind(null,g,A,s),[s]),g.flags|=2048,Na(9,{destroy:void 0},vy.bind(null,g,A,f,o),null),f},useId:function(){var s=Pn(),o=$t.identifierPrefix;if(kt){var f=$r,g=Br;f=(g&~(1<<32-tt(g)-1)).toString(32)+f,o="_"+o+"R_"+f,f=Ac++,0<f&&(o+="H"+f.toString(32)),o+="_"}else f=C2++,o="_"+o+"r_"+f.toString(32)+"_";return s.memoizedState=o},useHostTransitionStatus:sf,useFormState:Ay,useActionState:Ay,useOptimistic:function(s){var o=Pn();o.memoizedState=o.baseState=s;var f={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return o.queue=f,o=af.bind(null,ft,!0,f),f.dispatch=o,[s,o]},useMemoCache:Yh,useCacheRefresh:function(){return Pn().memoizedState=A2.bind(null,ft)},useEffectEvent:function(s){var o=Pn(),f={impl:s};return o.memoizedState=f,function(){if((Lt&2)!==0)throw Error(r(440));return f.impl.apply(void 0,arguments)}}},of={readContext:kn,use:Dc,useCallback:Hy,useContext:kn,useEffect:ef,useImperativeHandle:zy,useInsertionEffect:Py,useLayoutEffect:By,useMemo:Uy,useReducer:Rc,useRef:Oy,useState:function(){return Rc(as)},useDebugValue:tf,useDeferredValue:function(s,o){var f=tn();return Fy(f,It.memoizedState,s,o)},useTransition:function(){var s=Rc(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:$o(s),o]},useSyncExternalStore:yy,useId:qy,useHostTransitionStatus:sf,useFormState:Ly,useActionState:Ly,useOptimistic:function(s,o){var f=tn();return Cy(f,It,s,o)},useMemoCache:Yh,useCacheRefresh:Ky};of.useEffectEvent=My;var Zy={readContext:kn,use:Dc,useCallback:Hy,useContext:kn,useEffect:ef,useImperativeHandle:zy,useInsertionEffect:Py,useLayoutEffect:By,useMemo:Uy,useReducer:Qh,useRef:Oy,useState:function(){return Qh(as)},useDebugValue:tf,useDeferredValue:function(s,o){var f=tn();return It===null?nf(f,s,o):Fy(f,It.memoizedState,s,o)},useTransition:function(){var s=Qh(as)[0],o=tn().memoizedState;return[typeof s=="boolean"?s:$o(s),o]},useSyncExternalStore:yy,useId:qy,useHostTransitionStatus:sf,useFormState:Ry,useActionState:Ry,useOptimistic:function(s,o){var f=tn();return It!==null?Cy(f,It,s,o):(f.baseState=s,[s,f.queue.dispatch])},useMemoCache:Yh,useCacheRefresh:Ky};Zy.useEffectEvent=My;function lf(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 cf={enqueueSetState:function(s,o,f){s=s._reactInternals;var g=ar(),k=Ps(g);k.payload=o,f!=null&&(k.callback=f),o=Bs(s,k,g),o!==null&&(Kn(o,s,g),Io(o,s,g))},enqueueReplaceState:function(s,o,f){s=s._reactInternals;var g=ar(),k=Ps(g);k.tag=1,k.payload=o,f!=null&&(k.callback=f),o=Bs(s,k,g),o!==null&&(Kn(o,s,g),Io(o,s,g))},enqueueForceUpdate:function(s,o){s=s._reactInternals;var f=ar(),g=Ps(f);g.tag=2,o!=null&&(g.callback=o),o=Bs(s,g,f),o!==null&&(Kn(o,s,f),Io(o,s,f))}};function eb(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?!Eo(f,g)||!Eo(k,A):!0}function tb(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&&cf.enqueueReplaceState(o,o.state,null)}function Di(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 nb(s){mc(s)}function rb(s){console.error(s)}function sb(s){mc(s)}function Pc(s,o){try{var f=s.onUncaughtError;f(o.value,{componentStack:o.stack})}catch(g){setTimeout(function(){throw g})}}function ib(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 uf(s,o,f){return f=Ps(f),f.tag=3,f.payload={element:null},f.callback=function(){Pc(s,o)},f}function ab(s){return s=Ps(s),s.tag=3,s}function ob(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(){ib(o,f,g)}}var F=f.stateNode;F!==null&&typeof F.componentDidCatch=="function"&&(s.callback=function(){ib(o,f,g),typeof k!="function"&&(Vs===null?Vs=new Set([this]):Vs.add(this));var Y=g.stack;this.componentDidCatch(g.value,{componentStack:Y!==null?Y:""})})}function D2(s,o,f,g,k){if(f.flags|=32768,g!==null&&typeof g=="object"&&typeof g.then=="function"){if(o=f.alternate,o!==null&&va(o,f,k,!0),f=nr.current,f!==null){switch(f.tag){case 31:case 13:return xr===null?Yc():f.alternate===null&&Jt===0&&(Jt=3),f.flags&=-257,f.flags|=65536,f.lanes=k,g===Cc?f.flags|=16384:(o=f.updateQueue,o===null?f.updateQueue=new Set([g]):o.add(g),If(s,g,k)),!1;case 22:return f.flags|=65536,g===Cc?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)),If(s,g,k)),!1}throw Error(r(435,f.tag))}return If(s,g,k),Yc(),!1}if(kt)return o=nr.current,o!==null?((o.flags&65536)===0&&(o.flags|=256),o.flags|=65536,o.lanes=k,g!==Nh&&(s=Error(r(422),{cause:g}),Ao(fr(s,f)))):(g!==Nh&&(o=Error(r(423),{cause:g}),Ao(fr(o,f))),s=s.current.alternate,s.flags|=65536,k&=-k,s.lanes|=k,g=fr(g,f),k=uf(s.stateNode,g,k),$h(s,k),Jt!==4&&(Jt=2)),!1;var A=Error(r(520),{cause:g});if(A=fr(A,f),Yo===null?Yo=[A]:Yo.push(A),Jt!==4&&(Jt=2),o===null)return!0;g=fr(g,f),f=o;do{switch(f.tag){case 3:return f.flags|=65536,s=k&-k,f.lanes|=s,s=uf(f.stateNode,g,s),$h(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"&&(Vs===null||!Vs.has(A))))return f.flags|=65536,k&=-k,f.lanes|=k,k=ab(k),ob(k,s,f,g),$h(f,k),!1}f=f.return}while(f!==null);return!1}var df=Error(r(461)),on=!1;function jn(s,o,f,g){o.child=s===null?dy(o,null,f,g):Ai(o,s.child,f,g)}function lb(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 ji(o),g=Gh(s,o,f,F,A,k),Y=Wh(),s!==null&&!on?(qh(s,o,k),os(s,o,k)):(kt&&Y&&jh(o),o.flags|=1,jn(s,o,g,k),o.child)}function cb(s,o,f,g,k){if(s===null){var A=f.type;return typeof A=="function"&&!wh(A)&&A.defaultProps===void 0&&f.compare===null?(o.tag=15,o.type=A,ub(s,o,A,g,k)):(s=yc(f.type,null,g,o,o.mode,k),s.ref=o.ref,s.return=o,o.child=s)}if(A=s.child,!bf(s,k)){var F=A.memoizedProps;if(f=f.compare,f=f!==null?f:Eo,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 ub(s,o,f,g,k){if(s!==null){var A=s.memoizedProps;if(Eo(A,g)&&s.ref===o.ref)if(on=!1,o.pendingProps=g=A,bf(s,k))(s.flags&131072)!==0&&(on=!0);else return o.lanes=s.lanes,os(s,o,k)}return hf(s,o,f,g,k)}function db(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 hb(s,o,A,f,g)}if((f&536870912)!==0)o.memoizedState={baseLanes:0,cachePool:null},s!==null&&Sc(o,A!==null?A.cachePool:null),A!==null?my(o,A):Hh(),py(o);else return g=o.lanes=536870912,hb(s,o,A!==null?A.baseLanes|f:f,f,g)}else A!==null?(Sc(o,A.cachePool),my(o,A),zs(),o.memoizedState=null):(s!==null&&Sc(o,null),Hh(),zs());return jn(s,o,k,f),o.child}function Uo(s,o){return s!==null&&s.tag===22||o.stateNode!==null||(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.sibling}function hb(s,o,f,g,k){var A=Ih();return A=A===null?null:{parent:sn._currentValue,pool:A},o.memoizedState={baseLanes:f,cachePool:A},s!==null&&Sc(o,null),Hh(),py(o),s!==null&&va(s,o,g,!0),o.childLanes=k,null}function Bc(s,o){return o=zc({mode:o.mode,children:o.children},s.mode),o.ref=s.ref,s.child=o,o.return=s,o}function fb(s,o,f){return Ai(o,s.child,null,f),s=Bc(o,o.pendingProps),s.flags|=2,rr(o),o.memoizedState=null,s}function R2(s,o,f){var g=o.pendingProps,k=(o.flags&128)!==0;if(o.flags&=-129,s===null){if(kt){if(g.mode==="hidden")return s=Bc(o,g),o.lanes=536870912,Uo(null,s);if(Fh(o),(s=Wt)?(s=kv(s,gr),s=s!==null&&s.data==="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:Ds!==null?{id:Br,overflow:$r}:null,retryLane:536870912,hydrationErrors:null},f=Xx(s),f.return=o,o.child=f,Cn=o,Wt=null)):s=null,s===null)throw Os(o);return o.lanes=536870912,null}return Bc(o,g)}var A=s.memoizedState;if(A!==null){var F=A.dehydrated;if(Fh(o),k)if(o.flags&256)o.flags&=-257,o=fb(s,o,f);else if(o.memoizedState!==null)o.child=s.child,o.flags|=128,o=null;else throw Error(r(558));else if(on||va(s,o,f,!1),k=(f&s.childLanes)!==0,on||k){if(g=$t,g!==null&&(F=As(g,f),F!==0&&F!==A.retryLane))throw A.retryLane=F,Si(s,F),Kn(g,s,F),df;Yc(),o=fb(s,o,f)}else s=A.treeContext,Wt=yr(F.nextSibling),Cn=o,kt=!0,Rs=null,gr=!1,s!==null&&Zx(o,s),o=Bc(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 $c(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 hf(s,o,f,g,k){return ji(o),f=Gh(s,o,f,g,void 0,k),g=Wh(),s!==null&&!on?(qh(s,o,k),os(s,o,k)):(kt&&g&&jh(o),o.flags|=1,jn(s,o,f,k),o.child)}function mb(s,o,f,g,k,A){return ji(o),o.updateQueue=null,f=xy(o,g,f,k),gy(s),g=Wh(),s!==null&&!on?(qh(s,o,A),os(s,o,A)):(kt&&g&&jh(o),o.flags|=1,jn(s,o,f,A),o.child)}function pb(s,o,f,g,k){if(ji(o),o.stateNode===null){var A=ga,F=f.contextType;typeof F=="object"&&F!==null&&(A=kn(F)),A=new f(g,A),o.memoizedState=A.state!==null&&A.state!==void 0?A.state:null,A.updater=cf,o.stateNode=A,A._reactInternals=o,A=o.stateNode,A.props=g,A.state=o.memoizedState,A.refs={},Ph(o),F=f.contextType,A.context=typeof F=="object"&&F!==null?kn(F):ga,A.state=o.memoizedState,F=f.getDerivedStateFromProps,typeof F=="function"&&(lf(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&&cf.enqueueReplaceState(A,A.state,null),Po(o,g,A,k),Mo(),A.state=o.memoizedState),typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!0}else if(s===null){A=o.stateNode;var Y=o.memoizedProps,le=Di(f,Y);A.props=le;var ge=A.context,ke=f.contextType;F=ga,typeof ke=="object"&&ke!==null&&(F=kn(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)&&tb(o,A,g,F),Ms=!1;var xe=o.memoizedState;A.state=xe,Po(o,g,A,k),Mo(),ge=o.memoizedState,Y||xe!==ge||Ms?(typeof Ae=="function"&&(lf(o,f,Ae,g),ge=o.memoizedState),(le=Ms||eb(o,f,le,g,xe,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=le):(typeof A.componentDidMount=="function"&&(o.flags|=4194308),g=!1)}else{A=o.stateNode,Bh(s,o),F=o.memoizedProps,ke=Di(f,F),A.props=ke,Ae=o.pendingProps,xe=A.context,ge=f.contextType,le=ga,typeof ge=="object"&&ge!==null&&(le=kn(ge)),Y=f.getDerivedStateFromProps,(ge=typeof Y=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(F!==Ae||xe!==le)&&tb(o,A,g,le),Ms=!1,xe=o.memoizedState,A.state=xe,Po(o,g,A,k),Mo();var be=o.memoizedState;F!==Ae||xe!==be||Ms||s!==null&&s.dependencies!==null&&vc(s.dependencies)?(typeof Y=="function"&&(lf(o,f,Y,g),be=o.memoizedState),(ke=Ms||eb(o,f,ke,g,xe,be,le)||s!==null&&s.dependencies!==null&&vc(s.dependencies))?(ge||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(g,be,le),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(g,be,le)),typeof A.componentDidUpdate=="function"&&(o.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(o.flags|=1024)):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=1024),o.memoizedProps=g,o.memoizedState=be),A.props=g,A.state=be,A.context=le,g=ke):(typeof A.componentDidUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===s.memoizedProps&&xe===s.memoizedState||(o.flags|=1024),g=!1)}return A=g,$c(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=Ai(o,s.child,null,k),o.child=Ai(o,null,f,k)):jn(s,o,f,k),o.memoizedState=A.state,s=o.child):s=os(s,o,k),s}function gb(s,o,f,g){return Ci(),o.flags|=256,jn(s,o,f,g),o.child}var ff={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function mf(s){return{baseLanes:s,cachePool:iy()}}function pf(s,o,f){return s=s!==null?s.childLanes&~f:0,o&&(s|=ir),s}function xb(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(kt){if(k?$s(o):zs(),(s=Wt)?(s=kv(s,gr),s=s!==null&&s.data!=="&"?s:null,s!==null&&(o.memoizedState={dehydrated:s,treeContext:Ds!==null?{id:Br,overflow:$r}:null,retryLane:536870912,hydrationErrors:null},f=Xx(s),f.return=o,o.child=f,Cn=o,Wt=null)):s=null,s===null)throw Os(o);return Qf(s)?o.lanes=32:o.lanes=536870912,null}var Y=g.children;return g=g.fallback,k?(zs(),k=o.mode,Y=zc({mode:"hidden",children:Y},k),g=wi(g,k,f,null),Y.return=o,g.return=o,Y.sibling=g,o.child=Y,g=o.child,g.memoizedState=mf(f),g.childLanes=pf(s,F,f),o.memoizedState=ff,Uo(null,g)):($s(o),gf(o,Y))}var le=s.memoizedState;if(le!==null&&(Y=le.dehydrated,Y!==null)){if(A)o.flags&256?($s(o),o.flags&=-257,o=xf(s,o,f)):o.memoizedState!==null?(zs(),o.child=s.child,o.flags|=128,o=null):(zs(),Y=g.fallback,k=o.mode,g=zc({mode:"visible",children:g.children},k),Y=wi(Y,k,f,null),Y.flags|=2,g.return=o,Y.return=o,g.sibling=Y,o.child=g,Ai(o,s.child,null,f),g=o.child,g.memoizedState=mf(f),g.childLanes=pf(s,F,f),o.memoizedState=ff,o=Uo(null,g));else if($s(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,Ao({value:g,source:null,stack:null}),o=xf(s,o,f)}else if(on||va(s,o,f,!1),F=(f&s.childLanes)!==0,on||F){if(F=$t,F!==null&&(g=As(F,f),g!==0&&g!==le.retryLane))throw le.retryLane=g,Si(s,g),Kn(F,s,g),df;Xf(Y)||Yc(),o=xf(s,o,f)}else Xf(Y)?(o.flags|=192,o.child=s.child,o=null):(s=le.treeContext,Wt=yr(Y.nextSibling),Cn=o,kt=!0,Rs=null,gr=!1,s!==null&&Zx(o,s),o=gf(o,g.children),o.flags|=4096);return o}return k?(zs(),Y=g.fallback,k=o.mode,le=s.child,ge=le.sibling,g=ts(le,{mode:"hidden",children:g.children}),g.subtreeFlags=le.subtreeFlags&65011712,ge!==null?Y=ts(ge,Y):(Y=wi(Y,k,f,null),Y.flags|=2),Y.return=o,g.return=o,g.sibling=Y,o.child=g,Uo(null,g),g=o.child,Y=s.child.memoizedState,Y===null?Y=mf(f):(k=Y.cachePool,k!==null?(le=sn._currentValue,k=k.parent!==le?{parent:le,pool:le}:k):k=iy(),Y={baseLanes:Y.baseLanes|f,cachePool:k}),g.memoizedState=Y,g.childLanes=pf(s,F,f),o.memoizedState=ff,Uo(s.child,g)):($s(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 gf(s,o){return o=zc({mode:"visible",children:o},s.mode),o.return=s,s.child=o}function zc(s,o){return s=tr(22,s,null,o),s.lanes=0,s}function xf(s,o,f){return Ai(o,s.child,null,f),s=gf(o,o.pendingProps.children),s.flags|=2,o.memoizedState=null,s}function yb(s,o,f){s.lanes|=o;var g=s.alternate;g!==null&&(g.lanes|=o),Lh(s.return,o,f)}function yf(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 bb(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),jn(s,o,g,f),g=kt?To:0,!Y&&s!==null&&(s.flags&128)!==0)e:for(s=o.child;s!==null;){if(s.tag===13)s.memoizedState!==null&&yb(s,f,o);else if(s.tag===19)yb(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&&Nc(s)===null&&(k=f),f=f.sibling;f=k,f===null?(k=o.child,o.child=null):(k=f.sibling,f.sibling=null),yf(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&&Nc(s)===null){o.child=k;break}s=k.sibling,k.sibling=f,f=k,k=s}yf(o,!0,f,null,A,g);break;case"together":yf(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),Fs|=o.lanes,(f&o.childLanes)===0)if(s!==null){if(va(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 bf(s,o){return(s.lanes&o)!==0?!0:(s=s.dependencies,!!(s!==null&&vc(s)))}function O2(s,o,f){switch(o.tag){case 3:P(o,o.stateNode.containerInfo),Is(o,sn,s.memoizedState.cache),Ci();break;case 27:case 5:ie(o);break;case 4:P(o,o.stateNode.containerInfo);break;case 10:Is(o,o.type,o.memoizedProps.value);break;case 31:if(o.memoizedState!==null)return o.flags|=128,Fh(o),null;break;case 13:var g=o.memoizedState;if(g!==null)return g.dehydrated!==null?($s(o),o.flags|=128,null):(f&o.child.childLanes)!==0?xb(s,o,f):($s(o),s=os(s,o,f),s!==null?s.sibling:null);$s(o);break;case 19:var k=(s.flags&128)!==0;if(g=(f&o.childLanes)!==0,g||(va(s,o,f,!1),g=(f&o.childLanes)!==0),k){if(g)return bb(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,db(s,o,f,o.pendingProps);case 24:Is(o,sn,s.memoizedState.cache)}return os(s,o,f)}function vb(s,o,f){if(s!==null)if(s.memoizedProps!==o.pendingProps)on=!0;else{if(!bf(s,f)&&(o.flags&128)===0)return on=!1,O2(s,o,f);on=(s.flags&131072)!==0}else on=!1,kt&&(o.flags&1048576)!==0&&Jx(o,To,o.index);switch(o.lanes=0,o.tag){case 16:e:{var g=o.pendingProps;if(s=Ni(o.elementType),o.type=s,typeof s=="function")wh(s)?(g=Di(s,g),o.tag=1,o=pb(null,o,s,g,f)):(o.tag=0,o=hf(null,o,s,g,f));else{if(s!=null){var k=s.$$typeof;if(k===j){o.tag=11,o=lb(null,o,s,g,f);break e}else if(k===D){o.tag=14,o=cb(null,o,s,g,f);break e}}throw o=H(s)||s,Error(r(306,o,""))}}return o;case 0:return hf(s,o,o.type,o.pendingProps,f);case 1:return g=o.type,k=Di(g,o.pendingProps),pb(s,o,g,k,f);case 3:e:{if(P(o,o.stateNode.containerInfo),s===null)throw Error(r(387));g=o.pendingProps;var A=o.memoizedState;k=A.element,Bh(s,o),Po(o,g,null,f);var F=o.memoizedState;if(g=F.cache,Is(o,sn,g),g!==A.cache&&Dh(o,[sn],f,!0),Mo(),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=gb(s,o,g,f);break e}else if(g!==k){k=fr(Error(r(424)),o),Ao(k),o=gb(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(Wt=yr(s.firstChild),Cn=o,kt=!0,Rs=null,gr=!0,f=dy(o,null,g,f),o.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling}else{if(Ci(),g===k){o=os(s,o,f);break e}jn(s,o,g,f)}o=o.child}return o;case 26:return $c(s,o),s===null?(f=Lv(o.type,null,o.pendingProps,null))?o.memoizedState=f:kt||(f=o.type,s=o.pendingProps,g=nu(Q.current).createElement(f),g[Qe]=o,g[at]=s,En(g,f,s),vn(g),o.stateNode=g):o.memoizedState=Lv(o.type,s.memoizedProps,o.pendingProps,s.memoizedState),null;case 27:return ie(o),s===null&&kt&&(g=o.stateNode=Nv(o.type,o.pendingProps,Q.current),Cn=o,gr=!0,k=Wt,Ks(o.type)?(Jf=k,Wt=yr(g.firstChild)):Wt=k),jn(s,o,o.pendingProps.children,f),$c(s,o),s===null&&(o.flags|=4194304),o.child;case 5:return s===null&&kt&&((k=g=Wt)&&(g=uE(g,o.type,o.pendingProps,gr),g!==null?(o.stateNode=g,Cn=o,Wt=yr(g.firstChild),gr=!1,k=!0):k=!1),k||Os(o)),ie(o),k=o.type,A=o.pendingProps,F=s!==null?s.memoizedProps:null,g=A.children,qf(k,A)?g=null:F!==null&&qf(k,F)&&(o.flags|=32),o.memoizedState!==null&&(k=Gh(s,o,k2,null,null,f),rl._currentValue=k),$c(s,o),jn(s,o,g,f),o.child;case 6:return s===null&&kt&&((s=f=Wt)&&(f=dE(f,o.pendingProps,gr),f!==null?(o.stateNode=f,Cn=o,Wt=null,s=!0):s=!1),s||Os(o)),null;case 13:return xb(s,o,f);case 4:return P(o,o.stateNode.containerInfo),g=o.pendingProps,s===null?o.child=Ai(o,null,g,f):jn(s,o,g,f),o.child;case 11:return lb(s,o,o.type,o.pendingProps,f);case 7:return jn(s,o,o.pendingProps,f),o.child;case 8:return jn(s,o,o.pendingProps.children,f),o.child;case 12:return jn(s,o,o.pendingProps.children,f),o.child;case 10:return g=o.pendingProps,Is(o,o.type,g.value),jn(s,o,g.children,f),o.child;case 9:return k=o.type._context,g=o.pendingProps.children,ji(o),k=kn(k),g=g(k),o.flags|=1,jn(s,o,g,f),o.child;case 14:return cb(s,o,o.type,o.pendingProps,f);case 15:return ub(s,o,o.type,o.pendingProps,f);case 19:return bb(s,o,f);case 31:return R2(s,o,f);case 22:return db(s,o,f,o.pendingProps);case 24:return ji(o),g=kn(sn),s===null?(k=Ih(),k===null&&(k=$t,A=Rh(),k.pooledCache=A,A.refCount++,A!==null&&(k.pooledCacheLanes|=f),k=A),o.memoizedState={parent:g,cache:k},Ph(o),Is(o,sn,k)):((s.lanes&f)!==0&&(Bh(s,o),Po(o,null,null,f),Mo()),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),Is(o,sn,g)):(g=A.cache,Is(o,sn,g),g!==k.cache&&Dh(o,[sn],f,!0))),jn(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 vf(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(qb())s.flags|=8192;else throw Ti=Cc,Mh}else s.flags&=-16777217}function _b(s,o){if(o.type!=="stylesheet"||(o.state.loading&4)!==0)s.flags&=-16777217;else if(s.flags|=16777216,!Mv(o))if(qb())s.flags|=8192;else throw Ti=Cc,Mh}function Hc(s,o){o!==null&&(s.flags|=4),s.flags&16384&&(o=s.tag!==22?bn():536870912,s.lanes|=o,Da|=o)}function Fo(s,o){if(!kt)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 qt(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 I2(s,o,f){var g=o.pendingProps;switch(Eh(o),o.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return qt(o),null;case 1:return qt(o),null;case 3:return f=o.stateNode,g=null,s!==null&&(g=s.memoizedState.cache),o.memoizedState.cache!==g&&(o.flags|=2048),ss(sn),J(),f.pendingContext&&(f.context=f.pendingContext,f.pendingContext=null),(s===null||s.child===null)&&(ba(o)?ls(o):s===null||s.memoizedState.isDehydrated&&(o.flags&256)===0||(o.flags|=1024,Th())),qt(o),null;case 26:var k=o.type,A=o.memoizedState;return s===null?(ls(o),A!==null?(qt(o),_b(o,A)):(qt(o),vf(o,k,null,g,f))):A?A!==s.memoizedState?(ls(o),qt(o),_b(o,A)):(qt(o),o.flags&=-16777217):(s=s.memoizedProps,s!==g&&ls(o),qt(o),vf(o,k,s,g,f)),null;case 27:if(he(o),f=Q.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 qt(o),null}s=ne.current,ba(o)?ey(o):(s=Nv(k,g,f),o.stateNode=s,ls(o))}return qt(o),null;case 5:if(he(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 qt(o),null}if(A=ne.current,ba(o))ey(o);else{var F=nu(Q.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[Qe]=o,A[at]=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(En(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 qt(o),vf(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=Q.current,ba(o)){if(s=o.stateNode,f=o.memoizedProps,g=null,k=Cn,k!==null)switch(k.tag){case 27:case 5:g=k.memoizedProps}s[Qe]=o,s=!!(s.nodeValue===f||g!==null&&g.suppressHydrationWarning===!0||xv(s.nodeValue,f)),s||Os(o,!0)}else s=nu(s).createTextNode(g),s[Qe]=o,o.stateNode=s}return qt(o),null;case 31:if(f=o.memoizedState,s===null||s.memoizedState!==null){if(g=ba(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[Qe]=o}else Ci(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;qt(o),s=!1}else f=Th(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=f),s=!0;if(!s)return o.flags&256?(rr(o),o):(rr(o),null);if((o.flags&128)!==0)throw Error(r(558))}return qt(o),null;case 13:if(g=o.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(k=ba(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[Qe]=o}else Ci(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;qt(o),k=!1}else k=Th(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=k),k=!0;if(!k)return o.flags&256?(rr(o),o):(rr(o),null)}return rr(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),Hc(o,o.updateQueue),qt(o),null);case 4:return J(),s===null&&Uf(o.stateNode.containerInfo),qt(o),null;case 10:return ss(o.type),qt(o),null;case 19:if(q(en),g=o.memoizedState,g===null)return qt(o),null;if(k=(o.flags&128)!==0,A=g.rendering,A===null)if(k)Fo(g,!1);else{if(Jt!==0||s!==null&&(s.flags&128)!==0)for(s=o.child;s!==null;){if(A=Nc(s),A!==null){for(o.flags|=128,Fo(g,!1),s=A.updateQueue,o.updateQueue=s,Hc(o,s),o.subtreeFlags=0,s=f,f=o.child;f!==null;)Yx(f,s),f=f.sibling;return z(en,en.current&1|2),kt&&ns(o,g.treeForkCount),o.child}s=s.sibling}g.tail!==null&&Ie()>Wc&&(o.flags|=128,k=!0,Fo(g,!1),o.lanes=4194304)}else{if(!k)if(s=Nc(A),s!==null){if(o.flags|=128,k=!0,s=s.updateQueue,o.updateQueue=s,Hc(o,s),Fo(g,!0),g.tail===null&&g.tailMode==="hidden"&&!A.alternate&&!kt)return qt(o),null}else 2*Ie()-g.renderingStartTime>Wc&&f!==536870912&&(o.flags|=128,k=!0,Fo(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=Ie(),s.sibling=null,f=en.current,z(en,k?f&1|2:f&1),kt&&ns(o,g.treeForkCount),s):(qt(o),null);case 22:case 23:return rr(o),Uh(),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&&(qt(o),o.subtreeFlags&6&&(o.flags|=8192)):qt(o),f=o.updateQueue,f!==null&&Hc(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(Ei),null;case 24:return f=null,s!==null&&(f=s.memoizedState.cache),o.memoizedState.cache!==f&&(o.flags|=2048),ss(sn),qt(o),null;case 25:return null;case 30:return null}throw Error(r(156,o.tag))}function M2(s,o){switch(Eh(o),o.tag){case 1:return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 3:return ss(sn),J(),s=o.flags,(s&65536)!==0&&(s&128)===0?(o.flags=s&-65537|128,o):null;case 26:case 27:case 5:return he(o),null;case 31:if(o.memoizedState!==null){if(rr(o),o.alternate===null)throw Error(r(340));Ci()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 13:if(rr(o),s=o.memoizedState,s!==null&&s.dehydrated!==null){if(o.alternate===null)throw Error(r(340));Ci()}return s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 19:return q(en),null;case 4:return J(),null;case 10:return ss(o.type),null;case 22:case 23:return rr(o),Uh(),s!==null&&q(Ei),s=o.flags,s&65536?(o.flags=s&-65537|128,o):null;case 24:return ss(sn),null;case 25:return null;default:return null}}function Sb(s,o){switch(Eh(o),o.tag){case 3:ss(sn),J();break;case 26:case 27:case 5:he(o);break;case 4:J();break;case 31:o.memoizedState!==null&&rr(o);break;case 13:rr(o);break;case 19:q(en);break;case 10:ss(o.type);break;case 22:case 23:rr(o),Uh(),s!==null&&q(Ei);break;case 24:ss(sn)}}function Vo(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){Ot(o,o.return,Y)}}function Hs(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 le=f,ge=Y;try{ge()}catch(ke){Ot(k,le,ke)}}}g=g.next}while(g!==A)}}catch(ke){Ot(o,o.return,ke)}}function wb(s){var o=s.updateQueue;if(o!==null){var f=s.stateNode;try{fy(o,f)}catch(g){Ot(s,s.return,g)}}}function Cb(s,o,f){f.props=Di(s.type,s.memoizedProps),f.state=s.memoizedState;try{f.componentWillUnmount()}catch(g){Ot(s,o,g)}}function Go(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){Ot(s,o,k)}}function zr(s,o){var f=s.ref,g=s.refCleanup;if(f!==null)if(typeof g=="function")try{g()}catch(k){Ot(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){Ot(s,o,k)}else f.current=null}function kb(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){Ot(s,s.return,k)}}function _f(s,o,f){try{var g=s.stateNode;sE(g,s.type,f,o),g[at]=o}catch(k){Ot(s,s.return,k)}}function jb(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&Ks(s.type)||s.tag===4}function Sf(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||jb(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&&Ks(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 wf(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&&Ks(s.type)&&(f=s.stateNode,o=null),s=s.child,s!==null))for(wf(s,o,f),s=s.sibling;s!==null;)wf(s,o,f),s=s.sibling}function Uc(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&&Ks(s.type)&&(f=s.stateNode),s=s.child,s!==null))for(Uc(s,o,f),s=s.sibling;s!==null;)Uc(s,o,f),s=s.sibling}function Eb(s){var o=s.stateNode,f=s.memoizedProps;try{for(var g=s.type,k=o.attributes;k.length;)o.removeAttributeNode(k[0]);En(o,g,f),o[Qe]=s,o[at]=f}catch(A){Ot(s,s.return,A)}}var cs=!1,ln=!1,Cf=!1,Nb=typeof WeakSet=="function"?WeakSet:Set,_n=null;function P2(s,o){if(s=s.containerInfo,Gf=cu,s=zx(s),gh(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,le=-1,ge=0,ke=0,Ae=s,xe=null;t:for(;;){for(var be;Ae!==f||k!==0&&Ae.nodeType!==3||(Y=F+k),Ae!==A||g!==0&&Ae.nodeType!==3||(le=F+g),Ae.nodeType===3&&(F+=Ae.nodeValue.length),(be=Ae.firstChild)!==null;)xe=Ae,Ae=be;for(;;){if(Ae===s)break t;if(xe===f&&++ge===k&&(Y=F),xe===A&&++ke===g&&(le=F),(be=Ae.nextSibling)!==null)break;Ae=xe,xe=Ae.parentNode}Ae=be}f=Y===-1||le===-1?null:{start:Y,end:le}}else f=null}f=f||{start:0,end:0}}else f=null;for(Wf={focusedElem:s,selectionRange:f},cu=!1,_n=o;_n!==null;)if(o=_n,s=o.child,(o.subtreeFlags&1028)!==0&&s!==null)s.return=o,_n=s;else for(;_n!==null;){switch(o=_n,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 Ke=Di(f.type,k);s=g.getSnapshotBeforeUpdate(Ke,A),g.__reactInternalSnapshotBeforeUpdate=s}catch(it){Ot(f,f.return,it)}}break;case 3:if((s&1024)!==0){if(s=o.stateNode.containerInfo,f=s.nodeType,f===9)Yf(s);else if(f===1)switch(s.nodeName){case"HEAD":case"HTML":case"BODY":Yf(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,_n=s;break}_n=o.return}}function Tb(s,o,f){var g=f.flags;switch(f.tag){case 0:case 11:case 15:ds(s,f),g&4&&Vo(5,f);break;case 1:if(ds(s,f),g&4)if(s=f.stateNode,o===null)try{s.componentDidMount()}catch(F){Ot(f,f.return,F)}else{var k=Di(f.type,o.memoizedProps);o=o.memoizedState;try{s.componentDidUpdate(k,o,s.__reactInternalSnapshotBeforeUpdate)}catch(F){Ot(f,f.return,F)}}g&64&&wb(f),g&512&&Go(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{fy(s,o)}catch(F){Ot(f,f.return,F)}}break;case 27:o===null&&g&4&&Eb(f);case 26:case 5:ds(s,f),o===null&&g&4&&kb(f),g&512&&Go(f,f.return);break;case 12:ds(s,f);break;case 31:ds(s,f),g&4&&Db(s,f);break;case 13:ds(s,f),g&4&&Rb(s,f),g&64&&(s=f.memoizedState,s!==null&&(s=s.dehydrated,s!==null&&(f=W2.bind(null,f),hE(s,f))));break;case 22:if(g=f.memoizedState!==null||cs,!g){o=o!==null&&o.memoizedState!==null||ln,k=cs;var A=ln;cs=g,(ln=o)&&!A?hs(s,f,(f.subtreeFlags&8772)!==0):ds(s,f),cs=k,ln=A}break;case 30:break;default:ds(s,f)}}function Ab(s){var o=s.alternate;o!==null&&(s.alternate=null,Ab(o)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(o=s.stateNode,o!==null&&Zd(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 Kt=null,Vn=!1;function us(s,o,f){for(f=f.child;f!==null;)Lb(s,o,f),f=f.sibling}function Lb(s,o,f){if(Je&&typeof Je.onCommitFiberUnmount=="function")try{Je.onCommitFiberUnmount(ct,f)}catch{}switch(f.tag){case 26:ln||zr(f,o),us(s,o,f),f.memoizedState?f.memoizedState.count--:f.stateNode&&(f=f.stateNode,f.parentNode.removeChild(f));break;case 27:ln||zr(f,o);var g=Kt,k=Vn;Ks(f.type)&&(Kt=f.stateNode,Vn=!1),us(s,o,f),el(f.stateNode),Kt=g,Vn=k;break;case 5:ln||zr(f,o);case 6:if(g=Kt,k=Vn,Kt=null,us(s,o,f),Kt=g,Vn=k,Kt!==null)if(Vn)try{(Kt.nodeType===9?Kt.body:Kt.nodeName==="HTML"?Kt.ownerDocument.body:Kt).removeChild(f.stateNode)}catch(A){Ot(f,o,A)}else try{Kt.removeChild(f.stateNode)}catch(A){Ot(f,o,A)}break;case 18:Kt!==null&&(Vn?(s=Kt,wv(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,f.stateNode),za(s)):wv(Kt,f.stateNode));break;case 4:g=Kt,k=Vn,Kt=f.stateNode.containerInfo,Vn=!0,us(s,o,f),Kt=g,Vn=k;break;case 0:case 11:case 14:case 15:Hs(2,f,o),ln||Hs(4,f,o),us(s,o,f);break;case 1:ln||(zr(f,o),g=f.stateNode,typeof g.componentWillUnmount=="function"&&Cb(f,o,g)),us(s,o,f);break;case 21:us(s,o,f);break;case 22:ln=(g=ln)||f.memoizedState!==null,us(s,o,f),ln=g;break;default:us(s,o,f)}}function Db(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null))){s=s.dehydrated;try{za(s)}catch(f){Ot(o,o.return,f)}}}function Rb(s,o){if(o.memoizedState===null&&(s=o.alternate,s!==null&&(s=s.memoizedState,s!==null&&(s=s.dehydrated,s!==null))))try{za(s)}catch(f){Ot(o,o.return,f)}}function B2(s){switch(s.tag){case 31:case 13:case 19:var o=s.stateNode;return o===null&&(o=s.stateNode=new Nb),o;case 22:return s=s.stateNode,o=s._retryCache,o===null&&(o=s._retryCache=new Nb),o;default:throw Error(r(435,s.tag))}}function Fc(s,o){var f=B2(s);o.forEach(function(g){if(!f.has(g)){f.add(g);var k=q2.bind(null,s,g);g.then(k,k)}})}function Gn(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(Ks(Y.type)){Kt=Y.stateNode,Vn=!1;break e}break;case 5:Kt=Y.stateNode,Vn=!1;break e;case 3:case 4:Kt=Y.stateNode.containerInfo,Vn=!0;break e}Y=Y.return}if(Kt===null)throw Error(r(160));Lb(A,F,k),Kt=null,Vn=!1,A=k.alternate,A!==null&&(A.return=null),k.return=null}if(o.subtreeFlags&13886)for(o=o.child;o!==null;)Ob(o,s),o=o.sibling}var Er=null;function Ob(s,o){var f=s.alternate,g=s.flags;switch(s.tag){case 0:case 11:case 14:case 15:Gn(o,s),Wn(s),g&4&&(Hs(3,s,s.return),Vo(3,s),Hs(5,s,s.return));break;case 1:Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(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=Er;if(Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(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[yo]||A[Qe]||A.namespaceURI==="http://www.w3.org/2000/svg"||A.hasAttribute("itemprop"))&&(A=k.createElement(g),k.head.insertBefore(A,k.querySelector("head > title"))),En(A,g,f),A[Qe]=s,vn(A),g=A;break e;case"link":var F=Ov("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),En(A,g,f),k.head.appendChild(A);break;case"meta":if(F=Ov("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),En(A,g,f),k.head.appendChild(A);break;default:throw Error(r(468,g))}A[Qe]=s,vn(A),g=A}s.stateNode=g}else Iv(k,s.type,s.stateNode);else s.stateNode=Rv(k,g,s.memoizedProps);else A!==g?(A===null?f.stateNode!==null&&(f=f.stateNode,f.parentNode.removeChild(f)):A.count--,g===null?Iv(k,s.type,s.stateNode):Rv(k,g,s.memoizedProps)):g===null&&s.stateNode!==null&&_f(s,s.memoizedProps,f.memoizedProps)}break;case 27:Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(f,f.return)),f!==null&&g&4&&_f(s,s.memoizedProps,f.memoizedProps);break;case 5:if(Gn(o,s),Wn(s),g&512&&(ln||f===null||zr(f,f.return)),s.flags&32){k=s.stateNode;try{ca(k,"")}catch(Ke){Ot(s,s.return,Ke)}}g&4&&s.stateNode!=null&&(k=s.memoizedProps,_f(s,k,f!==null?f.memoizedProps:k)),g&1024&&(Cf=!0);break;case 6:if(Gn(o,s),Wn(s),g&4){if(s.stateNode===null)throw Error(r(162));g=s.memoizedProps,f=s.stateNode;try{f.nodeValue=g}catch(Ke){Ot(s,s.return,Ke)}}break;case 3:if(iu=null,k=Er,Er=ru(o.containerInfo),Gn(o,s),Er=k,Wn(s),g&4&&f!==null&&f.memoizedState.isDehydrated)try{za(o.containerInfo)}catch(Ke){Ot(s,s.return,Ke)}Cf&&(Cf=!1,Ib(s));break;case 4:g=Er,Er=ru(s.stateNode.containerInfo),Gn(o,s),Wn(s),Er=g;break;case 12:Gn(o,s),Wn(s);break;case 31:Gn(o,s),Wn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,Fc(s,g)));break;case 13:Gn(o,s),Wn(s),s.child.flags&8192&&s.memoizedState!==null!=(f!==null&&f.memoizedState!==null)&&(Gc=Ie()),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,Fc(s,g)));break;case 22:k=s.memoizedState!==null;var le=f!==null&&f.memoizedState!==null,ge=cs,ke=ln;if(cs=ge||k,ln=ke||le,Gn(o,s),ln=ke,cs=ge,Wn(s),g&8192)e:for(o=s.stateNode,o._visibility=k?o._visibility&-2:o._visibility|1,k&&(f===null||le||cs||ln||Ri(s)),f=null,o=s;;){if(o.tag===5||o.tag===26){if(f===null){le=f=o;try{if(A=le.stateNode,k)F=A.style,typeof F.setProperty=="function"?F.setProperty("display","none","important"):F.display="none";else{Y=le.stateNode;var Ae=le.memoizedProps.style,xe=Ae!=null&&Ae.hasOwnProperty("display")?Ae.display:null;Y.style.display=xe==null||typeof xe=="boolean"?"":(""+xe).trim()}}catch(Ke){Ot(le,le.return,Ke)}}}else if(o.tag===6){if(f===null){le=o;try{le.stateNode.nodeValue=k?"":le.memoizedProps}catch(Ke){Ot(le,le.return,Ke)}}}else if(o.tag===18){if(f===null){le=o;try{var be=le.stateNode;k?Cv(be,!0):Cv(le.stateNode,!1)}catch(Ke){Ot(le,le.return,Ke)}}}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,Fc(s,f))));break;case 19:Gn(o,s),Wn(s),g&4&&(g=s.updateQueue,g!==null&&(s.updateQueue=null,Fc(s,g)));break;case 30:break;case 21:break;default:Gn(o,s),Wn(s)}}function Wn(s){var o=s.flags;if(o&2){try{for(var f,g=s.return;g!==null;){if(jb(g)){f=g;break}g=g.return}if(f==null)throw Error(r(160));switch(f.tag){case 27:var k=f.stateNode,A=Sf(s);Uc(s,A,k);break;case 5:var F=f.stateNode;f.flags&32&&(ca(F,""),f.flags&=-33);var Y=Sf(s);Uc(s,Y,F);break;case 3:case 4:var le=f.stateNode.containerInfo,ge=Sf(s);wf(s,ge,le);break;default:throw Error(r(161))}}catch(ke){Ot(s,s.return,ke)}s.flags&=-3}o&4096&&(s.flags&=-4097)}function Ib(s){if(s.subtreeFlags&1024)for(s=s.child;s!==null;){var o=s;Ib(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;)Tb(s,o.alternate,o),o=o.sibling}function Ri(s){for(s=s.child;s!==null;){var o=s;switch(o.tag){case 0:case 11:case 14:case 15:Hs(4,o,o.return),Ri(o);break;case 1:zr(o,o.return);var f=o.stateNode;typeof f.componentWillUnmount=="function"&&Cb(o,o.return,f),Ri(o);break;case 27:el(o.stateNode);case 26:case 5:zr(o,o.return),Ri(o);break;case 22:o.memoizedState===null&&Ri(o);break;case 30:Ri(o);break;default:Ri(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),Vo(4,A);break;case 1:if(hs(k,A,f),g=A,k=g.stateNode,typeof k.componentDidMount=="function")try{k.componentDidMount()}catch(ge){Ot(g,g.return,ge)}if(g=A,k=g.updateQueue,k!==null){var Y=g.stateNode;try{var le=k.shared.hiddenCallbacks;if(le!==null)for(k.shared.hiddenCallbacks=null,k=0;k<le.length;k++)hy(le[k],Y)}catch(ge){Ot(g,g.return,ge)}}f&&F&64&&wb(A),Go(A,A.return);break;case 27:Eb(A);case 26:case 5:hs(k,A,f),f&&g===null&&F&4&&kb(A),Go(A,A.return);break;case 12:hs(k,A,f);break;case 31:hs(k,A,f),f&&F&4&&Db(k,A);break;case 13:hs(k,A,f),f&&F&4&&Rb(k,A);break;case 22:A.memoizedState===null&&hs(k,A,f),Go(A,A.return);break;case 30:break;default:hs(k,A,f)}o=o.sibling}}function kf(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&&Lo(f))}function jf(s,o){s=null,o.alternate!==null&&(s=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==s&&(o.refCount++,s!=null&&Lo(s))}function Nr(s,o,f,g){if(o.subtreeFlags&10256)for(o=o.child;o!==null;)Mb(s,o,f,g),o=o.sibling}function Mb(s,o,f,g){var k=o.flags;switch(o.tag){case 0:case 11:case 15:Nr(s,o,f,g),k&2048&&Vo(9,o);break;case 1:Nr(s,o,f,g);break;case 3:Nr(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&&Lo(s)));break;case 12:if(k&2048){Nr(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(le){Ot(o,o.return,le)}}else Nr(s,o,f,g);break;case 31:Nr(s,o,f,g);break;case 13:Nr(s,o,f,g);break;case 23:break;case 22:A=o.stateNode,F=o.alternate,o.memoizedState!==null?A._visibility&2?Nr(s,o,f,g):Wo(s,o):A._visibility&2?Nr(s,o,f,g):(A._visibility|=2,Ta(s,o,f,g,(o.subtreeFlags&10256)!==0||!1)),k&2048&&kf(F,o);break;case 24:Nr(s,o,f,g),k&2048&&jf(o.alternate,o);break;default:Nr(s,o,f,g)}}function Ta(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,le=g,ge=F.flags;switch(F.tag){case 0:case 11:case 15:Ta(A,F,Y,le,k),Vo(8,F);break;case 23:break;case 22:var ke=F.stateNode;F.memoizedState!==null?ke._visibility&2?Ta(A,F,Y,le,k):Wo(A,F):(ke._visibility|=2,Ta(A,F,Y,le,k)),k&&ge&2048&&kf(F.alternate,F);break;case 24:Ta(A,F,Y,le,k),k&&ge&2048&&jf(F.alternate,F);break;default:Ta(A,F,Y,le,k)}o=o.sibling}}function Wo(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:Wo(f,g),k&2048&&kf(g.alternate,g);break;case 24:Wo(f,g),k&2048&&jf(g.alternate,g);break;default:Wo(f,g)}o=o.sibling}}var qo=8192;function Aa(s,o,f){if(s.subtreeFlags&qo)for(s=s.child;s!==null;)Pb(s,o,f),s=s.sibling}function Pb(s,o,f){switch(s.tag){case 26:Aa(s,o,f),s.flags&qo&&s.memoizedState!==null&&CE(f,Er,s.memoizedState,s.memoizedProps);break;case 5:Aa(s,o,f);break;case 3:case 4:var g=Er;Er=ru(s.stateNode.containerInfo),Aa(s,o,f),Er=g;break;case 22:s.memoizedState===null&&(g=s.alternate,g!==null&&g.memoizedState!==null?(g=qo,qo=16777216,Aa(s,o,f),qo=g):Aa(s,o,f));break;default:Aa(s,o,f)}}function Bb(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 Ko(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];_n=g,zb(g,s)}Bb(s)}if(s.subtreeFlags&10256)for(s=s.child;s!==null;)$b(s),s=s.sibling}function $b(s){switch(s.tag){case 0:case 11:case 15:Ko(s),s.flags&2048&&Hs(9,s,s.return);break;case 3:Ko(s);break;case 12:Ko(s);break;case 22:var o=s.stateNode;s.memoizedState!==null&&o._visibility&2&&(s.return===null||s.return.tag!==13)?(o._visibility&=-3,Vc(s)):Ko(s);break;default:Ko(s)}}function Vc(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];_n=g,zb(g,s)}Bb(s)}for(s=s.child;s!==null;){switch(o=s,o.tag){case 0:case 11:case 15:Hs(8,o,o.return),Vc(o);break;case 22:f=o.stateNode,f._visibility&2&&(f._visibility&=-3,Vc(o));break;default:Vc(o)}s=s.sibling}}function zb(s,o){for(;_n!==null;){var f=_n;switch(f.tag){case 0:case 11:case 15:Hs(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:Lo(f.memoizedState.cache)}if(g=f.child,g!==null)g.return=f,_n=g;else e:for(f=s;_n!==null;){g=_n;var k=g.sibling,A=g.return;if(Ab(g),g===f){_n=null;break e}if(k!==null){k.return=A,_n=k;break e}_n=A}}}var $2={getCacheForType:function(s){var o=kn(sn),f=o.data.get(s);return f===void 0&&(f=s(),o.data.set(s,f)),f},cacheSignal:function(){return kn(sn).controller.signal}},z2=typeof WeakMap=="function"?WeakMap:Map,Lt=0,$t=null,yt=null,wt=0,Rt=0,sr=null,Us=!1,La=!1,Ef=!1,fs=0,Jt=0,Fs=0,Oi=0,Nf=0,ir=0,Da=0,Yo=null,qn=null,Tf=!1,Gc=0,Hb=0,Wc=1/0,qc=null,Vs=null,pn=0,Gs=null,Ra=null,ms=0,Af=0,Lf=null,Ub=null,Xo=0,Df=null;function ar(){return(Lt&2)!==0&&wt!==0?wt&-wt:V.T!==null?Bf():Oe()}function Fb(){if(ir===0)if((wt&536870912)===0||kt){var s=ye;ye<<=1,(ye&3932160)===0&&(ye=262144),ir=s}else ir=536870912;return s=nr.current,s!==null&&(s.flags|=32),ir}function Kn(s,o,f){(s===$t&&(Rt===2||Rt===9)||s.cancelPendingCommit!==null)&&(Oa(s,0),Ws(s,wt,ir,!1)),Pr(s,f),((Lt&2)===0||s!==$t)&&(s===$t&&((Lt&2)===0&&(Oi|=f),Jt===4&&Ws(s,wt,ir,!1)),Hr(s))}function Vb(s,o,f){if((Lt&6)!==0)throw Error(r(327));var g=!f&&(o&127)===0&&(o&s.expiredLanes)===0||Pe(s,o),k=g?F2(s,o):Of(s,o,!0),A=g;do{if(k===0){La&&!g&&Ws(s,o,0,!1);break}else{if(f=s.current.alternate,A&&!H2(f)){k=Of(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=Yo;var le=Y.current.memoizedState.isDehydrated;if(le&&(Oa(Y,F).flags|=256),F=Of(Y,F,!1),F!==2){if(Ef&&!le){Y.errorRecoveryDisabledLanes|=A,Oi|=A,k=4;break e}A=qn,qn=k,A!==null&&(qn===null?qn=A:qn.push.apply(qn,A))}k=F}if(A=!1,k!==2)continue}}if(k===1){Oa(s,0),Ws(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:Ws(g,o,ir,!Us);break e;case 2:qn=null;break;case 3:case 5:break;default:throw Error(r(329))}if((o&62914560)===o&&(k=Gc+300-Ie(),10<k)){if(Ws(g,o,ir,!Us),fe(g,0,!0)!==0)break e;ms=o,g.timeoutHandle=_v(Gb.bind(null,g,f,qn,qc,Tf,o,ir,Oi,Da,Us,A,"Throttled",-0,0),k);break e}Gb(g,f,qn,qc,Tf,o,ir,Oi,Da,Us,A,null,-0,0)}}break}while(!0);Hr(s)}function Gb(s,o,f,g,k,A,F,Y,le,ge,ke,Ae,xe,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},Pb(o,A,Ae);var Ke=(A&62914560)===A?Gc-Ie():(A&4194048)===A?Hb-Ie():0;if(Ke=kE(Ae,Ke),Ke!==null){ms=A,s.cancelPendingCommit=Ke(Zb.bind(null,s,o,A,f,g,k,F,Y,le,ke,Ae,null,xe,be)),Ws(s,A,F,!ge);return}}Zb(s,o,A,f,g,k,F,Y,le)}function H2(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(!er(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 Ws(s,o,f,g){o&=~Nf,o&=~Oi,s.suspendedLanes|=o,s.pingedLanes&=~o,g&&(s.warmLanes|=o),g=s.expirationTimes;for(var k=o;0<k;){var A=31-tt(k),F=1<<A;g[A]=-1,k&=~F}f!==0&&xi(s,f,o)}function Kc(){return(Lt&6)===0?(Qo(0),!1):!0}function Rf(){if(yt!==null){if(Rt===0)var s=yt.return;else s=yt,rs=ki=null,Kh(s),Ca=null,Ro=0,s=yt;for(;s!==null;)Sb(s.alternate,s),s=s.return;yt=null}}function Oa(s,o){var f=s.timeoutHandle;f!==-1&&(s.timeoutHandle=-1,oE(f)),f=s.cancelPendingCommit,f!==null&&(s.cancelPendingCommit=null,f()),ms=0,Rf(),$t=s,yt=f=ts(s.current,null),wt=o,Rt=0,sr=null,Us=!1,La=Pe(s,o),Ef=!1,Da=ir=Nf=Oi=Fs=Jt=0,qn=Yo=null,Tf=!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-tt(g),A=1<<k;o|=s[k],g&=~A}return fs=o,pc(),f}function Wb(s,o){ft=null,V.H=Ho,o===wa||o===wc?(o=ly(),Rt=3):o===Mh?(o=ly(),Rt=4):Rt=o===df?8:o!==null&&typeof o=="object"&&typeof o.then=="function"?6:1,sr=o,yt===null&&(Jt=1,Pc(s,fr(o,s.current)))}function qb(){var s=nr.current;return s===null?!0:(wt&4194048)===wt?xr===null:(wt&62914560)===wt||(wt&536870912)!==0?s===xr:!1}function Kb(){var s=V.H;return V.H=Ho,s===null?Ho:s}function Yb(){var s=V.A;return V.A=$2,s}function Yc(){Jt=4,Us||(wt&4194048)!==wt&&nr.current!==null||(La=!0),(Fs&134217727)===0&&(Oi&134217727)===0||$t===null||Ws($t,wt,ir,!1)}function Of(s,o,f){var g=Lt;Lt|=2;var k=Kb(),A=Yb();($t!==s||wt!==o)&&(qc=null,Oa(s,o)),o=!1;var F=Jt;e:do try{if(Rt!==0&&yt!==null){var Y=yt,le=sr;switch(Rt){case 8:Rf(),F=6;break e;case 3:case 2:case 9:case 6:nr.current===null&&(o=!0);var ge=Rt;if(Rt=0,sr=null,Ia(s,Y,le,ge),f&&La){F=0;break e}break;default:ge=Rt,Rt=0,sr=null,Ia(s,Y,le,ge)}}U2(),F=Jt;break}catch(ke){Wb(s,ke)}while(!0);return o&&s.shellSuspendCounter++,rs=ki=null,Lt=g,V.H=k,V.A=A,yt===null&&($t=null,wt=0,pc()),F}function U2(){for(;yt!==null;)Xb(yt)}function F2(s,o){var f=Lt;Lt|=2;var g=Kb(),k=Yb();$t!==s||wt!==o?(qc=null,Wc=Ie()+500,Oa(s,o)):La=Pe(s,o);e:do try{if(Rt!==0&&yt!==null){o=yt;var A=sr;t:switch(Rt){case 1:Rt=0,sr=null,Ia(s,o,A,1);break;case 2:case 9:if(ay(A)){Rt=0,sr=null,Qb(o);break}o=function(){Rt!==2&&Rt!==9||$t!==s||(Rt=7),Hr(s)},A.then(o,o);break e;case 3:Rt=7;break e;case 4:Rt=5;break e;case 7:ay(A)?(Rt=0,sr=null,Qb(o)):(Rt=0,sr=null,Ia(s,o,A,7));break;case 5:var F=null;switch(yt.tag){case 26:F=yt.memoizedState;case 5:case 27:var Y=yt;if(F?Mv(F):Y.stateNode.complete){Rt=0,sr=null;var le=Y.sibling;if(le!==null)yt=le;else{var ge=Y.return;ge!==null?(yt=ge,Xc(ge)):yt=null}break t}}Rt=0,sr=null,Ia(s,o,A,5);break;case 6:Rt=0,sr=null,Ia(s,o,A,6);break;case 8:Rf(),Jt=6;break e;default:throw Error(r(462))}}V2();break}catch(ke){Wb(s,ke)}while(!0);return rs=ki=null,V.H=g,V.A=k,Lt=f,yt!==null?0:($t=null,wt=0,pc(),Jt)}function V2(){for(;yt!==null&&!lt();)Xb(yt)}function Xb(s){var o=vb(s.alternate,s,fs);s.memoizedProps=s.pendingProps,o===null?Xc(s):yt=o}function Qb(s){var o=s,f=o.alternate;switch(o.tag){case 15:case 0:o=mb(f,o,o.pendingProps,o.type,void 0,wt);break;case 11:o=mb(f,o,o.pendingProps,o.type.render,o.ref,wt);break;case 5:Kh(o);default:Sb(f,o),o=yt=Yx(o,fs),o=vb(f,o,fs)}s.memoizedProps=s.pendingProps,o===null?Xc(s):yt=o}function Ia(s,o,f,g){rs=ki=null,Kh(o),Ca=null,Ro=0;var k=o.return;try{if(D2(s,k,o,f,wt)){Jt=1,Pc(s,fr(f,s.current)),yt=null;return}}catch(A){if(k!==null)throw yt=k,A;Jt=1,Pc(s,fr(f,s.current)),yt=null;return}o.flags&32768?(kt||g===1?s=!0:La||(wt&536870912)!==0?s=!1:(Us=s=!0,(g===2||g===9||g===3||g===6)&&(g=nr.current,g!==null&&g.tag===13&&(g.flags|=16384))),Jb(o,s)):Xc(o)}function Xc(s){var o=s;do{if((o.flags&32768)!==0){Jb(o,Us);return}s=o.return;var f=I2(o.alternate,o,fs);if(f!==null){yt=f;return}if(o=o.sibling,o!==null){yt=o;return}yt=o=s}while(o!==null);Jt===0&&(Jt=5)}function Jb(s,o){do{var f=M2(s.alternate,s);if(f!==null){f.flags&=32767,yt=f;return}if(f=s.return,f!==null&&(f.flags|=32768,f.subtreeFlags=0,f.deletions=null),!o&&(s=s.sibling,s!==null)){yt=s;return}yt=s=f}while(s!==null);Jt=6,yt=null}function Zb(s,o,f,g,k,A,F,Y,le){s.cancelPendingCommit=null;do Qc();while(pn!==0);if((Lt&6)!==0)throw Error(r(327));if(o!==null){if(o===s.current)throw Error(r(177));if(A=o.lanes|o.childLanes,A|=_h,Ns(s,f,A,F,Y,le),s===$t&&(yt=$t=null,wt=0),Ra=o,Gs=s,ms=f,Af=A,Lf=k,Ub=g,(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?(s.callbackNode=null,s.callbackPriority=0,K2(se,function(){return sv(),null})):(s.callbackNode=null,s.callbackPriority=0),g=(o.flags&13878)!==0,(o.subtreeFlags&13878)!==0||g){g=V.T,V.T=null,k=Z.p,Z.p=2,F=Lt,Lt|=4;try{P2(s,o,f)}finally{Lt=F,Z.p=k,V.T=g}}pn=1,ev(),tv(),nv()}}function ev(){if(pn===1){pn=0;var s=Gs,o=Ra,f=(o.flags&13878)!==0;if((o.subtreeFlags&13878)!==0||f){f=V.T,V.T=null;var g=Z.p;Z.p=2;var k=Lt;Lt|=4;try{Ob(o,s);var A=Wf,F=zx(s.containerInfo),Y=A.focusedElem,le=A.selectionRange;if(F!==Y&&Y&&Y.ownerDocument&&$x(Y.ownerDocument.documentElement,Y)){if(le!==null&&gh(Y)){var ge=le.start,ke=le.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,xe=Ae&&Ae.defaultView||window;if(xe.getSelection){var be=xe.getSelection(),Ke=Y.textContent.length,it=Math.min(le.start,Ke),Pt=le.end===void 0?it:Math.min(le.end,Ke);!be.extend&&it>Pt&&(F=Pt,Pt=it,it=F);var de=Bx(Y,it),ue=Bx(Y,Pt);if(de&&ue&&(be.rangeCount!==1||be.anchorNode!==de.node||be.anchorOffset!==de.offset||be.focusNode!==ue.node||be.focusOffset!==ue.offset)){var pe=Ae.createRange();pe.setStart(de.node,de.offset),be.removeAllRanges(),it>Pt?(be.addRange(pe),be.extend(ue.node,ue.offset)):(pe.setEnd(ue.node,ue.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 Ne=Ae[Y];Ne.element.scrollLeft=Ne.left,Ne.element.scrollTop=Ne.top}}cu=!!Gf,Wf=Gf=null}finally{Lt=k,Z.p=g,V.T=f}}s.current=o,pn=2}}function tv(){if(pn===2){pn=0;var s=Gs,o=Ra,f=(o.flags&8772)!==0;if((o.subtreeFlags&8772)!==0||f){f=V.T,V.T=null;var g=Z.p;Z.p=2;var k=Lt;Lt|=4;try{Tb(s,o.alternate,o)}finally{Lt=k,Z.p=g,V.T=f}}pn=3}}function nv(){if(pn===4||pn===3){pn=0,we();var s=Gs,o=Ra,f=ms,g=Ub;(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?pn=5:(pn=0,Ra=Gs=null,rv(s,s.pendingLanes));var k=s.pendingLanes;if(k===0&&(Vs=null),Ce(f),o=o.stateNode,Je&&typeof Je.onCommitFiberRoot=="function")try{Je.onCommitFiberRoot(ct,o,void 0,(o.current.flags&128)===128)}catch{}if(g!==null){o=V.T,k=Z.p,Z.p=2,V.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{V.T=o,Z.p=k}}(ms&3)!==0&&Qc(),Hr(s),k=s.pendingLanes,(f&261930)!==0&&(k&42)!==0?s===Df?Xo++:(Xo=0,Df=s):Xo=0,Qo(0)}}function rv(s,o){(s.pooledCacheLanes&=o)===0&&(o=s.pooledCache,o!=null&&(s.pooledCache=null,Lo(o)))}function Qc(){return ev(),tv(),nv(),sv()}function sv(){if(pn!==5)return!1;var s=Gs,o=Af;Af=0;var f=Ce(ms),g=V.T,k=Z.p;try{Z.p=32>f?32:f,V.T=null,f=Lf,Lf=null;var A=Gs,F=ms;if(pn=0,Ra=Gs=null,ms=0,(Lt&6)!==0)throw Error(r(331));var Y=Lt;if(Lt|=4,$b(A.current),Mb(A,A.current,F,f),Lt=Y,Qo(0,!1),Je&&typeof Je.onPostCommitFiberRoot=="function")try{Je.onPostCommitFiberRoot(ct,A)}catch{}return!0}finally{Z.p=k,V.T=g,rv(s,o)}}function iv(s,o,f){o=fr(f,o),o=uf(s.stateNode,o,2),s=Bs(s,o,2),s!==null&&(Pr(s,2),Hr(s))}function Ot(s,o,f){if(s.tag===3)iv(s,s,f);else for(;o!==null;){if(o.tag===3){iv(o,s,f);break}else if(o.tag===1){var g=o.stateNode;if(typeof o.type.getDerivedStateFromError=="function"||typeof g.componentDidCatch=="function"&&(Vs===null||!Vs.has(g))){s=fr(f,s),f=ab(2),g=Bs(o,f,2),g!==null&&(ob(f,g,o,s),Pr(g,2),Hr(g));break}}o=o.return}}function If(s,o,f){var g=s.pingCache;if(g===null){g=s.pingCache=new z2;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)||(Ef=!0,k.add(f),s=G2.bind(null,s,o,f),o.then(s,s))}function G2(s,o,f){var g=s.pingCache;g!==null&&g.delete(o),s.pingedLanes|=s.suspendedLanes&f,s.warmLanes&=~f,$t===s&&(wt&f)===f&&(Jt===4||Jt===3&&(wt&62914560)===wt&&300>Ie()-Gc?(Lt&2)===0&&Oa(s,0):Nf|=f,Da===wt&&(Da=0)),Hr(s)}function av(s,o){o===0&&(o=bn()),s=Si(s,o),s!==null&&(Pr(s,o),Hr(s))}function W2(s){var o=s.memoizedState,f=0;o!==null&&(f=o.retryLane),av(s,f)}function q2(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),av(s,f)}function K2(s,o){return je(s,o)}var Jc=null,Ma=null,Mf=!1,Zc=!1,Pf=!1,qs=0;function Hr(s){s!==Ma&&s.next===null&&(Ma===null?Jc=Ma=s:Ma=Ma.next=s),Zc=!0,Mf||(Mf=!0,X2())}function Qo(s,o){if(!Pf&&Zc){Pf=!0;do for(var f=!1,g=Jc;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-tt(42|s)+1)-1,A&=k&~(F&~Y),A=A&201326741?A&201326741|1:A?A|2:0}A!==0&&(f=!0,uv(g,A))}else A=wt,A=fe(g,g===$t?A:0,g.cancelPendingCommit!==null||g.timeoutHandle!==-1),(A&3)===0||Pe(g,A)||(f=!0,uv(g,A));g=g.next}while(f);Pf=!1}}function Y2(){ov()}function ov(){Zc=Mf=!1;var s=0;qs!==0&&aE()&&(s=qs);for(var o=Ie(),f=null,g=Jc;g!==null;){var k=g.next,A=lv(g,o);A===0?(g.next=null,f===null?Jc=k:f.next=k,k===null&&(Ma=f)):(f=g,(s!==0||(A&3)!==0)&&(Zc=!0)),g=k}pn!==0&&pn!==5||Qo(s),qs!==0&&(qs=0)}function lv(s,o){for(var f=s.suspendedLanes,g=s.pingedLanes,k=s.expirationTimes,A=s.pendingLanes&-62914561;0<A;){var F=31-tt(A),Y=1<<F,le=k[F];le===-1?((Y&f)===0||(Y&g)!==0)&&(k[F]=St(Y,o)):le<=o&&(s.expiredLanes|=Y),A&=~Y}if(o=$t,f=wt,f=fe(s,s===o?f:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g=s.callbackNode,f===0||s===o&&(Rt===2||Rt===9)||s.cancelPendingCommit!==null)return g!==null&&g!==null&&Me(g),s.callbackNode=null,s.callbackPriority=0;if((f&3)===0||Pe(s,f)){if(o=f&-f,o===s.callbackPriority)return o;switch(g!==null&&Me(g),Ce(f)){case 2:case 8:f=ae;break;case 32:f=se;break;case 268435456:f=Ue;break;default:f=se}return g=cv.bind(null,s),f=je(f,g),s.callbackPriority=o,s.callbackNode=f,o}return g!==null&&g!==null&&Me(g),s.callbackPriority=2,s.callbackNode=null,2}function cv(s,o){if(pn!==0&&pn!==5)return s.callbackNode=null,s.callbackPriority=0,null;var f=s.callbackNode;if(Qc()&&s.callbackNode!==f)return null;var g=wt;return g=fe(s,s===$t?g:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),g===0?null:(Vb(s,g,o),lv(s,Ie()),s.callbackNode!=null&&s.callbackNode===f?cv.bind(null,s):null)}function uv(s,o){if(Qc())return null;Vb(s,o,!0)}function X2(){lE(function(){(Lt&6)!==0?je(te,Y2):ov()})}function Bf(){if(qs===0){var s=_a;s===0&&(s=Un,Un<<=1,(Un&261888)===0&&(Un=256)),qs=s}return qs}function dv(s){return s==null||typeof s=="symbol"||typeof s=="boolean"?null:typeof s=="function"?s:oc(""+s)}function hv(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 Q2(s,o,f,g,k){if(o==="submit"&&f&&f.stateNode===k){var A=dv((k[at]||null).action),F=g.submitter;F&&(o=(o=F[at]||null)?dv(o.formAction):F.getAttribute("formAction"),o!==null&&(A=o,F=null));var Y=new dc("action","action",null,g,k);s.push({event:Y,listeners:[{instance:null,listener:function(){if(g.defaultPrevented){if(qs!==0){var le=F?hv(k,F):new FormData(k);rf(f,{pending:!0,data:le,method:k.method,action:A},null,le)}}else typeof A=="function"&&(Y.preventDefault(),le=F?hv(k,F):new FormData(k),rf(f,{pending:!0,data:le,method:k.method,action:A},A,le))},currentTarget:k}]})}}for(var $f=0;$f<vh.length;$f++){var zf=vh[$f],J2=zf.toLowerCase(),Z2=zf[0].toUpperCase()+zf.slice(1);jr(J2,"on"+Z2)}jr(Fx,"onAnimationEnd"),jr(Vx,"onAnimationIteration"),jr(Gx,"onAnimationStart"),jr("dblclick","onDoubleClick"),jr("focusin","onFocus"),jr("focusout","onBlur"),jr(p2,"onTransitionRun"),jr(g2,"onTransitionStart"),jr(x2,"onTransitionCancel"),jr(Wx,"onTransitionEnd"),oa("onMouseEnter",["mouseout","mouseover"]),oa("onMouseLeave",["mouseout","mouseover"]),oa("onPointerEnter",["pointerout","pointerover"]),oa("onPointerLeave",["pointerout","pointerover"]),yi("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),yi("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),yi("onBeforeInput",["compositionend","keypress","textInput","paste"]),yi("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),yi("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),yi("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Jo="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(" "),eE=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Jo));function fv(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],le=Y.instance,ge=Y.currentTarget;if(Y=Y.listener,le!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){mc(ke)}k.currentTarget=null,A=le}else for(F=0;F<g.length;F++){if(Y=g[F],le=Y.instance,ge=Y.currentTarget,Y=Y.listener,le!==A&&k.isPropagationStopped())break e;A=Y,k.currentTarget=ge;try{A(k)}catch(ke){mc(ke)}k.currentTarget=null,A=le}}}}function bt(s,o){var f=o[mn];f===void 0&&(f=o[mn]=new Set);var g=s+"__bubble";f.has(g)||(mv(o,s,2,!1),f.add(g))}function Hf(s,o,f){var g=0;o&&(g|=4),mv(f,s,g,o)}var eu="_reactListening"+Math.random().toString(36).slice(2);function Uf(s){if(!s[eu]){s[eu]=!0,ox.forEach(function(f){f!=="selectionchange"&&(eE.has(f)||Hf(f,!1,s),Hf(f,!0,s))});var o=s.nodeType===9?s:s.ownerDocument;o===null||o[eu]||(o[eu]=!0,Hf("selectionchange",!1,o))}}function mv(s,o,f,g){switch(Fv(o)){case 2:var k=NE;break;case 8:k=TE;break;default:k=rm}f=k.bind(null,o,f,s),k=void 0,!oh||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 Ff(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 le=F.tag;if((le===3||le===4)&&F.stateNode.containerInfo===k)return;F=F.return}for(;Y!==null;){if(F=sa(Y),F===null)return;if(le=F.tag,le===5||le===6||le===26||le===27){g=A=F;continue e}Y=Y.parentNode}}g=g.return}bx(function(){var ge=A,ke=ih(f),Ae=[];e:{var xe=qx.get(s);if(xe!==void 0){var be=dc,Ke=s;switch(s){case"keypress":if(cc(f)===0)break e;case"keydown":case"keyup":be=qj;break;case"focusin":Ke="focus",be=dh;break;case"focusout":Ke="blur",be=dh;break;case"beforeblur":case"afterblur":be=dh;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=Sx;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":be=Ij;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":be=Xj;break;case Fx:case Vx:case Gx:be=Bj;break;case Wx:be=Jj;break;case"scroll":case"scrollend":be=Rj;break;case"wheel":be=e2;break;case"copy":case"cut":case"paste":be=zj;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":be=Cx;break;case"toggle":case"beforetoggle":be=n2}var it=(o&4)!==0,Pt=!it&&(s==="scroll"||s==="scrollend"),de=it?xe!==null?xe+"Capture":null:xe;it=[];for(var ue=ge,pe;ue!==null;){var Ne=ue;if(pe=Ne.stateNode,Ne=Ne.tag,Ne!==5&&Ne!==26&&Ne!==27||pe===null||de===null||(Ne=vo(ue,de),Ne!=null&&it.push(Zo(ue,Ne,pe))),Pt)break;ue=ue.return}0<it.length&&(xe=new be(xe,Ke,null,f,ke),Ae.push({event:xe,listeners:it}))}}if((o&7)===0){e:{if(xe=s==="mouseover"||s==="pointerover",be=s==="mouseout"||s==="pointerout",xe&&f!==sh&&(Ke=f.relatedTarget||f.fromElement)&&(sa(Ke)||Ke[Zt]))break e;if((be||xe)&&(xe=ke.window===ke?ke:(xe=ke.ownerDocument)?xe.defaultView||xe.parentWindow:window,be?(Ke=f.relatedTarget||f.toElement,be=ge,Ke=Ke?sa(Ke):null,Ke!==null&&(Pt=l(Ke),it=Ke.tag,Ke!==Pt||it!==5&&it!==27&&it!==6)&&(Ke=null)):(be=null,Ke=ge),be!==Ke)){if(it=Sx,Ne="onMouseLeave",de="onMouseEnter",ue="mouse",(s==="pointerout"||s==="pointerover")&&(it=Cx,Ne="onPointerLeave",de="onPointerEnter",ue="pointer"),Pt=be==null?xe:bo(be),pe=Ke==null?xe:bo(Ke),xe=new it(Ne,ue+"leave",be,f,ke),xe.target=Pt,xe.relatedTarget=pe,Ne=null,sa(ke)===ge&&(it=new it(de,ue+"enter",Ke,f,ke),it.target=pe,it.relatedTarget=Pt,Ne=it),Pt=Ne,be&&Ke)t:{for(it=tE,de=be,ue=Ke,pe=0,Ne=de;Ne;Ne=it(Ne))pe++;Ne=0;for(var et=ue;et;et=it(et))Ne++;for(;0<pe-Ne;)de=it(de),pe--;for(;0<Ne-pe;)ue=it(ue),Ne--;for(;pe--;){if(de===ue||ue!==null&&de===ue.alternate){it=de;break t}de=it(de),ue=it(ue)}it=null}else it=null;be!==null&&pv(Ae,xe,be,it,!1),Ke!==null&&Pt!==null&&pv(Ae,Pt,Ke,it,!0)}}e:{if(xe=ge?bo(ge):window,be=xe.nodeName&&xe.nodeName.toLowerCase(),be==="select"||be==="input"&&xe.type==="file")var Tt=Dx;else if(Ax(xe))if(Rx)Tt=h2;else{Tt=u2;var Xe=c2}else be=xe.nodeName,!be||be.toLowerCase()!=="input"||xe.type!=="checkbox"&&xe.type!=="radio"?ge&&rh(ge.elementType)&&(Tt=Dx):Tt=d2;if(Tt&&(Tt=Tt(s,ge))){Lx(Ae,Tt,f,ke);break e}Xe&&Xe(s,xe,ge),s==="focusout"&&ge&&xe.type==="number"&&ge.memoizedProps.value!=null&&nh(xe,"number",xe.value)}switch(Xe=ge?bo(ge):window,s){case"focusin":(Ax(Xe)||Xe.contentEditable==="true")&&(fa=Xe,xh=ge,No=null);break;case"focusout":No=xh=fa=null;break;case"mousedown":yh=!0;break;case"contextmenu":case"mouseup":case"dragend":yh=!1,Hx(Ae,f,ke);break;case"selectionchange":if(m2)break;case"keydown":case"keyup":Hx(Ae,f,ke)}var mt;if(fh)e:{switch(s){case"compositionstart":var Ct="onCompositionStart";break e;case"compositionend":Ct="onCompositionEnd";break e;case"compositionupdate":Ct="onCompositionUpdate";break e}Ct=void 0}else ha?Nx(s,f)&&(Ct="onCompositionEnd"):s==="keydown"&&f.keyCode===229&&(Ct="onCompositionStart");Ct&&(kx&&f.locale!=="ko"&&(ha||Ct!=="onCompositionStart"?Ct==="onCompositionEnd"&&ha&&(mt=vx()):(Ls=ke,lh="value"in Ls?Ls.value:Ls.textContent,ha=!0)),Xe=tu(ge,Ct),0<Xe.length&&(Ct=new wx(Ct,s,null,f,ke),Ae.push({event:Ct,listeners:Xe}),mt?Ct.data=mt:(mt=Tx(f),mt!==null&&(Ct.data=mt)))),(mt=s2?i2(s,f):a2(s,f))&&(Ct=tu(ge,"onBeforeInput"),0<Ct.length&&(Xe=new wx("onBeforeInput","beforeinput",null,f,ke),Ae.push({event:Xe,listeners:Ct}),Xe.data=mt)),Q2(Ae,s,ge,f,ke)}fv(Ae,o)})}function Zo(s,o,f){return{instance:s,listener:o,currentTarget:f}}function tu(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=vo(s,f),k!=null&&g.unshift(Zo(s,k,A)),k=vo(s,o),k!=null&&g.push(Zo(s,k,A))),s.tag===3)return g;s=s.return}return[]}function tE(s){if(s===null)return null;do s=s.return;while(s&&s.tag!==5&&s.tag!==27);return s||null}function pv(s,o,f,g,k){for(var A=o._reactName,F=[];f!==null&&f!==g;){var Y=f,le=Y.alternate,ge=Y.stateNode;if(Y=Y.tag,le!==null&&le===g)break;Y!==5&&Y!==26&&Y!==27||ge===null||(le=ge,k?(ge=vo(f,A),ge!=null&&F.unshift(Zo(f,ge,le))):k||(ge=vo(f,A),ge!=null&&F.push(Zo(f,ge,le)))),f=f.return}F.length!==0&&s.push({event:o,listeners:F})}var nE=/\r\n?/g,rE=/\u0000|\uFFFD/g;function gv(s){return(typeof s=="string"?s:""+s).replace(nE,`
50
+ `).replace(rE,"")}function xv(s,o){return o=gv(o),gv(s)===o}function Mt(s,o,f,g,k,A){switch(f){case"children":typeof g=="string"?o==="body"||o==="textarea"&&g===""||ca(s,g):(typeof g=="number"||typeof g=="bigint")&&o!=="body"&&ca(s,""+g);break;case"className":ic(s,"class",g);break;case"tabIndex":ic(s,"tabindex",g);break;case"dir":case"role":case"viewBox":case"width":case"height":ic(s,f,g);break;case"style":xx(s,g,A);break;case"data":if(o!=="object"){ic(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=oc(""+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"&&Mt(s,o,"name",k.name,k,null),Mt(s,o,"formEncType",k.formEncType,k,null),Mt(s,o,"formMethod",k.formMethod,k,null),Mt(s,o,"formTarget",k.formTarget,k,null)):(Mt(s,o,"encType",k.encType,k,null),Mt(s,o,"method",k.method,k,null),Mt(s,o,"target",k.target,k,null)));if(g==null||typeof g=="symbol"||typeof g=="boolean"){s.removeAttribute(f);break}g=oc(""+g),s.setAttribute(f,g);break;case"onClick":g!=null&&(s.onclick=Zr);break;case"onScroll":g!=null&&bt("scroll",s);break;case"onScrollEnd":g!=null&&bt("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=oc(""+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":bt("beforetoggle",s),bt("toggle",s),sc(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":sc(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=Lj.get(f)||f,sc(s,f,g))}}function Vf(s,o,f,g,k,A){switch(f){case"style":xx(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"?ca(s,g):(typeof g=="number"||typeof g=="bigint")&&ca(s,""+g);break;case"onScroll":g!=null&&bt("scroll",s);break;case"onScrollEnd":g!=null&&bt("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(!lx.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[at]||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,""):sc(s,f,g)}}}function En(s,o,f){switch(o){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":bt("error",s),bt("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:Mt(s,o,A,F,f,null)}}k&&Mt(s,o,"srcSet",f.srcSet,f,null),g&&Mt(s,o,"src",f.src,f,null);return;case"input":bt("invalid",s);var Y=A=F=k=null,le=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":le=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:Mt(s,o,g,ke,f,null)}}fx(s,A,Y,le,ge,F,k,!1);return;case"select":bt("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:Mt(s,o,k,Y,f,null)}o=A,f=F,s.multiple=!!g,o!=null?la(s,!!g,o,!1):f!=null&&la(s,!!g,f,!0);return;case"textarea":bt("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:Mt(s,o,F,Y,f,null)}px(s,g,k,A);return;case"option":for(le in f)if(f.hasOwnProperty(le)&&(g=f[le],g!=null))switch(le){case"selected":s.selected=g&&typeof g!="function"&&typeof g!="symbol";break;default:Mt(s,o,le,g,f,null)}return;case"dialog":bt("beforetoggle",s),bt("toggle",s),bt("cancel",s),bt("close",s);break;case"iframe":case"object":bt("load",s);break;case"video":case"audio":for(g=0;g<Jo.length;g++)bt(Jo[g],s);break;case"image":bt("error",s),bt("load",s);break;case"details":bt("toggle",s);break;case"embed":case"source":case"link":bt("error",s),bt("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:Mt(s,o,ge,g,f,null)}return;default:if(rh(o)){for(ke in f)f.hasOwnProperty(ke)&&(g=f[ke],g!==void 0&&Vf(s,o,ke,g,f,void 0));return}}for(Y in f)f.hasOwnProperty(Y)&&(g=f[Y],g!=null&&Mt(s,o,Y,g,f,null))}function sE(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,le=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":le=Ae;default:g.hasOwnProperty(be)||Mt(s,o,be,null,g,Ae)}}for(var xe in g){var be=g[xe];if(Ae=f[xe],g.hasOwnProperty(xe)&&(be!=null||Ae!=null))switch(xe){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&&Mt(s,o,xe,be,g,Ae)}}th(s,F,Y,le,ge,ke,A,k);return;case"select":be=F=Y=xe=null;for(A in f)if(le=f[A],f.hasOwnProperty(A)&&le!=null)switch(A){case"value":break;case"multiple":be=le;default:g.hasOwnProperty(A)||Mt(s,o,A,null,g,le)}for(k in g)if(A=g[k],le=f[k],g.hasOwnProperty(k)&&(A!=null||le!=null))switch(k){case"value":xe=A;break;case"defaultValue":Y=A;break;case"multiple":F=A;default:A!==le&&Mt(s,o,k,A,g,le)}o=Y,f=F,g=be,xe!=null?la(s,!!f,xe,!1):!!g!=!!f&&(o!=null?la(s,!!f,o,!0):la(s,!!f,f?[]:"",!1));return;case"textarea":be=xe=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:Mt(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":xe=k;break;case"defaultValue":be=k;break;case"children":break;case"dangerouslySetInnerHTML":if(k!=null)throw Error(r(91));break;default:k!==A&&Mt(s,o,F,k,g,A)}mx(s,xe,be);return;case"option":for(var Ke in f)if(xe=f[Ke],f.hasOwnProperty(Ke)&&xe!=null&&!g.hasOwnProperty(Ke))switch(Ke){case"selected":s.selected=!1;break;default:Mt(s,o,Ke,null,g,xe)}for(le in g)if(xe=g[le],be=f[le],g.hasOwnProperty(le)&&xe!==be&&(xe!=null||be!=null))switch(le){case"selected":s.selected=xe&&typeof xe!="function"&&typeof xe!="symbol";break;default:Mt(s,o,le,xe,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 it in f)xe=f[it],f.hasOwnProperty(it)&&xe!=null&&!g.hasOwnProperty(it)&&Mt(s,o,it,null,g,xe);for(ge in g)if(xe=g[ge],be=f[ge],g.hasOwnProperty(ge)&&xe!==be&&(xe!=null||be!=null))switch(ge){case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(r(137,o));break;default:Mt(s,o,ge,xe,g,be)}return;default:if(rh(o)){for(var Pt in f)xe=f[Pt],f.hasOwnProperty(Pt)&&xe!==void 0&&!g.hasOwnProperty(Pt)&&Vf(s,o,Pt,void 0,g,xe);for(ke in g)xe=g[ke],be=f[ke],!g.hasOwnProperty(ke)||xe===be||xe===void 0&&be===void 0||Vf(s,o,ke,xe,g,be);return}}for(var de in f)xe=f[de],f.hasOwnProperty(de)&&xe!=null&&!g.hasOwnProperty(de)&&Mt(s,o,de,null,g,xe);for(Ae in g)xe=g[Ae],be=f[Ae],!g.hasOwnProperty(Ae)||xe===be||xe==null&&be==null||Mt(s,o,Ae,xe,g,be)}function yv(s){switch(s){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function iE(){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&&yv(F)){for(F=0,Y=k.responseEnd,g+=1;g<f.length;g++){var le=f[g],ge=le.startTime;if(ge>Y)break;var ke=le.transferSize,Ae=le.initiatorType;ke&&yv(Ae)&&(le=le.responseEnd,F+=ke*(le<Y?1:(Y-ge)/(le-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 Gf=null,Wf=null;function nu(s){return s.nodeType===9?s:s.ownerDocument}function bv(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 vv(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 qf(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 Kf=null;function aE(){var s=window.event;return s&&s.type==="popstate"?s===Kf?!1:(Kf=s,!0):(Kf=null,!1)}var _v=typeof setTimeout=="function"?setTimeout:void 0,oE=typeof clearTimeout=="function"?clearTimeout:void 0,Sv=typeof Promise=="function"?Promise:void 0,lE=typeof queueMicrotask=="function"?queueMicrotask:typeof Sv<"u"?function(s){return Sv.resolve(null).then(s).catch(cE)}:_v;function cE(s){setTimeout(function(){throw s})}function Ks(s){return s==="head"}function wv(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),za(o);return}g--}else if(f==="$"||f==="$?"||f==="$~"||f==="$!"||f==="&")g++;else if(f==="html")el(s.ownerDocument.documentElement);else if(f==="head"){f=s.ownerDocument.head,el(f);for(var A=f.firstChild;A;){var F=A.nextSibling,Y=A.nodeName;A[yo]||Y==="SCRIPT"||Y==="STYLE"||Y==="LINK"&&A.rel.toLowerCase()==="stylesheet"||f.removeChild(A),A=F}}else f==="body"&&el(s.ownerDocument.body);f=k}while(f);za(o)}function Cv(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 Yf(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":Yf(f),Zd(f);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(f.rel.toLowerCase()==="stylesheet")continue}s.removeChild(f)}}function uE(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[yo])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=yr(s.nextSibling),s===null)break}return null}function dE(s,o,f){if(o==="")return null;for(;s.nodeType!==3;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!f||(s=yr(s.nextSibling),s===null))return null;return s}function kv(s,o){for(;s.nodeType!==8;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!o||(s=yr(s.nextSibling),s===null))return null;return s}function Xf(s){return s.data==="$?"||s.data==="$~"}function Qf(s){return s.data==="$!"||s.data==="$?"&&s.ownerDocument.readyState!=="loading"}function hE(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 yr(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 Jf=null;function jv(s){s=s.nextSibling;for(var o=0;s;){if(s.nodeType===8){var f=s.data;if(f==="/$"||f==="/&"){if(o===0)return yr(s.nextSibling);o--}else f!=="$"&&f!=="$!"&&f!=="$?"&&f!=="$~"&&f!=="&"||o++}s=s.nextSibling}return null}function Ev(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 Nv(s,o,f){switch(o=nu(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 el(s){for(var o=s.attributes;o.length;)s.removeAttributeNode(o[0]);Zd(s)}var br=new Map,Tv=new Set;function ru(s){return typeof s.getRootNode=="function"?s.getRootNode():s.nodeType===9?s:s.ownerDocument}var ps=Z.d;Z.d={f:fE,r:mE,D:pE,C:gE,L:xE,m:yE,X:vE,S:bE,M:_E};function fE(){var s=ps.f(),o=Kc();return s||o}function mE(s){var o=ia(s);o!==null&&o.tag===5&&o.type==="form"?Wy(o):ps.r(s)}var Pa=typeof document>"u"?null:document;function Av(s,o,f){var g=Pa;if(g&&typeof o=="string"&&o){var k=dr(o);k='link[rel="'+s+'"][href="'+k+'"]',typeof f=="string"&&(k+='[crossorigin="'+f+'"]'),Tv.has(k)||(Tv.add(k),s={rel:s,crossOrigin:f,href:o},g.querySelector(k)===null&&(o=g.createElement("link"),En(o,"link",s),vn(o),g.head.appendChild(o)))}}function pE(s){ps.D(s),Av("dns-prefetch",s,null)}function gE(s,o){ps.C(s,o),Av("preconnect",s,o)}function xE(s,o,f){ps.L(s,o,f);var g=Pa;if(g&&s&&o){var k='link[rel="preload"][as="'+dr(o)+'"]';o==="image"&&f&&f.imageSrcSet?(k+='[imagesrcset="'+dr(f.imageSrcSet)+'"]',typeof f.imageSizes=="string"&&(k+='[imagesizes="'+dr(f.imageSizes)+'"]')):k+='[href="'+dr(s)+'"]';var A=k;switch(o){case"style":A=Ba(s);break;case"script":A=$a(s)}br.has(A)||(s=m({rel:"preload",href:o==="image"&&f&&f.imageSrcSet?void 0:s,as:o},f),br.set(A,s),g.querySelector(k)!==null||o==="style"&&g.querySelector(tl(A))||o==="script"&&g.querySelector(nl(A))||(o=g.createElement("link"),En(o,"link",s),vn(o),g.head.appendChild(o)))}}function yE(s,o){ps.m(s,o);var f=Pa;if(f&&s){var g=o&&typeof o.as=="string"?o.as:"script",k='link[rel="modulepreload"][as="'+dr(g)+'"][href="'+dr(s)+'"]',A=k;switch(g){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":A=$a(s)}if(!br.has(A)&&(s=m({rel:"modulepreload",href:s},o),br.set(A,s),f.querySelector(k)===null)){switch(g){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(f.querySelector(nl(A)))return}g=f.createElement("link"),En(g,"link",s),vn(g),f.head.appendChild(g)}}}function bE(s,o,f){ps.S(s,o,f);var g=Pa;if(g&&s){var k=aa(g).hoistableStyles,A=Ba(s);o=o||"default";var F=k.get(A);if(!F){var Y={loading:0,preload:null};if(F=g.querySelector(tl(A)))Y.loading=5;else{s=m({rel:"stylesheet",href:s,"data-precedence":o},f),(f=br.get(A))&&Zf(s,f);var le=F=g.createElement("link");vn(le),En(le,"link",s),le._p=new Promise(function(ge,ke){le.onload=ge,le.onerror=ke}),le.addEventListener("load",function(){Y.loading|=1}),le.addEventListener("error",function(){Y.loading|=2}),Y.loading|=4,su(F,o,g)}F={type:"stylesheet",instance:F,count:1,state:Y},k.set(A,F)}}}function vE(s,o){ps.X(s,o);var f=Pa;if(f&&s){var g=aa(f).hoistableScripts,k=$a(s),A=g.get(k);A||(A=f.querySelector(nl(k)),A||(s=m({src:s,async:!0},o),(o=br.get(k))&&em(s,o),A=f.createElement("script"),vn(A),En(A,"link",s),f.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},g.set(k,A))}}function _E(s,o){ps.M(s,o);var f=Pa;if(f&&s){var g=aa(f).hoistableScripts,k=$a(s),A=g.get(k);A||(A=f.querySelector(nl(k)),A||(s=m({src:s,async:!0,type:"module"},o),(o=br.get(k))&&em(s,o),A=f.createElement("script"),vn(A),En(A,"link",s),f.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},g.set(k,A))}}function Lv(s,o,f,g){var k=(k=Q.current)?ru(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=Ba(f.href),f=aa(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=Ba(f.href);var A=aa(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(tl(s)))&&!A._p&&(F.instance=A,F.state.loading=5),br.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},br.set(s,f),A||SE(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=$a(f),f=aa(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 Ba(s){return'href="'+dr(s)+'"'}function tl(s){return'link[rel="stylesheet"]['+s+"]"}function Dv(s){return m({},s,{"data-precedence":s.precedence,precedence:null})}function SE(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}),En(o,"link",f),vn(o),s.head.appendChild(o))}function $a(s){return'[src="'+dr(s)+'"]'}function nl(s){return"script[async]"+s}function Rv(s,o,f){if(o.count++,o.instance===null)switch(o.type){case"style":var g=s.querySelector('style[data-href~="'+dr(f.href)+'"]');if(g)return o.instance=g,vn(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"),vn(g),En(g,"style",k),su(g,f.precedence,s),o.instance=g;case"stylesheet":k=Ba(f.href);var A=s.querySelector(tl(k));if(A)return o.state.loading|=4,o.instance=A,vn(A),A;g=Dv(f),(k=br.get(k))&&Zf(g,k),A=(s.ownerDocument||s).createElement("link"),vn(A);var F=A;return F._p=new Promise(function(Y,le){F.onload=Y,F.onerror=le}),En(A,"link",g),o.state.loading|=4,su(A,f.precedence,s),o.instance=A;case"script":return A=$a(f.src),(k=s.querySelector(nl(A)))?(o.instance=k,vn(k),k):(g=f,(k=br.get(A))&&(g=m({},f),em(g,k)),s=s.ownerDocument||s,k=s.createElement("script"),vn(k),En(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,su(g,f.precedence,s));return o.instance}function su(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 Zf(s,o){s.crossOrigin==null&&(s.crossOrigin=o.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=o.referrerPolicy),s.title==null&&(s.title=o.title)}function em(s,o){s.crossOrigin==null&&(s.crossOrigin=o.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=o.referrerPolicy),s.integrity==null&&(s.integrity=o.integrity)}var iu=null;function Ov(s,o,f){if(iu===null){var g=new Map,k=iu=new Map;k.set(f,g)}else k=iu,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[yo]||A[Qe]||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 Iv(s,o,f){s=s.ownerDocument||s,s.head.insertBefore(f,o==="title"?s.querySelector("head > title"):null)}function wE(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 Mv(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function CE(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=Ba(g.href),A=o.querySelector(tl(k));if(A){o=A._p,o!==null&&typeof o=="object"&&typeof o.then=="function"&&(s.count++,s=au.bind(s),o.then(s,s)),f.state.loading|=4,f.instance=A,vn(A);return}A=o.ownerDocument||o,g=Dv(g),(k=br.get(k))&&Zf(g,k),A=A.createElement("link"),vn(A);var F=A;F._p=new Promise(function(Y,le){F.onload=Y,F.onerror=le}),En(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=au.bind(s),o.addEventListener("load",f),o.addEventListener("error",f))}}var tm=0;function kE(s,o){return s.stylesheets&&s.count===0&&lu(s,s.stylesheets),0<s.count||0<s.imgCount?function(f){var g=setTimeout(function(){if(s.stylesheets&&lu(s,s.stylesheets),s.unsuspend){var A=s.unsuspend;s.unsuspend=null,A()}},6e4+o);0<s.imgBytes&&tm===0&&(tm=62500*iE());var k=setTimeout(function(){if(s.waitingForImages=!1,s.count===0&&(s.stylesheets&&lu(s,s.stylesheets),s.unsuspend)){var A=s.unsuspend;s.unsuspend=null,A()}},(s.imgBytes>tm?50:800)+o);return s.unsuspend=f,function(){s.unsuspend=null,clearTimeout(g),clearTimeout(k)}}:null}function au(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)lu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var ou=null;function lu(s,o){s.stylesheets=null,s.unsuspend!==null&&(s.count++,ou=new Map,o.forEach(jE,s),ou=null,au.call(s))}function jE(s,o){if(!(o.state.loading&4)){var f=ou.get(s);if(f)var g=f.get(null);else{f=new Map,ou.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=au.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 rl={$$typeof:b,Provider:null,Consumer:null,_currentValue:X,_currentValue2:X,_threadCount:0};function EE(s,o,f,g,k,A,F,Y,le){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=fn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=fn(0),this.hiddenUpdates=fn(null),this.identifierPrefix=g,this.onUncaughtError=k,this.onCaughtError=A,this.onRecoverableError=F,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=le,this.incompleteTransitions=new Map}function Pv(s,o,f,g,k,A,F,Y,le,ge,ke,Ae){return s=new EE(s,o,f,F,le,ge,ke,Ae,Y),o=1,A===!0&&(o|=24),A=tr(3,null,null,o),s.current=A,A.stateNode=s,o=Rh(),o.refCount++,s.pooledCache=o,o.refCount++,A.memoizedState={element:g,isDehydrated:f,cache:o},Ph(A),s}function Bv(s){return s?(s=ga,s):ga}function $v(s,o,f,g,k,A){k=Bv(k),g.context===null?g.context=k:g.pendingContext=k,g=Ps(o),g.payload={element:f},A=A===void 0?null:A,A!==null&&(g.callback=A),f=Bs(s,g,o),f!==null&&(Kn(f,s,o),Io(f,s,o))}function zv(s,o){if(s=s.memoizedState,s!==null&&s.dehydrated!==null){var f=s.retryLane;s.retryLane=f!==0&&f<o?f:o}}function nm(s,o){zv(s,o),(s=s.alternate)&&zv(s,o)}function Hv(s){if(s.tag===13||s.tag===31){var o=Si(s,67108864);o!==null&&Kn(o,s,67108864),nm(s,67108864)}}function Uv(s){if(s.tag===13||s.tag===31){var o=ar();o=Se(o);var f=Si(s,o);f!==null&&Kn(f,s,o),nm(s,o)}}var cu=!0;function NE(s,o,f,g){var k=V.T;V.T=null;var A=Z.p;try{Z.p=2,rm(s,o,f,g)}finally{Z.p=A,V.T=k}}function TE(s,o,f,g){var k=V.T;V.T=null;var A=Z.p;try{Z.p=8,rm(s,o,f,g)}finally{Z.p=A,V.T=k}}function rm(s,o,f,g){if(cu){var k=sm(g);if(k===null)Ff(s,o,g,uu,f),Vv(s,g);else if(LE(k,s,o,f,g))g.stopPropagation();else if(Vv(s,g),o&4&&-1<AE.indexOf(s)){for(;k!==null;){var A=ia(k);if(A!==null)switch(A.tag){case 3:if(A=A.stateNode,A.current.memoizedState.isDehydrated){var F=oe(A.pendingLanes);if(F!==0){var Y=A;for(Y.pendingLanes|=2,Y.entangledLanes|=2;F;){var le=1<<31-tt(F);Y.entanglements[1]|=le,F&=~le}Hr(A),(Lt&6)===0&&(Wc=Ie()+500,Qo(0))}}break;case 31:case 13:Y=Si(A,2),Y!==null&&Kn(Y,A,2),Kc(),nm(A,2)}if(A=sm(g),A===null&&Ff(s,o,g,uu,f),A===k)break;k=A}k!==null&&g.stopPropagation()}else Ff(s,o,g,null,f)}}function sm(s){return s=ih(s),im(s)}var uu=null;function im(s){if(uu=null,s=sa(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 uu=s,null}function Fv(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(qe()){case te:return 2;case ae:return 8;case se:case me:return 32;case Ue:return 268435456;default:return 32}default:return 32}}var am=!1,Ys=null,Xs=null,Qs=null,sl=new Map,il=new Map,Js=[],AE="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 Vv(s,o){switch(s){case"focusin":case"focusout":Ys=null;break;case"dragenter":case"dragleave":Xs=null;break;case"mouseover":case"mouseout":Qs=null;break;case"pointerover":case"pointerout":sl.delete(o.pointerId);break;case"gotpointercapture":case"lostpointercapture":il.delete(o.pointerId)}}function al(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=ia(o),o!==null&&Hv(o)),s):(s.eventSystemFlags|=g,o=s.targetContainers,k!==null&&o.indexOf(k)===-1&&o.push(k),s)}function LE(s,o,f,g,k){switch(o){case"focusin":return Ys=al(Ys,s,o,f,g,k),!0;case"dragenter":return Xs=al(Xs,s,o,f,g,k),!0;case"mouseover":return Qs=al(Qs,s,o,f,g,k),!0;case"pointerover":var A=k.pointerId;return sl.set(A,al(sl.get(A)||null,s,o,f,g,k)),!0;case"gotpointercapture":return A=k.pointerId,il.set(A,al(il.get(A)||null,s,o,f,g,k)),!0}return!1}function Gv(s){var o=sa(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,We(s.priority,function(){Uv(f)});return}}else if(o===31){if(o=c(f),o!==null){s.blockedOn=o,We(s.priority,function(){Uv(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 du(s){if(s.blockedOn!==null)return!1;for(var o=s.targetContainers;0<o.length;){var f=sm(s.nativeEvent);if(f===null){f=s.nativeEvent;var g=new f.constructor(f.type,f);sh=g,f.target.dispatchEvent(g),sh=null}else return o=ia(f),o!==null&&Hv(o),s.blockedOn=f,!1;o.shift()}return!0}function Wv(s,o,f){du(s)&&f.delete(o)}function DE(){am=!1,Ys!==null&&du(Ys)&&(Ys=null),Xs!==null&&du(Xs)&&(Xs=null),Qs!==null&&du(Qs)&&(Qs=null),sl.forEach(Wv),il.forEach(Wv)}function hu(s,o){s.blockedOn===o&&(s.blockedOn=null,am||(am=!0,e.unstable_scheduleCallback(e.unstable_NormalPriority,DE)))}var fu=null;function qv(s){fu!==s&&(fu=s,e.unstable_scheduleCallback(e.unstable_NormalPriority,function(){fu===s&&(fu=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(im(g||f)===null)continue;break}var A=ia(f);A!==null&&(s.splice(o,3),o-=3,rf(A,{pending:!0,data:k,method:f.method,action:g},g,k))}}))}function za(s){function o(le){return hu(le,s)}Ys!==null&&hu(Ys,s),Xs!==null&&hu(Xs,s),Qs!==null&&hu(Qs,s),sl.forEach(o),il.forEach(o);for(var f=0;f<Js.length;f++){var g=Js[f];g.blockedOn===s&&(g.blockedOn=null)}for(;0<Js.length&&(f=Js[0],f.blockedOn===null);)Gv(f),f.blockedOn===null&&Js.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[at]||null;if(typeof A=="function")F||qv(f);else if(F){var Y=null;if(A&&A.hasAttribute("formAction")){if(k=A,F=A[at]||null)Y=F.formAction;else if(im(k)!==null)continue}else Y=F.action;typeof Y=="function"?f[g+1]=Y:(f.splice(g,3),g-=3),qv(f)}}}function Kv(){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 om(s){this._internalRoot=s}mu.prototype.render=om.prototype.render=function(s){var o=this._internalRoot;if(o===null)throw Error(r(409));var f=o.current,g=ar();$v(f,g,s,o,null,null)},mu.prototype.unmount=om.prototype.unmount=function(){var s=this._internalRoot;if(s!==null){this._internalRoot=null;var o=s.containerInfo;$v(s.current,2,null,s,null,null),Kc(),o[Zt]=null}};function mu(s){this._internalRoot=s}mu.prototype.unstable_scheduleHydration=function(s){if(s){var o=Oe();s={blockedOn:null,target:s,priority:o};for(var f=0;f<Js.length&&o!==0&&o<Js[f].priority;f++);Js.splice(f,0,s),f===0&&Gv(s)}};var Yv=t.version;if(Yv!=="19.2.4")throw Error(r(527,Yv,"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 RE={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:V,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var pu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!pu.isDisabled&&pu.supportsFiber)try{ct=pu.inject(RE),Je=pu}catch{}}return ll.createRoot=function(s,o){if(!a(s))throw Error(r(299));var f=!1,g="",k=nb,A=rb,F=sb;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=Pv(s,1,!1,null,null,f,g,null,k,A,F,Kv),s[Zt]=o.current,Uf(s),new om(o)},ll.hydrateRoot=function(s,o,f){if(!a(s))throw Error(r(299));var g=!1,k="",A=nb,F=rb,Y=sb,le=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&&(le=f.formState)),o=Pv(s,1,!0,o,f??null,g,k,le,A,F,Y,Kv),o.context=Bv(null),f=o.current,g=ar(),g=Se(g),k=Ps(g),k.callback=null,Bs(f,k,g),f=g,o.current.lanes=f,Pr(o,f),Hr(o),s[Zt]=o.current,Uf(s),new mu(o)},ll.version="19.2.4",ll}var o_;function KE(){if(o_)return hm.exports;o_=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(),hm.exports=qE(),hm.exports}var YE=KE();const XE=_d(YE);function QE(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 gm={exports:{}},xm={};/**
51
51
  * @license React
52
52
  * use-sync-external-store-shim.production.js
53
53
  *
@@ -55,8 +55,8 @@ 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 l_;function JE(){if(l_)return xm;l_=1;var e=Sd();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 xm.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,xm}var c_;function ZE(){return c_||(c_=1,gm.exports=JE()),gm.exports}var eN=ZE();const tN=FE.useInsertionEffect,nN=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",rN=nN?E.useLayoutEffect:E.useEffect,sN=tN||rN,i1=e=>{const t=E.useRef([e,(...n)=>t[0](...n)]).current;return sN(()=>{t[0]=e}),t[1]},iN="popstate",tg="pushState",ng="replaceState",aN="hashchange",u_=[iN,tg,ng,aN],oN=e=>{for(const t of u_)addEventListener(t,e);return()=>{for(const t of u_)removeEventListener(t,e)}},a1=(e,t)=>eN.useSyncExternalStore(oN,e,t),d_=()=>location.search,lN=({ssrSearch:e}={})=>a1(d_,e!=null?()=>e:d_),h_=()=>location.pathname,cN=({ssrPath:e}={})=>a1(h_,e!=null?()=>e:h_),uN=(e,{replace:t=!1,state:n=null}={})=>history[t?ng:tg](n,"",e),dN=(e={})=>[cN(e),uN],f_=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[f_]>"u"){for(const e of[tg,ng]){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,f_,{value:!0})}const hN=(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())?"~"+t:t.slice(e.length)||"/",o1=(e="")=>e==="/"?"":e,fN=(e,t)=>e[0]==="~"?e.slice(1):o1(t)+e,mN=(e="",t)=>hN(m_(o1(e)),m_(t)),m_=e=>{try{return decodeURI(e)}catch{return e}},l1={hook:dN,searchHook:lN,parser:QE,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,t,n)=>e(t,n)},c1=E.createContext(l1),co=()=>E.useContext(c1),u1={},d1=E.createContext(u1),pN=()=>E.useContext(d1),wd=e=>{const[t,n]=e.hook(e);return[mN(e.base,t),i1((r,a)=>e.aroundNav(n,fN(r,e.base),a))]},Tn=()=>wd(co()),rg=(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]},uo=e=>rg(co().parser,e,Tn()[0]),h1=({children:e,...t})=>{var p,m,x;const n=co(),r=t.hook?l1: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=E.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 E.createElement(c1.Provider,{value:a,children:e})},p_=({children:e,component:t},n)=>t?E.createElement(t,{params:n}):typeof e=="function"?e(n):e,gN=e=>{let t=E.useRef(u1);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},cl=({path:e,nest:t,match:n,...r})=>{const a=co(),[l]=wd(a),[u,c,d]=n??rg(a.parser,e,l,t),h=gN({...pN(),...c});if(!u)return null;const p=d?E.createElement(h1,{base:d},p_(r,h)):p_(r,h);return E.createElement(d1.Provider,{value:h,children:p})},Xn=E.forwardRef((e,t)=>{const n=co(),[r,a]=wd(n),{to:l="",href:u=l,onClick:c,asChild:d,children:h,className:p,replace:m,state:x,transition:y,...w}=e,C=i1(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&&E.isValidElement(h)?E.cloneElement(h,{onClick:C,href:_}):E.createElement("a",{...w,onClick:C,href:_,className:p!=null&&p.call?p(r===u):p,children:h,ref:t})}),f1=e=>Array.isArray(e)?e.flatMap(t=>f1(t&&t.type===E.Fragment?t.props.children:t)):[e],xN=({children:e,location:t})=>{const n=co(),[r]=wd(n);for(const a of f1(e)){let l=0;if(E.isValidElement(a)&&(l=rg(n.parser,a.props.path,t||r,a.props.nest))[0])return E.cloneElement(a,{match:l})}return null},g_=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},yN=(e=>e?g_(e):g_),bN=e=>e;function vN(e,t=bN){const n=ai.useSyncExternalStore(e.subscribe,ai.useCallback(()=>t(e.getState()),[e,t]),ai.useCallback(()=>t(e.getInitialState()),[e,t]));return ai.useDebugValue(n),n}const x_=e=>{const t=yN(e),n=r=>vN(t,r);return Object.assign(n,t),n},In=(e=>e?x_(e):x_);function _N(){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 m1=_N();function ks(e){return e.startsWith("/")?`${m1}${e}`||"/":e}async function ve(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 y_(e,t,n){try{return(await ve(`/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 p1(e,t,n){try{const r=await ve(`/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 gu(e,t){return n=>({loading:{...n.loading,[e]:t}})}function b_(e,t){return n=>({settings:{...n.settings,[e]:t},loading:{...n.loading,[e]:!1}})}const sg=[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 Zi(){return{showThinking:Ft(e=>e.settings[Te.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:Ft(e=>e.settings[Te.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:Ft(e=>e.settings[Te.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:Ft(e=>e.settings[Te.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:Ft(e=>e.settings[Te.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true",showSyntaxHighlighting:Ft(e=>e.settings[Te.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING]??"true")==="true",maxVisibleItems:Number(Ft(e=>e.settings[Te.DISPLAY_MAX_VISIBLE_ITEMS]??"300"))}}const Ft=In(e=>({settings:{},loading:{},getSetting:async t=>{e(gu(t,!0));try{const r=await(await ve(`/api/settings/${t}`)).json();return e(b_(t,r.value??"")),r.value}catch{return e(gu(t,!1)),null}},getSettings:async t=>{if(t.length!==0)try{const r=await(await ve(`/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(gu(t,!0));try{const a=await(await ve(`/api/settings/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})})).json();e(b_(t,a.value??""))}catch{e(gu(t,!1))}}})),ul=Object.freeze(Object.defineProperty({__proto__:null,DISPLAY_SETTINGS_KEYS:sg,SETTINGS_KEYS:Te,useDisplaySettings:Zi,useSettingsStore:Ft},Symbol.toStringTag,{value:"Module"}));function SN(){const[e,t]=E.useState({offsetTop:0,height:window.innerHeight,keyboardVisible:!1}),n=E.useRef(window.innerHeight);return E.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 wN(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Uu(){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 CN{constructor(t){_e(this,"ws",null);_e(this,"handlers",new Set);_e(this,"statusHandler",null);_e(this,"baseUrl");_e(this,"isReconnecting",!1);_e(this,"connectingPromise",null);_e(this,"lastCloseCode",0);_e(this,"reconnectAttempts",0);_e(this,"manualReconnectScheduled",!1);_e(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);wN(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=Uu(),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 kN=window.location.protocol==="https:"?"wss:":"ws:";let gp=window.location.port;gp||(gp=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?"10469":window.location.protocol==="https:"?"443":"80");const jN=`${kN}//${window.location.hostname}:${gp}${ks("/ws")}`,Bt=new CN(jN),EN=3e4;function g1(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 Xt=In((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 ve("/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 ve("/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 ve(`/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 ve("/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 ve(`/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()},EN);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}})),Gt=In((e,t)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const r=await(await ve("/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 ve("/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 ve(`/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 ve(`/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 ve(`/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 ve(`/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})}})),fi=async(e,t,n)=>{try{const r=await ve(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"}}},Cd=async(e,t,n)=>{try{const r=await ve(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 x1(e){let t=null;function n(){t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))}return n}let xu=[];const kl=In()((e,t)=>{function n(){if(xu.length===0)return;const a=xu;xu=[],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=x1(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 ve(`/api/sessions/${l}/background-process/${a}/stop`,{method:"POST"})).ok&&t().removeProcess(a)}catch{}},appendLog:(a,l,u)=>{xu.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}}}}}),NN={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Fu=null;function TN(e){Fu=e}function Hi(){return NN}function ym(){Fu==null||Fu()}let yu=[];const Dn=In()((e,t)=>{function n(){if(yu.length===0)return;const a=yu;yu=[],e(l=>({logs:[...l.logs,...a]}))}const r=x1(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 ve(`/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 ve(`/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 ve(`/api/dev-server/logs?workdir=${encodeURIComponent(a)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content,...d.type?{type:d.type}:{}}));e({logs:c})}catch{}},clearLogs:async()=>{const a=t().workdir;if(a)try{await ve(`/api/dev-server/clear-logs?workdir=${encodeURIComponent(a)}`,{method:"POST"}),e({logs:[]})}catch{}},insertMarker:async()=>{const a=t().workdir;if(a)try{await ve(`/api/dev-server/insert-marker?workdir=${encodeURIComponent(a)}`,{method:"POST"}),t().fetchLogs()}catch{}},start:async()=>{const a=t().workdir;if(a)try{const u=await(await ve(`/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 ve(`/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 ve(`/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 ve(`/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;yu.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}}}}}),AN=[{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"}],LN=[{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"}],y1={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"},oi={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},b1={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},xp={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...oi},waiting_for_user:{...oi},phase_done:{...oi},phase_blocked:{...oi},new_message:{...b1}},agentOverrides:{}};function v1(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 Ui=In((e,t)=>({settings:xp,loaded:!1,load:()=>{Ft.getState().getSetting(Te.NOTIFICATION_SETTINGS);const r=Ft.subscribe(l=>{const u=l.settings[Te.NOTIFICATION_SETTINGS];if(u!==void 0)try{const c=JSON.parse(u);e({settings:v_(c),loaded:!0})}catch{e({loaded:!0})}}),a=Ft.getState().settings[Te.NOTIFICATION_SETTINGS];if(a)try{const l=JSON.parse(a);e({settings:v_(l),loaded:!0})}catch{e({loaded:!0})}return r},update:n=>{e({settings:n}),bm(n)},updateEvent:(n,r)=>{const a=t().settings,l={...a,events:{...a.events,[n]:{...a.events[n],...r}}};e({settings:l}),bm(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}),bm(c)}}));function bm(e){Ft.getState().setSetting(Te.NOTIFICATION_SETTINGS,JSON.stringify(e))}function v_(e){var t,n,r,a,l;return{soundEnabled:e.soundEnabled??xp.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??xp.browserNotificationEnabled,events:{complete:{...oi,...(t=e.events)==null?void 0:t.complete},waiting_for_user:{...oi,...(n=e.events)==null?void 0:n.waiting_for_user},phase_done:{...oi,...(r=e.events)==null?void 0:r.phase_done},phase_blocked:{...oi,...(a=e.events)==null?void 0:a.phase_blocked},new_message:{...b1,...(l=e.events)==null?void 0:l.new_message}},agentOverrides:e.agentOverrides??{}}}const __=new Map;function DN(e){let t=__.get(e);return t||(t=new Audio(ks(e)),t.volume=.5,__.set(e,t)),t}let _1=typeof Notification<"u"?Notification.permission:"denied";function RN(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(_1=e,e))}const ON={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},IN={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 MN(e){typeof Notification>"u"||_1==="granted"&&(document.hasFocus()||new Notification(ON[e],{body:IN[e],icon:ks("/fox.svg"),tag:`openfox-${e}`}))}function ql(e,t){const{settings:n}=Ui.getState(),r=v1(n,e,t);if(n.soundEnabled&&r.soundEnabled){const a=r.customSoundUrl??y1[e],l=DN(a);l.currentTime=0,l.play().catch(()=>{})}n.browserNotificationEnabled&&r.browserNotification&&MN(e)}const PN=e=>ql("complete",e),BN=e=>ql("phase_done",e),$N=e=>ql("phase_blocked",e),vm=e=>ql("waiting_for_user",e),zN=e=>ql("new_message",e),S_=new Map;function Ya(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 HN(e,t){if(e.type==="chat.done"){const n=e.payload,r=Ya(t,e.sessionId),a=n.agentType??r;n.reason==="complete"&&PN(a),n.reason==="waiting_for_user"&&vm(a);return}if(e.type==="chat.path_confirmation"){const n=Ya(t,e.sessionId);vm(n);return}if(e.type==="session.confirmation_pending"){const n=Ya(t,e.sessionId);vm(n);return}if(e.type==="task.completed"){const n=Ya(t,e.sessionId);BN(n);return}if(e.type==="phase.changed"&&e.sessionId){const n=e.payload,r=S_.get(e.sessionId)??null;if(S_.set(e.sessionId,n.phase),r===n.phase)return;const a=Ya(t,e.sessionId);n.phase==="blocked"&&$N(a)}}const Dl=In(e=>({servers:[],setServers:t=>e({servers:t}),fetchServers:async()=>{try{const t=await ve("/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{}}})),_m=new Set;function cn(e,t){return t!==null&&e.sessionId===t}function UN(e,t,n){return e.id!==void 0||cn(e,t)||n===!0&&e.sessionId!==void 0}function FN(e,t){return e.includes(t)?e:[...e,t]}function w_(e,t){return e.filter(n=>n!==t)}function VN(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 Sm(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 GN(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 C_(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 k_(e,t,n){var c,d,h,p,m,x,y,w,C,_,S,v,b,j,N,T,D,L,O,M,W,U;const r=n();HN(e,r);const a=((c=r.currentSession)==null?void 0:c.id)??null,l=()=>{const R=e.sessionId;!R||R===a||t(H=>({unreadSessionIds:FN(H.unreadSessionIds,R)}))},u=(R,H,G)=>({messages:R.messages.map(V=>V.id===H?G(V):V)});switch(e.type){case"session.state":{const R=e.payload;if(!UN(e,a,r.pendingSessionCreate))break;const H=n().pendingSessionCreate===!0,G=R.pendingConfirmations??[],V=R.session.id,Z={...n().crossSessionConfirmations};delete Z[V],t({currentSession:R.session,sessions:VN(n().sessions,R.session),unreadSessionIds:w_(n().unreadSessionIds,V),messages:R.messages,hiddenCount:R.hiddenCount??0,currentTodos:[],pendingPathConfirmations:G,crossSessionConfirmations:Z,sessionsWithPendingConfirmations:Object.keys(Z),pendingQuestions:R.pendingQuestions??[],waitingWorkflow:R.waitingWorkflow??null,...H?{pendingSessionCreate:R.session.id}:{}});break}case"session.list":{const R=e.payload;t(H=>({sessions:GN(R.sessions,H.sessions,H.currentSession)}));break}case"session.created":{const R=e.payload;t(H=>({sessions:H.sessions.some(G=>G.id===R.session.id)?H.sessions.map(G=>G.id===R.session.id?{...G,...R.session}:G):[R.session,...H.sessions]}));break}case"session.deleted":{const R=e.payload;t(H=>({unreadSessionIds:w_(H.unreadSessionIds,R.sessionId)})),n().listSessions();break}case"session.deletedAll":{n().listSessions();break}case"session.running":{const R=e.payload;C_(e,t,n,H=>({...H,isRunning:R.isRunning})),R.isRunning||t({abortInProgress:!1,queuedMessages:[]}),R.isRunning&&t({restoredInput:null});break}case"chat.message":{if(!cn(e,((d=n().currentSession)==null?void 0:d.id)??null)){l();break}const R=e.payload;t(H=>{if(H.messages.some(V=>V.id===R.message.id))return H;const G=R.message.role==="user";return{messages:[...H.messages,R.message],sessions:H.sessions.map(V=>V.id===e.sessionId&&G?{...V,messageCount:V.messageCount+1}:V)}});break}case"chat.message_updated":{if(!cn(e,((h=n().currentSession)==null?void 0:h.id)??null)){l();break}const R=e.payload,H=n().messages.find(G=>G.id===R.messageId);R.updates.isStreaming===!1&&(H==null||H.isStreaming),t(G=>({messages:G.messages.map(V=>V.id===R.messageId?{...V,...R.updates}:V)}));break}case"chat.delta":{if(!cn(e,((p=n().currentSession)==null?void 0:p.id)??null)){l();break}const R=e.payload;if(!_m.has(R.messageId)){_m.add(R.messageId);const G=R.subAgentType?"sub-agent":Ya(n(),e.sessionId);zN(G)}const H=Hi();H.messageId=R.messageId,H.deltaContent+=R.content,ym();break}case"chat.thinking":{if(!cn(e,((m=n().currentSession)==null?void 0:m.id)??null)){l();break}const R=e.payload,H=Hi();H.messageId=R.messageId,H.thinkingContent+=R.content,ym();break}case"chat.tool_preparing":{if(!cn(e,((x=n().currentSession)==null?void 0:x.id)??null)){l();break}const R=e.payload;t(H=>{var I;const G=H.messages.find(B=>B.id===R.messageId);if(!G)return{};if((I=G.toolCalls)==null?void 0:I.find((B,q)=>q===R.index))return{};const Z=G.preparingToolCalls??[],X=Z.findIndex(B=>B.index===R.index);let $;return X>=0?$=Z.map((B,q)=>q===X?{...B,arguments:R.arguments}:B):$=[...Z,{index:R.index,name:R.name,...R.arguments?{arguments:R.arguments}:{}}],{messages:H.messages.map(B=>B.id===R.messageId?{...B,preparingToolCalls:$}:B)}});break}case"chat.tool_call":{if(!cn(e,((y=n().currentSession)==null?void 0:y.id)??null)){l();break}const R=e.payload,H=G=>{var I;const V=(G.toolCalls??[]).length,Z=(I=G.preparingToolCalls)==null?void 0:I.filter(B=>B.index!==V),X=Hi(),$=X.toolOutput.filter(B=>B.callId===R.callId);return $.length>0&&(X.toolOutput=X.toolOutput.filter(B=>B.callId!==R.callId)),{...G,toolCalls:[...G.toolCalls??[],{id:R.callId,name:R.tool,arguments:R.args,startedAt:Date.now(),...$.length>0?{streamingOutput:$.map(B=>({stream:B.stream,content:B.content,timestamp:Date.now()}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};t(G=>u(G,R.messageId,H));break}case"chat.tool_output":{if(!cn(e,((w=n().currentSession)==null?void 0:w.id)??null)){l();break}const R=e.payload,H=Hi();H.messageId=R.messageId,H.toolOutput.push({messageId:R.messageId,callId:R.callId,stream:R.stream,content:R.output}),ym();break}case"chat.tool_result":{if(!cn(e,((C=n().currentSession)==null?void 0:C.id)??null)){l();break}const R=e.payload,H=G=>{var Z;const V=(Z=G.toolCalls)==null?void 0:Z.map(X=>X.id===R.callId?{...X,result:R.result}:X);return{...G,toolCalls:V}};t(G=>u(G,R.messageId,H));break}case"chat.vision_fallback":{if(!cn(e,((_=n().currentSession)==null?void 0:_.id)??null)){l();break}const R=e.payload;t(H=>{const G=`${R.messageId}-${R.attachmentId}`,V={...H.visionFallbackByMessage};return V[G]={type:R.type,attachmentId:R.attachmentId,filename:R.filename,description:R.description},{visionFallbackByMessage:V}});break}case"chat.todo":{if(!cn(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(!cn(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(!cn(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(!cn(e,((j=n().currentSession)==null?void 0:j.id)??null)){l();break}const R=Hi();R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[],_m.delete(e.payload.messageId);const H=e.payload,G=H.stats;t(V=>({messages:V.messages.map(Z=>Z.id===H.messageId?{...Z,isStreaming:!1,stats:G??Z.stats,completeReason:H.reason,preparingToolCalls:void 0}:Z),visionFallbackByMessage:{}}));break}case"chat.error":{if(!cn(e,((N=n().currentSession)==null?void 0:N.id)??null)){l();break}const R=Hi(),H=e.payload;console.error("Chat error:",H.error,"recoverable:",H.recoverable),H.recoverable||(R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[]),t(G=>({error:{code:"CHAT_ERROR",message:H.error},...H.recoverable?{}:{messages:G.messages}}));break}case"chat.path_confirmation":{const R=e.sessionId,H=R===(((T=n().currentSession)==null?void 0:T.id)??null),G=e.payload,V={callId:G.callId,tool:G.tool,paths:G.paths,workdir:G.workdir,reason:G.reason};if(!H){l(),R&&t(Z=>({crossSessionConfirmations:{...Z.crossSessionConfirmations,[R]:Sm(Z.crossSessionConfirmations[R]??[],V)},sessionsWithPendingConfirmations:Z.sessionsWithPendingConfirmations.includes(R)?Z.sessionsWithPendingConfirmations:[...Z.sessionsWithPendingConfirmations,R]}));break}t(Z=>({pendingPathConfirmations:Sm(Z.pendingPathConfirmations,V)}));break}case"session.confirmation_pending":{const R=e.sessionId,H=e.payload,G={callId:H.callId,tool:H.tool,paths:H.paths,workdir:H.workdir,reason:H.reason};R&&t(V=>({crossSessionConfirmations:{...V.crossSessionConfirmations,[R]:Sm(V.crossSessionConfirmations[R]??[],G)},sessionsWithPendingConfirmations:V.sessionsWithPendingConfirmations.includes(R)?V.sessionsWithPendingConfirmations:[...V.sessionsWithPendingConfirmations,R]}));break}case"session.confirmation_resolved":{const R=e.sessionId,H=e.payload;R&&t(G=>{const Z=(G.crossSessionConfirmations[R]??[]).filter($=>$.callId!==H.callId),X={...G.crossSessionConfirmations};return Z.length===0?delete X[R]:X[R]=Z,{crossSessionConfirmations:X,sessionsWithPendingConfirmations:Object.keys(X)}});break}case"chat.ask_user":{if(!cn(e,((D=n().currentSession)==null?void 0:D.id)??null)){l();return}const R=e.payload,H={callId:R.callId,question:R.question,type:R.type??"text",options:R.options??void 0};t(G=>({pendingQuestions:[...G.pendingQuestions.filter(V=>V.callId!==R.callId),H]}));break}case"mode.changed":{if(!cn(e,((L=n().currentSession)==null?void 0:L.id)??null)){l();break}const R=e.payload;t(H=>({currentSession:H.currentSession?{...H.currentSession,mode:R.mode}:null}));break}case"phase.changed":{const R=e.payload;C_(e,t,n,H=>({...H,phase:R.phase})),R.phase!=="waiting"&&t({waitingWorkflow:null});break}case"workflow.waiting":{const R=e.payload;t({waitingWorkflow:R});break}case"criteria.updated":{if(!cn(e,((O=n().currentSession)==null?void 0:O.id)??null)){l();break}const R=e.payload;t(H=>({currentSession:H.currentSession?{...H.currentSession,criteria:R.criteria}:null}));break}case"metadata.updated":{if(!cn(e,((M=n().currentSession)==null?void 0:M.id)??null)){l();break}const R=e.payload;t(H=>({currentSession:H.currentSession?{...H.currentSession,metadataEntries:{...H.currentSession.metadataEntries,[R.key]:R.entries}}:null}));break}case"context.state":{const R=e.payload,H=cn(e,((W=n().currentSession)==null?void 0:W.id)??null);R.subAgentId?H&&n().updateSubAgentContextState(R.subAgentId,R.context):H?t({contextState:R.context}):l();break}case"session.name_generated":{const R=e.payload,H=e.sessionId,G=(U=n().currentSession)==null?void 0:U.id;t(V=>{const Z=V.sessions.map($=>$.id===H?{...$,title:R.name,updatedAt:new Date().toISOString()}:$),X=G===H?V.currentSession?{...V.currentSession,title:R.name,updatedAt:new Date().toISOString()}:null:V.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 H=[...R.servers].sort((G,V)=>G.name.localeCompare(V.name));Dl.getState().setServers(H)}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":{Dn.getState().handleMessage(e);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{kl.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 dl=!1,Ur=null;const wm=new Set,bu=new Map;function j_(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 E_(e,t,n,r,a){try{const u=await(await ve(`/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 Le=In((e,t)=>(TN(()=>{const n=Hi();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=j_(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:j_(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,waitingWorkflow: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 ve("/api/auth")).json()).requiresAuth}catch{}if(r&&!Bt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Bt.onStatusChange(a=>{var l;if(e({connectionStatus:a}),a==="connected"){t().listSessions(void 0),Gt.getState().listProjects();const u=(l=t().currentSession)==null?void 0:l.id;u&&t().loadSession(u)}});try{await Bt.connect(),dl||(dl=!0,Ur=Bt.subscribe(a=>{k_(a,e,t)}))}catch(a){console.error("Failed to connect:",a);const l=Bt.getLastCloseCode();if(!Bt.hasToken()&&(l===1006||l===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}Ur&&(Ur(),Ur=null),dl=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Bt.disconnect(),Ur&&(Ur(),Ur=null),dl=!1,e({connectionStatus:"disconnected"}),t().connect()},disconnect:()=>{Bt.disconnect(),Ur&&(Ur(),Ur=null),dl=!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();Bt.setToken(a),e({showPasswordModal:!1}),t().connect();const{listProjects:l}=Gt.getState(),{fetchConfig:u}=Xt.getState();l(),u(),t().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Bt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(n,r)=>{if(t().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const l=await ve("/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{Bt.send("session.load",{sessionId:u.session.id})}catch{}return u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async n=>{if(!wm.has(n)){wm.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 ve(`/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)}),Bt.send("session.load",{sessionId:n});try{const d=await ve(`/api/sessions/${n}/background-processes`);if(d.ok){const h=await d.json();kl.getState().setProcesses(h.processes??[])}}catch{}}catch{}finally{wm.delete(n)}}},listSessions:async(n,r=20)=>{const a=n??"global";if(bu.has(a))return bu.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 ve(`/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{bu.delete(a)}})();return bu.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 ve(`/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 ve(`/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 ve(`/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 ve(`/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 ve(`/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 ve(`/api/sessions/${n}/stop`,{method:"POST"})).json();if(l.queuedMessages&&l.queuedMessages.length>0){const u=l.queuedMessages.map(c=>c.content).join(`
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 ve(`/api/sessions/${n}/continue`,{method:"POST"})}catch(a){console.error("Error continuing generation:",a)}},launchWorkflow:(n,r,a,l,u)=>{const c={};n!=null&&n.trim()&&(c.content=n),r&&r.length>0&&(c.attachments=r),a&&(c.workflowId=a),l&&(c.subGroup=l),u&&(c.params=u),Bt.send("runner.launch",c)},continueWorkflow:()=>{const r=t().waitingWorkflow;r&&Bt.send("runner.launch",{workflowId:r.workflowId,resumeFrom:r.stepId,stepOutput:r.stepOutput})},switchMode:async n=>{var a;const r=(a=t().currentSession)==null?void 0:a.id;if(r)try{const l=await ve(`/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 ve(`/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 ve(`/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:()=>{Bt.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 ve(`/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 ve(`/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 ve(`/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 E_(l,n,r,a,e)},queueCompletion:async(n,r,a)=>{var u;const l=(u=t().currentSession)==null?void 0:u.id;l&&await E_(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 ve(`/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}),Bt.send("context.applyDynamic",{}))},handleServerMessage:n=>{k_(n,e,t)}}));function kd(){return Le(e=>{var t;return((t=e.currentSession)==null?void 0:t.isRunning)??!1})}function WN(){return Le(e=>e.abortInProgress)}function qN(){const e=Le(a=>a.connect),t=Le(a=>a.connectionStatus),n=Ui(a=>a.load),r=uo("/p/:projectId/s/:sessionId/readonly")[0];return E.useEffect(()=>{r||e()},[e,r]),E.useEffect(()=>{r||t==="connected"&&n()},[t,n,r]),{connectionStatus:t}}const KN="modulepreload",YN=function(e){return"/"+e},N_={},ee=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=YN(h),h in N_)return;N_[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":KN,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)})},XN=[{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"}],QN=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"}]'),S1={tokens:XN,presets:QN},w1=S1.tokens,$n=S1.presets;function T_(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}function JN(){try{const e=localStorage.getItem("openfox:systemThemePrefs");if(e)return JSON.parse(e)}catch{}return{darkPreset:"dark",lightPreset:"light"}}const Pt=In((e,t)=>{const n=JN();return{currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:T_(),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($n.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=$n.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=$n.find(p=>p.id===r))==null?void 0:c.tokens)??{},...a};if(l)return{...w1.reduce((h,p)=>({...h,[p.key]:p.defaultValue}),{}),...a};const u=$n.find(h=>h.id===t().currentPreset);return(u==null?void 0:u.tokens)??((d=$n[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 ee(async()=>{const{useSettingsStore:l}=await Promise.resolve().then(()=>ul);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}),ee(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ul);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=$n.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:T_()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(t().userPresets)),ee(async()=>{const{useSettingsStore:r}=await Promise.resolve().then(()=>ul);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})),ee(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ul);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})),ee(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ul);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 ZN({canLoad:e,projectId:t,currentProjectId:n}){const r=Gt(u=>u.loadProject),a=Le(u=>u.listSessions),l=Le(u=>u.clearSession);E.useEffect(()=>{e&&t&&(n!==t&&r(t),a(t),l())},[e,t,n,r,a,l])}function eT({canLoad:e,projectId:t,sessionId:n,currentProjectId:r,currentSessionId:a}){const l=Le(h=>h.loadSession),u=Gt(h=>h.loadProject),c=Le(h=>h.listSessions),d=Le(h=>h.pendingSessionCreate);E.useEffect(()=>{e&&t&&r!==t&&u(t)},[e,t,r,u]),E.useEffect(()=>{e&&n&&a!==n&&l(n),e&&t&&c(t)},[e,n,a,l,c,d,t])}function tT({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 C1({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 nT({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 rT({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 Ki({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 Mr({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 k1({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 hn(e){return i.jsx(k1,{direction:"down",...e})}function sT(e){return i.jsx(k1,{direction:"up",...e})}function iT({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 Rl({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 j1({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 E1({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 ig({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 Rr({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 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:"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 oT({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 lT({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 ag({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 cT({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 A_({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 N1({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 T1({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 A1({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 Xr({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 uT({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 jd({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 dT({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 hT({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 L1({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 D1({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 og({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 fT({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 mT({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 ea({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 Xi({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 pT({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 yp({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 lg({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 gT({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 xT({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 L_({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 bp(){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 D_(e,t){const n=Bt.ws;!n||n.readyState!==WebSocket.OPEN||n.send(JSON.stringify({id:bp(),type:e,payload:t}))}const Lr=In((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 ve(`/api/terminals?projectId=${encodeURIComponent(n)}`);if(r.ok){const a=await r.json();e({sessions:a});const l=Bt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of a)l.send(JSON.stringify({id:bp(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(r){console.error("Failed to fetch terminals:",r)}},createSession:async(n,r)=>{try{const a=await ve("/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=Bt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:bp(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(a){console.error("Failed to create terminal:",a)}},writeSession:(n,r)=>{D_("terminal.write",{sessionId:n,data:r})},resizeSession:(n,r,a)=>{D_("terminal.resize",{sessionId:n,cols:r,rows:a})},killSession:async n=>{try{(await ve(`/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}}}}));Bt.subscribe(e=>{var t;(t=e.type)!=null&&t.startsWith("terminal.")&&Lr.getState().handleMessage(e)});const Cs=In((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"})}}}})),Wr={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 vp(e){if(!e)return structuredClone(Wr);try{const t=JSON.parse(e),n=r=>t[r]===void 0?structuredClone(Wr[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(Wr)}}function R_(e){return e.code.startsWith("Digit")?e.code.slice(-1):/^[a-zA-Z]$/.test(e.key)?e.key.toLowerCase():e.key}function Xu(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 yT(e){return e.type==="double-press"}function R1(e){return e.type==="chord"}function bT(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 O1(e,t){const n=t.modifiers.includes("ctrl"),r=t.modifiers.includes("meta"),a=t.modifiers.includes("alt"),l=t.modifiers.includes("shift");return bT(e,t.key)&&e.ctrlKey===n&&e.metaKey===r&&e.altKey===a&&e.shiftKey===l}function Kl(){const e=Ft(t=>t.settings[Te.KEYBINDINGS]);return vp(e)}function vT(e,t,n){const r=E.useRef(0),a=E.useRef(t);a.current=t,E.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 _T(e,t){const n=E.useRef(t);n.current=t,E.useEffect(()=>{if(!e)return;const r=a=>{O1(a,e)&&(a.preventDefault(),n.current())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e])}function Ol(e,t,n){vT(e&&yT(e)?e:void 0,t,n),_T(e&&R1(e)?e:void 0,t)}function ST(e,t,n){const r=E.useRef(n);r.current=n,E.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&&R1(c)&&O1(l,c)){l.preventDefault(),r.current(d.id);return}}};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,t])}var mi=s1();const Ed=E.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})})}));Ed.displayName="IconButton";const wT="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",ci=E.forwardRef((e,t)=>i.jsx(Ed,{ref:t,icon:wT,title:"Edit",...e}));ci.displayName="EditButton";const CT="M6 18L18 6M6 6l12 12",cg=E.forwardRef((e,t)=>i.jsx(Ed,{ref:t,icon:CT,...e}));cg.displayName="CloseButton";const kT={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 jt({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]=E.useState(!1),_=h!==void 0,S=_?h:w,v=E.useCallback(()=>{_||C(!0)},[_]),b=E.useCallback(()=>{_||C(!1),d==null||d()},[_,d]);E.useEffect(()=>{if(!S||!m)return;const N=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",N),()=>document.removeEventListener("keydown",N)},[S,b,m]);const j=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:[j,S&&(typeof document<"u"?mi.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 ${kT[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(cg,{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 jT({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:LN.map(({url:l,label:u})=>i.jsx("option",{value:l,title:u,children:u.split(" ")[0]},l))}),i.jsx(hn,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const O_=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function ET(){const e=Ui(d=>d.settings),t=Ui(d=>d.update),n=Ui(d=>d.updateEvent),r=Ui(d=>d.updateAgentOverride),a=Ui(d=>d.load);E.useEffect(()=>{a()},[a]);const l=async()=>{await RN()==="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(I_,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>t({...e,soundEnabled:d})}),i.jsx(I_,{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"}),O_.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:AN.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})}),O_.map(h=>{const p=v1(e,d.key,h.key==="general"?void 0:h.key),m=y1[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(jT,{value:p.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:x=>c(h.key,d.key,x)})]})},h.key)})]},d.key))})]})})]})]})}function I_({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 rt=E.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})});rt.displayName="Button";async function M_(e,t,n){try{const r=await ve(e,t);return r.ok?(await n(),{success:!0}):{success:!1,error:(await r.json()).error}}catch{return{success:!1,error:"Network error"}}}const Nn=In((e,t)=>({defaults:[],userItems:[],projectItems:[],items:[],selectedDirectory:null,diagnostics:[],loading:!1,fetchSkills:async()=>{e({loading:!0});try{const r=await(await ve("/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 ve(`/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 ve(`/api/skills/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/skills/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createSkill:async(n,r)=>{const a=await fi("POST","/api/skills",{...n,destination:r});return a.success&&await t().fetchSkills(),a},updateSkill:async(n,r)=>{const a=await fi("PUT",`/api/skills/${n}`,r);return a.success&&await t().fetchSkills(),a},deleteSkill:async n=>{try{const r=await ve(`/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)=>Cd(`/api/skills/${n}/duplicate`,()=>t().fetchSkills(),r),selectDirectory:async n=>M_("/api/skills/library",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})},t().fetchSkills),removeDirectory:async()=>{await ve("/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 M_("/api/skills/install",{method:"POST",body:r},t().fetchSkills)}}));function Yl(){const[e,t]=E.useState({id:null,type:null}),n=E.useCallback(l=>t({id:l,type:"delete"}),[]),r=E.useCallback(()=>t({id:null,type:null}),[]),a=E.useCallback((l,u)=>e.id===l&&e.type===u,[e.id,e.type]);return{requestDelete:n,clearConfirm:r,isConfirming:a}}function Qu({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 Ju({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(ea,{})})}function Il({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(Rl,{})})}function Cr({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 NT({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(rt,{variant:"secondary",onClick:e,children:"Cancel"}),i.jsx(rt,{variant:"primary",onClick:t,disabled:n||r,children:n?"Saving...":"Save"})]})}function eo({message:e}){return i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Nd({value:e,onChange:t}){return 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:e,onChange:n=>t(n.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/)"})]})]})}function I1({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(rt,{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 M1({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 P1({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(rt,{variant:"primary",size:"sm",onClick:t,children:n})})]})}function ug({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 B1({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(Cr,{label:n,value:e,onChange:h,placeholder:a,hint:u}),i.jsx(Cr,{label:r,value:t,onChange:p,readOnly:c,placeholder:l,hint:c?d:void 0,mono:!0})]})}function $1(e={}){const{initialData:t={}}=e,[n,r]=E.useState("list"),[a,l]=E.useState(null),[u,c]=E.useState(""),[d,h]=E.useState(!1),[p,m]=E.useState(t),x=E.useCallback(()=>{m(t),c(""),l(null)},[t]),y=E.useCallback(S=>{r(S),S==="list"&&x()},[x]),w=E.useCallback(S=>{m(v=>typeof S=="function"?S(v):S)},[]),C=E.useCallback((S,v={})=>{l(S),r("edit"),m({...v}),c("")},[]),_=E.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 Ml({isOpen:e,onClose:t,onConfirm:n,title:r,message:a,confirmLabel:l="Confirm",confirmVariant:u="primary",disabled:c=!1}){return i.jsx(jt,{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(rt,{variant:"secondary",onClick:t,disabled:c,children:"Cancel"}),i.jsx(rt,{variant:u,onClick:n,disabled:c,autoFocus:!0,children:l})]})]})})}const TT={sm:"w-4 h-4",md:"w-8 h-8",lg:"w-12 h-12"};function pi({size:e="md",className:t=""}){return i.jsx("div",{className:`animate-spin border-2 border-accent-primary border-t-transparent rounded-full ${TT[e]} ${t}`})}function AT({text:e,...t}){return i.jsxs("div",{className:"text-center",children:[i.jsx(pi,{...t,className:"mx-auto mb-4"}),e&&i.jsx("div",{className:"text-text-secondary",children:e})]})}function z1(e){return e.split(/[\\/]/).filter(Boolean).pop()??""}function LT(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 H1(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 ui=E.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}));ui.displayName="Input";function Td({onSelect:e,onClose:t,initialPath:n}){const[r,a]=E.useState(null),[l,u]=E.useState(!0),[c,d]=E.useState(""),[h,p]=E.useState(-1),m=E.useRef(null),x=E.useRef(null),y=E.useCallback(async b=>{u(!0),d(""),p(-1);try{const j=b?`/api/directories?path=${encodeURIComponent(b)}`:"/api/directories",T=await(await ve(j)).json();a(T)}catch(j){console.error("Failed to load directories:",j)}finally{u(!1)}},[]);E.useEffect(()=>{y(n)},[n,y]);const w=LT((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}))];E.useEffect(()=>{p(c?0:-1)},[c,C.length]),E.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 j;if(b.key==="ArrowDown")b.preventDefault(),p(N=>Math.min(N+1,_.length-1));else if(b.key==="ArrowUp")b.preventDefault(),p(N=>Math.max(N-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(""),(j=m.current)==null||j.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(jt,{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,j)=>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 ${j===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(Xi,{})}),i.jsx(ui,{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(pi,{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,j)=>i.jsxs("div",{"data-index":j,className:`group flex items-center ${j===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(tT,{className:"w-5 h-5 text-text-muted shrink-0"}):i.jsx(Rr,{className:"w-5 h-5 shrink-0"}),i.jsx("span",{className:"truncate",children:b.name}),b.type==="dir"&&i.jsx(hn,{className:`w-5 h-5 text-text-muted shrink-0 ml-1 ${j===h?"opacity-100":"opacity-0 group-hover:opacity-100"}`,rotate:-90})]}),b.type==="dir"&&i.jsx("button",{"data-select":"true",tabIndex:j===h?0:-1,onClick:N=>{N.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 ${j===h?"opacity-100":"opacity-0 group-hover:opacity-100"}`,"aria-label":`Select ${b.name}`,children:"Select"})]},b.path))})})]})})}function U1(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 DT(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 U1(r,t.map(a=>({path:a.webkitRelativePath.slice(r.length+1),file:a})))}function RT(e){return new Promise((t,n)=>e.file(t,n))}async function F1(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?F1(l,u):[{path:u,file:await RT(l)}]}))).flat()}async function OT(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 U1(n.name,await F1(n))}function IT({selectedDirectory:e,onSelect:t,onRemove:n,onRefresh:r,onInstall:a}){const[l,u]=E.useState(!1),[c,d]=E.useState(!1),[h,p]=E.useState(""),[m,x]=E.useState(null),[y,w]=E.useState(!1),C=E.useRef(null);E.useEffect(()=>{var j;(j=C.current)==null||j.setAttribute("webkitdirectory","")},[]);const _=j=>{x(j)},S=async()=>{if(!m||y)return;w(!0);const j=await t(m);if(j&&!j.success){p(j.error??"Cannot use selected folder."),w(!1);return}x(null),u(!1),w(!1)},v=async j=>{d(!0),p("");const N=await a(j);d(!1),N.success||p(N.error??"Failed to install skill package.")},b=async j=>{if(j.preventDefault(),!(!(e!=null&&e.available)||c))try{await v(await OT(j.dataTransfer))}catch(N){p(N instanceof Error?N.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(rt,{variant:"secondary",onClick:()=>u(!0),children:"Change folder"}),e&&i.jsxs(i.Fragment,{children:[i.jsx(rt,{variant:"secondary",onClick:r,children:"Refresh"}),e.custom&&i.jsx(rt,{variant:"secondary",onClick:n,children:"Use default"})]})]})]}),i.jsx("button",{type:"button",disabled:!(e!=null&&e.available)||c,onClick:()=>{var j;return(j=C.current)==null?void 0:j.click()},onDragOver:j=>j.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:j=>{var N;if((N=j.target.files)!=null&&N.length)try{v(DT(j.target.files))}catch(T){p(T instanceof Error?T.message:"Invalid skill folder.")}finally{j.target.value=""}}}),h&&i.jsx("p",{className:"mt-2 text-xs text-error",children:h}),l&&i.jsx(Td,{initialPath:(e==null?void 0:e.resolvedPath)??void 0,onSelect:_,onClose:()=>u(!1)}),i.jsx(Ml,{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 Kr({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 V1({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(ig,{})}),i.jsx(Il,{onClick:a}),!e&&r&&i.jsx(ci,{onClick:r}),!e&&l&&(t?i.jsx(Qu,{onConfirm:()=>{l==null||l()},onCancel:()=>u==null?void 0:u()}):i.jsx(Ju,{onClick:()=>l==null?void 0:l()})),c]})]})}function MT({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(V1,{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 P_({skill:e,isBuiltIn:t,isConfirmingDelete:n,onView:r,onEdit:a,onDuplicate:l,onDelete:u,onToggle:c,readOnly:d=!1}){return i.jsx(MT,{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(Kr,{enabled:e.enabled,onClick:c,label:`Activation for ${e.name}`})})}function PT({skill:e,deleting:t,error:n,onClose:r,onConfirm:a}){return i.jsxs(jt,{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(rt,{variant:"secondary",onClick:r,disabled:t,children:"Cancel"}),i.jsx(rt,{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 BT({isOpen:e}){const t=Nn(J=>J.defaults),n=Nn(J=>J.userItems),r=Nn(J=>J.projectItems),a=Nn(J=>J.items),l=Nn(J=>J.selectedDirectory),u=Nn(J=>J.diagnostics),c=Nn(J=>J.loading),d=Nn(J=>J.fetchSkills),h=Nn(J=>J.fetchSkill),p=Nn(J=>J.fetchDefaultContent),m=Nn(J=>J.createSkill),x=Nn(J=>J.updateSkill),y=Nn(J=>J.deleteSkill),w=Nn(J=>J.selectDirectory),C=Nn(J=>J.removeDirectory),_=Nn(J=>J.installSkill),S=Nn(J=>J.toggleSkill),[v,b]=E.useState(null),[j,N]=E.useState(!1),[T,D]=E.useState(""),{view:L,editingId:O,formError:M,saving:W,formData:U,setView:R,setEditingId:H,setFormError:G,setFormData:V,setSaving:Z}=$1(),{clearConfirm:X}=Yl();E.useEffect(()=>{e&&(d(),R("list"),H(null),X())},[e,d,X]);const $=(J,ie,he,ce)=>{V({name:ce??J.metadata.name,id:he??J.metadata.id,description:J.metadata.description??"",version:J.metadata.version??"1.0.0",prompt:J.prompt,isReadOnly:ie,destination:"user"})},I=async J=>{if(t.some(he=>he.id===J)){const he=await p(J);if(!he)return;$(he,!0),H(J),G(""),R("edit")}else{const he=await h(J);if(!he)return;$(he,!0),H(J),G(""),R("edit")}},B=async J=>{const he=t.some(De=>De.id===J)?await p(J):await h(J);if(!he)return;const ce=`${J}-copy-${Date.now()}`;$(he,!1,ce,`${he.metadata.name} (copy)`),H(null),G(""),R("edit")},q=()=>{V({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1,destination:"user"}),R("edit")},z=async J=>{const ie=await h(J);ie&&($(ie,!1),H(J),G(""),R("edit"))},ne=async()=>{if(!v)return;N(!0),D("");const J=await y(v.id);if(N(!1),!J.success){D(J.error??"Failed to delete skill.");return}await d(),b(null),X()},re=async()=>{const J=O??U.id;if(!J||!U.name||!U.prompt){G("Name, ID, and prompt are required.");return}Z(!0),G("");const ie={metadata:{id:J,name:U.name,description:U.description,version:U.version},prompt:U.prompt},he=O?await x(O,ie):await m(ie,U.destination);if(Z(!1),!he.success){G(he.error??"Failed to save skill.");return}R("list")},Q=J=>{V(ie=>({...ie,name:J})),O||V(ie=>({...ie,id:J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},K=U.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?U.name:O?"Edit Skill":"New Skill"}),i.jsx("button",{onClick:()=>R("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),M&&i.jsx(eo,{message:M}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(B1,{name:U.name,id:U.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:Q,onIdChange:()=>{}}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Description",value:U.description,onChange:J=>V(ie=>({...ie,description:J})),placeholder:"What this skill does...",readOnly:K}),i.jsx(Cr,{label:"Version",value:U.version,onChange:J=>V(ie=>({...ie,version:J})),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:U.prompt,onChange:J=>V(ie=>({...ie,prompt:J.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"})]}),!O&&i.jsx(Nd,{value:U.destination,onChange:J=>V(ie=>({...ie,destination:J}))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[i.jsx(rt,{variant:"secondary",onClick:()=>R("list"),children:"Cancel"}),K?i.jsx(rt,{variant:"primary",onClick:()=>{V(J=>({...J,name:J.name+" (copy)",id:`${O}-copy-${Date.now()}`,isReadOnly:!1})),H(null)},children:"Duplicate & Customize"}):i.jsx(rt,{variant:"primary",onClick:re,disabled:W||!U.name||!U.id||!U.prompt,children:W?"Saving...":"Save"})]})]});function P({items:J}){return J.map(ie=>i.jsx(P_,{skill:ie,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>I(ie.id),onEdit:()=>z(ie.id),onDuplicate:()=>B(ie.id),onDelete:()=>{D(""),b(ie)},onToggle:()=>S(ie.id),readOnly:ie.readOnly},ie.id))}return i.jsxs("div",{children:[i.jsx(PT,{skill:v,deleting:j,error:T,onClose:()=>{j||b(null)},onConfirm:ne}),i.jsx(IT,{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((J,ie)=>i.jsx("p",{children:J},`${J}-${ie}`))}),i.jsx(P1,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:q}),i.jsxs(ug,{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(J=>i.jsx(P_,{skill:J,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>I(J.id),onDuplicate:()=>B(J.id),onToggle:()=>S(J.id)},J.id))})]}),n.length>0&&i.jsx(M1,{children:i.jsx(P,{items:n})}),a.some(J=>["global-shared","selected","project-shared"].includes(J.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(P,{items:a.filter(J=>["global-shared","selected","project-shared"].includes(J.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(P,{items:r})})]})]})]})}function ta(){const e=Ft(a=>a.settings),t=Ft(a=>a.loading),n=Ft(a=>a.getSetting),r=Ft(a=>a.setSetting);return{settings:e,loading:t,getSetting:n,setSetting:r}}function $T({isOpen:e}){const{settings:t,loading:n,getSetting:r,setSetting:a}=ta(),l=t[Te.GLOBAL_INSTRUCTIONS]??"",u=n[Te.GLOBAL_INSTRUCTIONS]??!1,[c,d]=E.useState(l),[h,p]=E.useState(!1),[m,x]=E.useState(!1);E.useEffect(()=>{e&&r(Te.GLOBAL_INSTRUCTIONS)},[e,r]),E.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(rt,{variant:"secondary",onClick:w,disabled:!h,children:"Discard"}),i.jsx(rt,{variant:"primary",onClick:y,disabled:!h||C,children:m?"Saving...":"Save"})]})]})}function zT(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 Vu(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 HT({isOpen:e,isNew:t,basePresetId:n,presetName:r,mode:a,initialTokens:l,onClose:u,onSave:c}){const[d,h]=E.useState(l),[p,m]=E.useState(r),[x,y]=E.useState(a);E.useEffect(()=>{h(l),m(r)},[l,r]);const w=(b,j)=>{const N=j.startsWith("#")?zT(j):j;h(T=>({...T,[b]:N}))},C=()=>{c(p.trim()||"Untitled",{...d},x)},_=w1.reduce((b,j)=>{const N=j.category;return b[N]||(b[N]=[]),b[N].push(j),b},{}),S={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},v=$n.find(b=>b.id===n);return i.jsx(jt,{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,j])=>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:j.map(N=>i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("label",{htmlFor:N.key,className:"text-xs text-text-muted",children:N.label}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"color",id:N.key,value:Vu(d[N.key]??N.defaultValue),onChange:T=>w(N.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[N.key]??N.defaultValue,onChange:T=>w(N.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"})]})]},N.key))})]},b))]})})}function B_({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":Vu(e.tokens["color-bg-primary"]??"#000"),borderColor:Vu(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:Vu(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 UT(){const[e,t]=E.useState(null),n=Pt(U=>U.currentPreset),r=Pt(U=>U.isCustom),a=Pt(U=>U.basePreset),l=Pt(U=>U.isSystem),u=Pt(U=>U.systemDarkPreset),c=Pt(U=>U.systemLightPreset),d=Pt(U=>U.applyPreset),h=Pt(U=>U.applyUserPreset),p=Pt(U=>U.deleteUserPreset),m=Pt(U=>U.saveTheme),x=Pt(U=>U.setSystemDarkPreset),y=Pt(U=>U.setSystemLightPreset),w=Pt(U=>U.activeUserPresetId),C=Pt(U=>U.userPresets),_=$n.filter(U=>U.mode==="dark"),S=$n.filter(U=>U.mode==="light"),v=U=>{var R;if(l){const H=C[U];if(!H)return;const G=H.mode??((R=$n.find(V=>V.id===H.basePreset))==null?void 0:R.mode);G==="dark"?x(H.id):G==="light"&&y(H.id)}else h(U)},b=U=>{const R=$n.find(H=>H.id===U);R&&t({type:"new",presetIndex:C.length,basePresetId:U,presetName:R.name+" Copy",mode:R.mode??"dark",tokens:{...R.tokens}})},j=U=>{const R=C[U];if(!R)return;const H=$n.find(V=>V.id===R.basePreset),G=H?{...H.tokens,...R.tokens}:R.tokens;t({type:"edit",presetIndex:U,basePresetId:R.basePreset,presetName:R.name,mode:R.mode??"dark",tokens:G})},N=(U,R,H)=>{if(!e)return;const G=[...C];if(e.type==="new"){const V={id:"custom-"+Date.now(),name:U,basePreset:e.basePresetId,mode:H,tokens:R};G.push(V);const Z=G.length-1;Pt.setState({userPresets:G}),Pt.getState().saveUserPresets(),Pt.getState().applyUserPreset(Z)}else{const V=G[e.presetIndex];V&&(G[e.presetIndex]={...V,name:U,mode:H,tokens:R}),Pt.setState({userPresets:G}),Pt.getState().saveUserPresets(),Pt.getState().applyUserPreset(e.presetIndex)}t(null)},T=()=>{t(null)},D=(U,R)=>{U.stopPropagation(),p(R)},L=l?"system":r?a:n,O=()=>{l?(d(n),m(JSON.stringify({preset:n})).catch(()=>{})):(d("system"),m(JSON.stringify({preset:"system"})).catch(()=>{}))},M=U=>{if(l){const R=$n.find(H=>H.id===U);(R==null?void 0:R.mode)==="dark"?x(U):(R==null?void 0:R.mode)==="light"&&y(U)}else d(U),m(JSON.stringify({preset:U})).catch(()=>{})},W=U=>{const R=$n.find(H=>H.id===U.basePreset);return R?{...R.tokens,...U.tokens}:U.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:O,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:U,mode:R})=>{const H=R==="dark"?_:S,G=C.filter(V=>{var X;return(V.mode??((X=$n.find($=>$.id===V.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:U}),i.jsxs("div",{className:"flex flex-wrap gap-2",children:[H.map(V=>i.jsx(B_,{preset:V,isActive:V.id===L&&!r,isUnderlying:l&&(V.id===u||V.id===c),onClick:()=>M(V.id),onNewFrom:()=>b(V.id)},V.id)),G.map(V=>{const Z=C.indexOf(V),X=W(V);return i.jsx(B_,{preset:{id:V.id,name:V.name,tokens:X},isActive:w===V.id,isUnderlying:l&&(V.id===u||V.id===c),onClick:()=>v(Z),onEdit:()=>j(Z),onDelete:$=>D($,Z)},V.id)})]})]},U)}),e&&i.jsx(HT,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,mode:e.mode,initialTokens:e.tokens,onClose:T,onSave:N})]})}function FT(){return i.jsx(UT,{})}function VT(){const{settings:e,loading:t,getSetting:n,setSetting:r}=ta(),a=t[Te.DISPLAY_SHOW_THINKING]??!1,l=e[Te.DISPLAY_MAX_VISIBLE_ITEMS]??"300",[u,c]=E.useState(l);E.useEffect(()=>{n(Te.DISPLAY_MAX_VISIBLE_ITEMS)},[n]),E.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]=E.useState(()=>Object.fromEntries(h.map(w=>[w.key,p[w.key]==="true"])));E.useEffect(()=>{h.forEach(w=>n(w.key))},[n]),E.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(FT,{}),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(GT,{})]}),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 $_=[{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(`
58
+ */var l_;function JE(){if(l_)return xm;l_=1;var e=Sd();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 xm.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,xm}var c_;function ZE(){return c_||(c_=1,gm.exports=JE()),gm.exports}var eN=ZE();const tN=FE.useInsertionEffect,nN=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",rN=nN?E.useLayoutEffect:E.useEffect,sN=tN||rN,i1=e=>{const t=E.useRef([e,(...n)=>t[0](...n)]).current;return sN(()=>{t[0]=e}),t[1]},iN="popstate",tg="pushState",ng="replaceState",aN="hashchange",u_=[iN,tg,ng,aN],oN=e=>{for(const t of u_)addEventListener(t,e);return()=>{for(const t of u_)removeEventListener(t,e)}},a1=(e,t)=>eN.useSyncExternalStore(oN,e,t),d_=()=>location.search,lN=({ssrSearch:e}={})=>a1(d_,e!=null?()=>e:d_),h_=()=>location.pathname,cN=({ssrPath:e}={})=>a1(h_,e!=null?()=>e:h_),uN=(e,{replace:t=!1,state:n=null}={})=>history[t?ng:tg](n,"",e),dN=(e={})=>[cN(e),uN],f_=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[f_]>"u"){for(const e of[tg,ng]){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,f_,{value:!0})}const hN=(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())?"~"+t:t.slice(e.length)||"/",o1=(e="")=>e==="/"?"":e,fN=(e,t)=>e[0]==="~"?e.slice(1):o1(t)+e,mN=(e="",t)=>hN(m_(o1(e)),m_(t)),m_=e=>{try{return decodeURI(e)}catch{return e}},l1={hook:dN,searchHook:lN,parser:QE,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,t,n)=>e(t,n)},c1=E.createContext(l1),co=()=>E.useContext(c1),u1={},d1=E.createContext(u1),pN=()=>E.useContext(d1),wd=e=>{const[t,n]=e.hook(e);return[mN(e.base,t),i1((r,a)=>e.aroundNav(n,fN(r,e.base),a))]},Tn=()=>wd(co()),rg=(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]},uo=e=>rg(co().parser,e,Tn()[0]),h1=({children:e,...t})=>{var p,m,x;const n=co(),r=t.hook?l1: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=E.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 E.createElement(c1.Provider,{value:a,children:e})},p_=({children:e,component:t},n)=>t?E.createElement(t,{params:n}):typeof e=="function"?e(n):e,gN=e=>{let t=E.useRef(u1);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},cl=({path:e,nest:t,match:n,...r})=>{const a=co(),[l]=wd(a),[u,c,d]=n??rg(a.parser,e,l,t),h=gN({...pN(),...c});if(!u)return null;const p=d?E.createElement(h1,{base:d},p_(r,h)):p_(r,h);return E.createElement(d1.Provider,{value:h,children:p})},Xn=E.forwardRef((e,t)=>{const n=co(),[r,a]=wd(n),{to:l="",href:u=l,onClick:c,asChild:d,children:h,className:p,replace:m,state:x,transition:y,...w}=e,C=i1(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&&E.isValidElement(h)?E.cloneElement(h,{onClick:C,href:_}):E.createElement("a",{...w,onClick:C,href:_,className:p!=null&&p.call?p(r===u):p,children:h,ref:t})}),f1=e=>Array.isArray(e)?e.flatMap(t=>f1(t&&t.type===E.Fragment?t.props.children:t)):[e],xN=({children:e,location:t})=>{const n=co(),[r]=wd(n);for(const a of f1(e)){let l=0;if(E.isValidElement(a)&&(l=rg(n.parser,a.props.path,t||r,a.props.nest))[0])return E.cloneElement(a,{match:l})}return null},g_=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},yN=(e=>e?g_(e):g_),bN=e=>e;function vN(e,t=bN){const n=ai.useSyncExternalStore(e.subscribe,ai.useCallback(()=>t(e.getState()),[e,t]),ai.useCallback(()=>t(e.getInitialState()),[e,t]));return ai.useDebugValue(n),n}const x_=e=>{const t=yN(e),n=r=>vN(t,r);return Object.assign(n,t),n},In=(e=>e?x_(e):x_);function _N(){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 m1=_N();function ks(e){return e.startsWith("/")?`${m1}${e}`||"/":e}async function ve(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 y_(e,t,n){try{return(await ve(`/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 p1(e,t,n){try{const r=await ve(`/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 gu(e,t){return n=>({loading:{...n.loading,[e]:t}})}function b_(e,t){return n=>({settings:{...n.settings,[e]:t},loading:{...n.loading,[e]:!1}})}const sg=[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 Zi(){return{showThinking:Ft(e=>e.settings[Te.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:Ft(e=>e.settings[Te.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:Ft(e=>e.settings[Te.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:Ft(e=>e.settings[Te.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:Ft(e=>e.settings[Te.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true",showSyntaxHighlighting:Ft(e=>e.settings[Te.DISPLAY_SHOW_SYNTAX_HIGHLIGHTING]??"true")==="true",maxVisibleItems:Number(Ft(e=>e.settings[Te.DISPLAY_MAX_VISIBLE_ITEMS]??"300"))}}const Ft=In(e=>({settings:{},loading:{},getSetting:async t=>{e(gu(t,!0));try{const r=await(await ve(`/api/settings/${t}`)).json();return e(b_(t,r.value??"")),r.value}catch{return e(gu(t,!1)),null}},getSettings:async t=>{if(t.length!==0)try{const r=await(await ve(`/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(gu(t,!0));try{const a=await(await ve(`/api/settings/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})})).json();e(b_(t,a.value??""))}catch{e(gu(t,!1))}}})),ul=Object.freeze(Object.defineProperty({__proto__:null,DISPLAY_SETTINGS_KEYS:sg,SETTINGS_KEYS:Te,useDisplaySettings:Zi,useSettingsStore:Ft},Symbol.toStringTag,{value:"Module"}));function SN(){const[e,t]=E.useState({offsetTop:0,height:window.innerHeight,keyboardVisible:!1}),n=E.useRef(window.innerHeight);return E.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 wN(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Uu(){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 CN{constructor(t){_e(this,"ws",null);_e(this,"handlers",new Set);_e(this,"statusHandler",null);_e(this,"baseUrl");_e(this,"isReconnecting",!1);_e(this,"connectingPromise",null);_e(this,"lastCloseCode",0);_e(this,"reconnectAttempts",0);_e(this,"manualReconnectScheduled",!1);_e(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);wN(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=Uu(),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 kN=window.location.protocol==="https:"?"wss:":"ws:";let gp=window.location.port;gp||(gp=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"?"10469":window.location.protocol==="https:"?"443":"80");const jN=`${kN}//${window.location.hostname}:${gp}${ks("/ws")}`,Dt=new CN(jN),EN=3e4;function g1(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 Xt=In((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 ve("/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 ve("/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 ve(`/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 ve("/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 ve(`/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()},EN);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}})),Gt=In((e,t)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const r=await(await ve("/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 ve("/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 ve(`/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 ve(`/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 ve(`/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 ve(`/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})}})),fi=async(e,t,n)=>{try{const r=await ve(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"}}},Cd=async(e,t,n)=>{try{const r=await ve(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 x1(e){let t=null;function n(){t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))}return n}let xu=[];const kl=In()((e,t)=>{function n(){if(xu.length===0)return;const a=xu;xu=[],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=x1(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 ve(`/api/sessions/${l}/background-process/${a}/stop`,{method:"POST"})).ok&&t().removeProcess(a)}catch{}},appendLog:(a,l,u)=>{xu.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}}}}}),NN={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Fu=null;function TN(e){Fu=e}function Hi(){return NN}function ym(){Fu==null||Fu()}let yu=[];const Dn=In()((e,t)=>{function n(){if(yu.length===0)return;const a=yu;yu=[],e(l=>({logs:[...l.logs,...a]}))}const r=x1(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 ve(`/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 ve(`/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 ve(`/api/dev-server/logs?workdir=${encodeURIComponent(a)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content,...d.type?{type:d.type}:{}}));e({logs:c})}catch{}},clearLogs:async()=>{const a=t().workdir;if(a)try{await ve(`/api/dev-server/clear-logs?workdir=${encodeURIComponent(a)}`,{method:"POST"}),e({logs:[]})}catch{}},insertMarker:async()=>{const a=t().workdir;if(a)try{await ve(`/api/dev-server/insert-marker?workdir=${encodeURIComponent(a)}`,{method:"POST"}),t().fetchLogs()}catch{}},start:async()=>{const a=t().workdir;if(a)try{const u=await(await ve(`/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 ve(`/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 ve(`/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 ve(`/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;yu.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}}}}}),AN=[{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"}],LN=[{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"}],y1={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"},oi={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},b1={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},xp={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...oi},waiting_for_user:{...oi},phase_done:{...oi},phase_blocked:{...oi},new_message:{...b1}},agentOverrides:{}};function v1(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 Ui=In((e,t)=>({settings:xp,loaded:!1,load:()=>{Ft.getState().getSetting(Te.NOTIFICATION_SETTINGS);const r=Ft.subscribe(l=>{const u=l.settings[Te.NOTIFICATION_SETTINGS];if(u!==void 0)try{const c=JSON.parse(u);e({settings:v_(c),loaded:!0})}catch{e({loaded:!0})}}),a=Ft.getState().settings[Te.NOTIFICATION_SETTINGS];if(a)try{const l=JSON.parse(a);e({settings:v_(l),loaded:!0})}catch{e({loaded:!0})}return r},update:n=>{e({settings:n}),bm(n)},updateEvent:(n,r)=>{const a=t().settings,l={...a,events:{...a.events,[n]:{...a.events[n],...r}}};e({settings:l}),bm(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}),bm(c)}}));function bm(e){Ft.getState().setSetting(Te.NOTIFICATION_SETTINGS,JSON.stringify(e))}function v_(e){var t,n,r,a,l;return{soundEnabled:e.soundEnabled??xp.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??xp.browserNotificationEnabled,events:{complete:{...oi,...(t=e.events)==null?void 0:t.complete},waiting_for_user:{...oi,...(n=e.events)==null?void 0:n.waiting_for_user},phase_done:{...oi,...(r=e.events)==null?void 0:r.phase_done},phase_blocked:{...oi,...(a=e.events)==null?void 0:a.phase_blocked},new_message:{...b1,...(l=e.events)==null?void 0:l.new_message}},agentOverrides:e.agentOverrides??{}}}const __=new Map;function DN(e){let t=__.get(e);return t||(t=new Audio(ks(e)),t.volume=.5,__.set(e,t)),t}let _1=typeof Notification<"u"?Notification.permission:"denied";function RN(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(_1=e,e))}const ON={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},IN={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 MN(e){typeof Notification>"u"||_1==="granted"&&(document.hasFocus()||new Notification(ON[e],{body:IN[e],icon:ks("/fox.svg"),tag:`openfox-${e}`}))}function ql(e,t){const{settings:n}=Ui.getState(),r=v1(n,e,t);if(n.soundEnabled&&r.soundEnabled){const a=r.customSoundUrl??y1[e],l=DN(a);l.currentTime=0,l.play().catch(()=>{})}n.browserNotificationEnabled&&r.browserNotification&&MN(e)}const PN=e=>ql("complete",e),BN=e=>ql("phase_done",e),$N=e=>ql("phase_blocked",e),vm=e=>ql("waiting_for_user",e),zN=e=>ql("new_message",e),S_=new Map;function Ya(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 HN(e,t){if(e.type==="chat.done"){const n=e.payload,r=Ya(t,e.sessionId),a=n.agentType??r;n.reason==="complete"&&PN(a),n.reason==="waiting_for_user"&&vm(a);return}if(e.type==="chat.path_confirmation"){const n=Ya(t,e.sessionId);vm(n);return}if(e.type==="session.confirmation_pending"){const n=Ya(t,e.sessionId);vm(n);return}if(e.type==="task.completed"){const n=Ya(t,e.sessionId);BN(n);return}if(e.type==="phase.changed"&&e.sessionId){const n=e.payload,r=S_.get(e.sessionId)??null;if(S_.set(e.sessionId,n.phase),r===n.phase)return;const a=Ya(t,e.sessionId);n.phase==="blocked"&&$N(a)}}const Dl=In(e=>({servers:[],setServers:t=>e({servers:t}),fetchServers:async()=>{try{const t=await ve("/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{}}})),_m=new Set;function cn(e,t){return t!==null&&e.sessionId===t}function UN(e,t,n){return e.id!==void 0||cn(e,t)||n===!0&&e.sessionId!==void 0}function FN(e,t){return e.includes(t)?e:[...e,t]}function w_(e,t){return e.filter(n=>n!==t)}function VN(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 Sm(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 GN(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 C_(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 k_(e,t,n){var c,d,h,p,m,x,y,w,C,_,S,v,b,j,N,T,D,L,O,M,W,U;const r=n();HN(e,r);const a=((c=r.currentSession)==null?void 0:c.id)??null,l=()=>{const R=e.sessionId;!R||R===a||t(H=>({unreadSessionIds:FN(H.unreadSessionIds,R)}))},u=(R,H,G)=>({messages:R.messages.map(V=>V.id===H?G(V):V)});switch(e.type){case"session.state":{const R=e.payload;if(!UN(e,a,r.pendingSessionCreate))break;const H=n().pendingSessionCreate===!0,G=R.pendingConfirmations??[],V=R.session.id,Z={...n().crossSessionConfirmations};delete Z[V],t({currentSession:R.session,sessions:VN(n().sessions,R.session),unreadSessionIds:w_(n().unreadSessionIds,V),messages:R.messages,hiddenCount:R.hiddenCount??0,currentTodos:[],pendingPathConfirmations:G,crossSessionConfirmations:Z,sessionsWithPendingConfirmations:Object.keys(Z),pendingQuestions:R.pendingQuestions??[],activeWorkflowExecution:R.activeWorkflowExecution??null,...H?{pendingSessionCreate:R.session.id}:{}});break}case"session.list":{const R=e.payload;t(H=>({sessions:GN(R.sessions,H.sessions,H.currentSession)}));break}case"session.created":{const R=e.payload;t(H=>({sessions:H.sessions.some(G=>G.id===R.session.id)?H.sessions.map(G=>G.id===R.session.id?{...G,...R.session}:G):[R.session,...H.sessions]}));break}case"session.deleted":{const R=e.payload;t(H=>({unreadSessionIds:w_(H.unreadSessionIds,R.sessionId)})),n().listSessions();break}case"session.deletedAll":{n().listSessions();break}case"session.running":{const R=e.payload;C_(e,t,n,H=>({...H,isRunning:R.isRunning})),R.isRunning||t({abortInProgress:!1,queuedMessages:[]}),R.isRunning&&t({restoredInput:null});break}case"chat.message":{if(!cn(e,((d=n().currentSession)==null?void 0:d.id)??null)){l();break}const R=e.payload;t(H=>{if(H.messages.some(V=>V.id===R.message.id))return H;const G=R.message.role==="user";return{messages:[...H.messages,R.message],sessions:H.sessions.map(V=>V.id===e.sessionId&&G?{...V,messageCount:V.messageCount+1}:V)}});break}case"chat.message_updated":{if(!cn(e,((h=n().currentSession)==null?void 0:h.id)??null)){l();break}const R=e.payload,H=n().messages.find(G=>G.id===R.messageId);R.updates.isStreaming===!1&&(H==null||H.isStreaming),t(G=>({messages:G.messages.map(V=>V.id===R.messageId?{...V,...R.updates}:V)}));break}case"chat.delta":{if(!cn(e,((p=n().currentSession)==null?void 0:p.id)??null)){l();break}const R=e.payload;if(!_m.has(R.messageId)){_m.add(R.messageId);const G=R.subAgentType?"sub-agent":Ya(n(),e.sessionId);zN(G)}const H=Hi();H.messageId=R.messageId,H.deltaContent+=R.content,ym();break}case"chat.thinking":{if(!cn(e,((m=n().currentSession)==null?void 0:m.id)??null)){l();break}const R=e.payload,H=Hi();H.messageId=R.messageId,H.thinkingContent+=R.content,ym();break}case"chat.tool_preparing":{if(!cn(e,((x=n().currentSession)==null?void 0:x.id)??null)){l();break}const R=e.payload;t(H=>{var I;const G=H.messages.find(B=>B.id===R.messageId);if(!G)return{};if((I=G.toolCalls)==null?void 0:I.find((B,q)=>q===R.index))return{};const Z=G.preparingToolCalls??[],X=Z.findIndex(B=>B.index===R.index);let $;return X>=0?$=Z.map((B,q)=>q===X?{...B,arguments:R.arguments}:B):$=[...Z,{index:R.index,name:R.name,...R.arguments?{arguments:R.arguments}:{}}],{messages:H.messages.map(B=>B.id===R.messageId?{...B,preparingToolCalls:$}:B)}});break}case"chat.tool_call":{if(!cn(e,((y=n().currentSession)==null?void 0:y.id)??null)){l();break}const R=e.payload,H=G=>{var I;const V=(G.toolCalls??[]).length,Z=(I=G.preparingToolCalls)==null?void 0:I.filter(B=>B.index!==V),X=Hi(),$=X.toolOutput.filter(B=>B.callId===R.callId);return $.length>0&&(X.toolOutput=X.toolOutput.filter(B=>B.callId!==R.callId)),{...G,toolCalls:[...G.toolCalls??[],{id:R.callId,name:R.tool,arguments:R.args,startedAt:Date.now(),...$.length>0?{streamingOutput:$.map(B=>({stream:B.stream,content:B.content,timestamp:Date.now()}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};t(G=>u(G,R.messageId,H));break}case"chat.tool_output":{if(!cn(e,((w=n().currentSession)==null?void 0:w.id)??null)){l();break}const R=e.payload,H=Hi();H.messageId=R.messageId,H.toolOutput.push({messageId:R.messageId,callId:R.callId,stream:R.stream,content:R.output}),ym();break}case"chat.tool_result":{if(!cn(e,((C=n().currentSession)==null?void 0:C.id)??null)){l();break}const R=e.payload,H=G=>{var Z;const V=(Z=G.toolCalls)==null?void 0:Z.map(X=>X.id===R.callId?{...X,result:R.result}:X);return{...G,toolCalls:V}};t(G=>u(G,R.messageId,H));break}case"chat.vision_fallback":{if(!cn(e,((_=n().currentSession)==null?void 0:_.id)??null)){l();break}const R=e.payload;t(H=>{const G=`${R.messageId}-${R.attachmentId}`,V={...H.visionFallbackByMessage};return V[G]={type:R.type,attachmentId:R.attachmentId,filename:R.filename,description:R.description},{visionFallbackByMessage:V}});break}case"chat.todo":{if(!cn(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(!cn(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(!cn(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(!cn(e,((j=n().currentSession)==null?void 0:j.id)??null)){l();break}const R=Hi();R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[],_m.delete(e.payload.messageId);const H=e.payload,G=H.stats;t(V=>({messages:V.messages.map(Z=>Z.id===H.messageId?{...Z,isStreaming:!1,stats:G??Z.stats,completeReason:H.reason,preparingToolCalls:void 0}:Z),visionFallbackByMessage:{}}));break}case"chat.error":{if(!cn(e,((N=n().currentSession)==null?void 0:N.id)??null)){l();break}const R=Hi(),H=e.payload;console.error("Chat error:",H.error,"recoverable:",H.recoverable),H.recoverable||(R.messageId=null,R.deltaContent="",R.thinkingContent="",R.toolOutput=[]),t(G=>({error:{code:"CHAT_ERROR",message:H.error},...H.recoverable?{}:{messages:G.messages}}));break}case"chat.path_confirmation":{const R=e.sessionId,H=R===(((T=n().currentSession)==null?void 0:T.id)??null),G=e.payload,V={callId:G.callId,tool:G.tool,paths:G.paths,workdir:G.workdir,reason:G.reason};if(!H){l(),R&&t(Z=>({crossSessionConfirmations:{...Z.crossSessionConfirmations,[R]:Sm(Z.crossSessionConfirmations[R]??[],V)},sessionsWithPendingConfirmations:Z.sessionsWithPendingConfirmations.includes(R)?Z.sessionsWithPendingConfirmations:[...Z.sessionsWithPendingConfirmations,R]}));break}t(Z=>({pendingPathConfirmations:Sm(Z.pendingPathConfirmations,V)}));break}case"session.confirmation_pending":{const R=e.sessionId,H=e.payload,G={callId:H.callId,tool:H.tool,paths:H.paths,workdir:H.workdir,reason:H.reason};R&&t(V=>({crossSessionConfirmations:{...V.crossSessionConfirmations,[R]:Sm(V.crossSessionConfirmations[R]??[],G)},sessionsWithPendingConfirmations:V.sessionsWithPendingConfirmations.includes(R)?V.sessionsWithPendingConfirmations:[...V.sessionsWithPendingConfirmations,R]}));break}case"session.confirmation_resolved":{const R=e.sessionId,H=e.payload;R&&t(G=>{const Z=(G.crossSessionConfirmations[R]??[]).filter($=>$.callId!==H.callId),X={...G.crossSessionConfirmations};return Z.length===0?delete X[R]:X[R]=Z,{crossSessionConfirmations:X,sessionsWithPendingConfirmations:Object.keys(X)}});break}case"chat.ask_user":{if(!cn(e,((D=n().currentSession)==null?void 0:D.id)??null)){l();return}const R=e.payload,H={callId:R.callId,question:R.question,type:R.type??"text",options:R.options??void 0};t(G=>({pendingQuestions:[...G.pendingQuestions.filter(V=>V.callId!==R.callId),H]}));break}case"mode.changed":{if(!cn(e,((L=n().currentSession)==null?void 0:L.id)??null)){l();break}const R=e.payload;t(H=>({currentSession:H.currentSession?{...H.currentSession,mode:R.mode}:null}));break}case"phase.changed":{const R=e.payload;C_(e,t,n,H=>({...H,phase:R.phase}));break}case"workflow.execution_changed":{const R=e.payload;t(H=>{const G=H.activeWorkflowExecution;return G?{activeWorkflowExecution:{...G,status:R.status,...R.currentStepId?{currentStepId:R.currentStepId}:{},...R.currentStepName?{currentStepName:R.currentStepName}:{}}}:{activeWorkflowExecution:{id:R.executionId,sessionId:e.sessionId??"",workflowId:R.workflowId,workflowName:R.workflowName,...R.workflowColor?{workflowColor:R.workflowColor}:{},status:R.status,...R.currentStepId?{currentStepId:R.currentStepId}:{},...R.currentStepName?{currentStepName:R.currentStepName}:{},stepOutput:{},params:{},createdAt:Date.now(),updatedAt:Date.now()}}});break}case"criteria.updated":{if(!cn(e,((O=n().currentSession)==null?void 0:O.id)??null)){l();break}const R=e.payload;t(H=>({currentSession:H.currentSession?{...H.currentSession,criteria:R.criteria}:null}));break}case"metadata.updated":{if(!cn(e,((M=n().currentSession)==null?void 0:M.id)??null)){l();break}const R=e.payload;t(H=>({currentSession:H.currentSession?{...H.currentSession,metadataEntries:{...H.currentSession.metadataEntries,[R.key]:R.entries}}:null}));break}case"context.state":{const R=e.payload,H=cn(e,((W=n().currentSession)==null?void 0:W.id)??null);R.subAgentId?H&&n().updateSubAgentContextState(R.subAgentId,R.context):H?t({contextState:R.context}):l();break}case"session.name_generated":{const R=e.payload,H=e.sessionId,G=(U=n().currentSession)==null?void 0:U.id;t(V=>{const Z=V.sessions.map($=>$.id===H?{...$,title:R.name}:$),X=G===H?V.currentSession?{...V.currentSession,metadata:{...V.currentSession.metadata,title:R.name}}:null:V.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 H=[...R.servers].sort((G,V)=>G.name.localeCompare(V.name));Dl.getState().setServers(H)}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":{Dn.getState().handleMessage(e);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{kl.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 dl=!1,Ur=null;const wm=new Set,bu=new Map;function j_(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 E_(e,t,n,r,a){try{const u=await(await ve(`/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 Le=In((e,t)=>{TN(()=>{const r=Hi();if(!r.messageId)return;const a=r.deltaContent.length>0,l=r.thinkingContent.length>0,u=r.toolOutput.length>0;if(!a&&!l&&!u)return;const c=r.deltaContent,d=r.thinkingContent,h=r.toolOutput;r.deltaContent="",r.thinkingContent="",r.toolOutput=[],e(p=>{const m=p.messages.find(x=>x.id===r.messageId);if(m){const x={...m};if(a&&(x.content=x.content+c),l&&(x.thinkingContent=(x.thinkingContent??"")+d),u){const y=new Set;x.toolCalls=j_(x.toolCalls,h,y);const w=h.filter(C=>!y.has(C.callId));w.length>0&&r.toolOutput.push(...w)}return{messages:p.messages.map(y=>y.id===r.messageId?x:y)}}if(u){const x=new Set,y=p.messages.map(C=>C.id!==r.messageId?C:{...C,toolCalls:j_(C.toolCalls,h,x)}),w=h.filter(C=>!x.has(C.callId));return w.length>0&&r.toolOutput.push(...w),{messages:y}}return p})});function n(r,a,l,u){return{workflowId:r.workflowId,resumeFrom:r.currentStepId,stepOutput:r.stepOutput,...r.params&&Object.keys(r.params).length>0?{params:r.params}:{},...a!=null&&a.trim()?{content:a}:{},...l&&l.length>0?{attachments:l}:{},...u?{messageKind:u}:{}}}return{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,activeWorkflowExecution:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,pendingUpdate:!1,connect:async()=>{if(t().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let a=!1;try{a=(await(await ve("/api/auth")).json()).requiresAuth}catch{}if(a&&!Dt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Dt.onStatusChange(l=>{var u;if(e({connectionStatus:l}),l==="connected"){t().listSessions(void 0),Gt.getState().listProjects();const c=(u=t().currentSession)==null?void 0:u.id;c&&t().loadSession(c)}});try{await Dt.connect(),dl||(dl=!0,Ur=Dt.subscribe(l=>{k_(l,e,t)}))}catch(l){console.error("Failed to connect:",l);const u=Dt.getLastCloseCode();if(!Dt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}Ur&&(Ur(),Ur=null),dl=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Dt.disconnect(),Ur&&(Ur(),Ur=null),dl=!1,e({connectionStatus:"disconnected"}),t().connect()},disconnect:()=>{Dt.disconnect(),Ur&&(Ur(),Ur=null),dl=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async r=>{try{const a=await fetch(ks("/api/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:r})});if(!a.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:l}=await a.json();Dt.setToken(l),e({showPasswordModal:!1}),t().connect();const{listProjects:u}=Gt.getState(),{fetchConfig:c}=Xt.getState();u(),c(),t().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Dt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(r,a)=>{if(t().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const u=await ve("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:r,title:a})});if(!u.ok)return e({pendingSessionCreate:!1}),null;const c=await u.json();try{Dt.send("session.load",{sessionId:c.session.id})}catch{}return c.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async r=>{if(!wm.has(r)){wm.add(r);try{const a=t().currentSession;if(!a||a.id!==r){const h=a==null?void 0:a.id,p=t().pendingPathConfirmations,x={...t().crossSessionConfirmations};h&&p.length>0&&(x[h]=[...x[h]??[],...p]),e({currentSession:null,unreadSessionIds:t().unreadSessionIds.filter(y=>y!==r),subAgentContextStates:{},messages:[],currentTodos:[],contextState:null,pendingPathConfirmations:[],pendingQuestions:[],queuedMessages:[],abortInProgress:!1,restoredInput:null,error:null,gitStatus:null,pendingSessionCreate:!1,crossSessionConfirmations:x,sessionsWithPendingConfirmations:Object.keys(x)})}else e({unreadSessionIds:t().unreadSessionIds.filter(h=>h!==r)});const l=await ve(`/api/sessions/${r}`);if(!l.ok)return;const u=await l.json(),c=u.messages??[],d={...t().crossSessionConfirmations};delete d[r],e({currentSession:u.session,messages:c,hiddenCount:u.hiddenCount??0,contextState:u.contextState,queuedMessages:u.queueState??[],pendingPathConfirmations:u.pendingConfirmations??[],pendingQuestions:u.pendingQuestions??[],activeWorkflowExecution:u.activeWorkflowExecution??null,crossSessionConfirmations:d,sessionsWithPendingConfirmations:Object.keys(d)}),Dt.send("session.load",{sessionId:r});try{const h=await ve(`/api/sessions/${r}/background-processes`);if(h.ok){const p=await h.json();kl.getState().setProcesses(p.processes??[])}}catch{}}catch{}finally{wm.delete(r)}}},listSessions:async(r,a=20)=>{const l=r??"global";if(bu.has(l))return bu.get(l);const u=(async()=>{var c;try{const d=new URLSearchParams;d.set("limit",String(a)),r&&d.set("projectId",r);const p=await(await ve(`/api/sessions?${d.toString()}`)).json(),m=p.sessions??[];e(y=>({sessions:m.map(w=>{var _,S;const C=y.sessions.find(v=>v.id===w.id);return{...w,title:w.title??(C==null?void 0:C.title),mode:((_=y.currentSession)==null?void 0:_.id)===w.id?y.currentSession.mode:(C==null?void 0:C.mode)??w.mode,phase:((S=y.currentSession)==null?void 0:S.id)===w.id?y.currentSession.phase:(C==null?void 0:C.phase)??w.phase,isRunning:w.isRunning&&(C==null?void 0:C.isRunning)!==!1,messageCount:w.messageCount,recentUserPrompts:w.recentUserPrompts}}),sessionsHasMore:r?p.hasMore??!1:!0}));const x=p.pendingConfirmationsBySession;if(x){const y=(c=t().currentSession)==null?void 0:c.id,w={};for(const[C,_]of Object.entries(x))C!==y&&(w[C]=_);e({crossSessionConfirmations:w,sessionsWithPendingConfirmations:Object.keys(w)})}}catch{}finally{bu.delete(l)}})();return bu.set(l,u),u},loadMoreSessions:async r=>{const a=t();if(!(a.sessionsPaginationLoading||!a.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const l=new URLSearchParams;l.set("limit","20"),l.set("offset",String(a.sessions.length)),l.set("projectId",r);const c=await(await ve(`/api/sessions?${l.toString()}`)).json(),d=c.sessions??[];e(h=>({sessions:[...h.sessions,...d.map(p=>{const m=h.sessions.find(x=>x.id===p.id);return(m==null?void 0:m.isRunning)===!1?{...p,isRunning:!1}:p})],sessionsHasMore:c.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async r=>{var a;try{return(await ve(`/api/sessions/${r}`,{method:"DELETE"})).ok?(await t().listSessions(),((a=t().currentSession)==null?void 0:a.id)===r&&t().clearSession(),!0):!1}catch{return!1}},renameSession:async(r,a)=>{var l;try{const u=await ve(`/api/sessions/${r}/title`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:a})});if(!u.ok)return!1;if(await t().listSessions(),((l=t().currentSession)==null?void 0:l.id)===r){const d=await u.json();d.session&&e({currentSession:d.session})}return!0}catch{return!1}},deleteAllSessions:async r=>{try{return(await ve(`/api/projects/${r}/sessions`,{method:"DELETE"})).ok?(await t().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{e(r=>({currentSession:null,messages:[],hiddenCount:0,currentTodos:[],contextState:null,restoredInput:null,pendingSessionCreate:!1,unreadSessionIds:r.currentSession?r.unreadSessionIds.filter(a=>a!==r.currentSession.id):r.unreadSessionIds}))},sendMessage:async(r,a,l)=>{var d;e({error:null});const u=(d=t().currentSession)==null?void 0:d.id;if(!u)return;const c=t().activeWorkflowExecution;if(c&&c.status==="running"){Dt.send("runner.launch",n(c,r,a,l==null?void 0:l.messageKind));return}try{const h=r==null?void 0:r.trim(),p=a&&a.length>0,m={};h&&(m.content=r),p&&(m.attachments=a),l!=null&&l.messageKind&&(m.messageKind=l.messageKind);const y=await(await ve(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)})).json();y.queueState&&e({queuedMessages:y.queueState})}catch(h){console.error("Error sending message:",h)}},stopGeneration:async()=>{var a;const r=(a=t().currentSession)==null?void 0:a.id;if(r&&!t().abortInProgress){e({abortInProgress:!0});try{const u=await(await ve(`/api/sessions/${r}/stop`,{method:"POST"})).json();if(u.queuedMessages&&u.queuedMessages.length>0){const c=u.queuedMessages.map(d=>d.content).join(`
59
+ `);e({restoredInput:c})}}catch(l){console.error("Error stopping generation:",l)}}},continueGeneration:async()=>{var a;const r=(a=t().currentSession)==null?void 0:a.id;if(r)try{await ve(`/api/sessions/${r}/continue`,{method:"POST"})}catch(l){console.error("Error continuing generation:",l)}},launchWorkflow:(r,a,l,u,c)=>{const d={};r!=null&&r.trim()&&(d.content=r),a&&a.length>0&&(d.attachments=a),l&&(d.workflowId=l),u&&(d.subGroup=u),c&&(d.params=c),Dt.send("runner.launch",d)},continueWorkflow:()=>{const a=t().activeWorkflowExecution;!a||a.status!=="waiting"||Dt.send("runner.launch",n(a))},exitWorkflow:()=>{Dt.send("workflow.exit",{})},switchMode:async r=>{var l;const a=(l=t().currentSession)==null?void 0:l.id;if(a)try{const u=await ve(`/api/sessions/${a}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:r})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const c=await u.json();c.session&&e({currentSession:c.session}),c.messages&&e({messages:c.messages,hiddenCount:c.hiddenCount??0})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async r=>{var l;const a=(l=t().currentSession)==null?void 0:l.id;if(a)try{const u=await ve(`/api/sessions/${a}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:r})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const c=await u.json();c.session&&e({currentSession:c.session})}catch(u){console.error("Error switching danger level:",u)}},editCriteria:async r=>{var l;const a=(l=t().currentSession)==null?void 0:l.id;if(a)try{const u=await ve(`/api/sessions/${a}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:r})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{Dt.send("context.compact",{})},setSessionProvider:async(r,a)=>{var l;try{const u=(l=t().currentSession)==null?void 0:l.id;if(!u)return null;const c=await ve(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:r,...a?{model:a}:{}})});if(!c.ok)return null;const d=await c.json();return e({currentSession:d.session,messages:d.messages??[],hiddenCount:d.hiddenCount??0,contextState:d.contextState}),d.session}catch{return null}},updateContextState:r=>{e({contextState:r})},updateSubAgentContextState:(r,a)=>{e(l=>({subAgentContextStates:{...l.subAgentContextStates,[r]:a}}))},clearSubAgentContextState:r=>{e(a=>{const l={...a.subAgentContextStates};return delete l[r],{subAgentContextStates:l}})},confirmPath:async(r,a,l=!1)=>{var c;const u=(c=t().currentSession)==null?void 0:c.id;if(u)try{const d=await ve(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:r,approved:a,alwaysAllow:l})});if(!d.ok){const h=await d.json().catch(()=>({}));console.error("Error confirming path:",h.error??`HTTP ${d.status}`)}}catch(d){console.error("Error confirming path:",d)}},answerQuestion:async(r,a,l)=>{var c;const u=(c=t().currentSession)==null?void 0:c.id;if(u){try{await ve(`/api/sessions/${u}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:r,answer:a,skip:l})})}catch(d){console.error("Error answering question:",d)}e(d=>({pendingQuestions:d.pendingQuestions.filter(h=>h.callId!==r)}))}},queueAsap:async(r,a,l)=>{var c;const u=(c=t().currentSession)==null?void 0:c.id;u&&await E_(u,r,a,l,e)},queueCompletion:async(r,a,l)=>{var c;const u=(c=t().currentSession)==null?void 0:c.id;u&&await E_(u,r,a,l,e)},cancelQueued:async r=>{var l;const a=(l=t().currentSession)==null?void 0:l.id;if(a)try{const c=await(await ve(`/api/sessions/${a}/queue/${r}`,{method:"DELETE"})).json();c.queueState&&e({queuedMessages:c.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},clearRestoredInput:()=>{e({restoredInput:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},queueUpdate:()=>{e({pendingUpdate:!0})},triggerPendingUpdate:()=>{t().pendingUpdate&&(e({pendingUpdate:!1}),Dt.send("context.applyDynamic",{}))},handleServerMessage:r=>{k_(r,e,t)}}});function kd(){return Le(e=>{var t;return((t=e.currentSession)==null?void 0:t.isRunning)??!1})}function WN(){return Le(e=>e.abortInProgress)}function qN(){const e=Le(a=>a.connect),t=Le(a=>a.connectionStatus),n=Ui(a=>a.load),r=uo("/p/:projectId/s/:sessionId/readonly")[0];return E.useEffect(()=>{r||e()},[e,r]),E.useEffect(()=>{r||t==="connected"&&n()},[t,n,r]),{connectionStatus:t}}const KN="modulepreload",YN=function(e){return"/"+e},N_={},ee=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=YN(h),h in N_)return;N_[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":KN,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)})},XN=[{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"}],QN=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"}]'),S1={tokens:XN,presets:QN},w1=S1.tokens,$n=S1.presets;function T_(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}function JN(){try{const e=localStorage.getItem("openfox:systemThemePrefs");if(e)return JSON.parse(e)}catch{}return{darkPreset:"dark",lightPreset:"light"}}const Bt=In((e,t)=>{const n=JN();return{currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:T_(),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($n.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=$n.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=$n.find(p=>p.id===r))==null?void 0:c.tokens)??{},...a};if(l)return{...w1.reduce((h,p)=>({...h,[p.key]:p.defaultValue}),{}),...a};const u=$n.find(h=>h.id===t().currentPreset);return(u==null?void 0:u.tokens)??((d=$n[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 ee(async()=>{const{useSettingsStore:l}=await Promise.resolve().then(()=>ul);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}),ee(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ul);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=$n.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:T_()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(t().userPresets)),ee(async()=>{const{useSettingsStore:r}=await Promise.resolve().then(()=>ul);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})),ee(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ul);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})),ee(async()=>{const{useSettingsStore:a,SETTINGS_KEYS:l}=await Promise.resolve().then(()=>ul);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 ZN({canLoad:e,projectId:t,currentProjectId:n}){const r=Gt(u=>u.loadProject),a=Le(u=>u.listSessions),l=Le(u=>u.clearSession);E.useEffect(()=>{e&&t&&(n!==t&&r(t),a(t),l())},[e,t,n,r,a,l])}function eT({canLoad:e,projectId:t,sessionId:n,currentProjectId:r,currentSessionId:a}){const l=Le(h=>h.loadSession),u=Gt(h=>h.loadProject),c=Le(h=>h.listSessions),d=Le(h=>h.pendingSessionCreate);E.useEffect(()=>{e&&t&&r!==t&&u(t)},[e,t,r,u]),E.useEffect(()=>{e&&n&&a!==n&&l(n),e&&t&&c(t)},[e,n,a,l,c,d,t])}function tT({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 C1({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 nT({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 rT({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 Ki({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 Mr({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 k1({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 hn(e){return i.jsx(k1,{direction:"down",...e})}function sT(e){return i.jsx(k1,{direction:"up",...e})}function iT({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 Rl({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 j1({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 E1({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 ig({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 Rr({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 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:"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 oT({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 lT({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 ag({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 cT({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 A_({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 N1({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 T1({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 A1({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 Xr({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 uT({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 jd({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 dT({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 hT({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 L1({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 D1({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 og({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 fT({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 mT({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 ea({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 Xi({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 pT({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 yp({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 lg({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 gT({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 xT({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 L_({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 bp(){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 D_(e,t){const n=Dt.ws;!n||n.readyState!==WebSocket.OPEN||n.send(JSON.stringify({id:bp(),type:e,payload:t}))}const Lr=In((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 ve(`/api/terminals?projectId=${encodeURIComponent(n)}`);if(r.ok){const a=await r.json();e({sessions:a});const l=Dt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of a)l.send(JSON.stringify({id:bp(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(r){console.error("Failed to fetch terminals:",r)}},createSession:async(n,r)=>{try{const a=await ve("/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=Dt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:bp(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(a){console.error("Failed to create terminal:",a)}},writeSession:(n,r)=>{D_("terminal.write",{sessionId:n,data:r})},resizeSession:(n,r,a)=>{D_("terminal.resize",{sessionId:n,cols:r,rows:a})},killSession:async n=>{try{(await ve(`/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}}}}));Dt.subscribe(e=>{var t;(t=e.type)!=null&&t.startsWith("terminal.")&&Lr.getState().handleMessage(e)});const Cs=In((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"})}}}})),Wr={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 vp(e){if(!e)return structuredClone(Wr);try{const t=JSON.parse(e),n=r=>t[r]===void 0?structuredClone(Wr[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(Wr)}}function R_(e){return e.code.startsWith("Digit")?e.code.slice(-1):/^[a-zA-Z]$/.test(e.key)?e.key.toLowerCase():e.key}function Xu(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 yT(e){return e.type==="double-press"}function R1(e){return e.type==="chord"}function bT(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 O1(e,t){const n=t.modifiers.includes("ctrl"),r=t.modifiers.includes("meta"),a=t.modifiers.includes("alt"),l=t.modifiers.includes("shift");return bT(e,t.key)&&e.ctrlKey===n&&e.metaKey===r&&e.altKey===a&&e.shiftKey===l}function Kl(){const e=Ft(t=>t.settings[Te.KEYBINDINGS]);return vp(e)}function vT(e,t,n){const r=E.useRef(0),a=E.useRef(t);a.current=t,E.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 _T(e,t){const n=E.useRef(t);n.current=t,E.useEffect(()=>{if(!e)return;const r=a=>{O1(a,e)&&(a.preventDefault(),n.current())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e])}function Ol(e,t,n){vT(e&&yT(e)?e:void 0,t,n),_T(e&&R1(e)?e:void 0,t)}function ST(e,t,n){const r=E.useRef(n);r.current=n,E.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&&R1(c)&&O1(l,c)){l.preventDefault(),r.current(d.id);return}}};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,t])}var mi=s1();const Ed=E.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})})}));Ed.displayName="IconButton";const wT="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",ci=E.forwardRef((e,t)=>i.jsx(Ed,{ref:t,icon:wT,title:"Edit",...e}));ci.displayName="EditButton";const CT="M6 18L18 6M6 6l12 12",cg=E.forwardRef((e,t)=>i.jsx(Ed,{ref:t,icon:CT,...e}));cg.displayName="CloseButton";const kT={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 jt({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]=E.useState(!1),_=h!==void 0,S=_?h:w,v=E.useCallback(()=>{_||C(!0)},[_]),b=E.useCallback(()=>{_||C(!1),d==null||d()},[_,d]);E.useEffect(()=>{if(!S||!m)return;const N=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",N),()=>document.removeEventListener("keydown",N)},[S,b,m]);const j=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:[j,S&&(typeof document<"u"?mi.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 ${kT[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(cg,{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 jT({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:LN.map(({url:l,label:u})=>i.jsx("option",{value:l,title:u,children:u.split(" ")[0]},l))}),i.jsx(hn,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const O_=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function ET(){const e=Ui(d=>d.settings),t=Ui(d=>d.update),n=Ui(d=>d.updateEvent),r=Ui(d=>d.updateAgentOverride),a=Ui(d=>d.load);E.useEffect(()=>{a()},[a]);const l=async()=>{await RN()==="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(I_,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>t({...e,soundEnabled:d})}),i.jsx(I_,{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"}),O_.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:AN.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})}),O_.map(h=>{const p=v1(e,d.key,h.key==="general"?void 0:h.key),m=y1[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(jT,{value:p.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:x=>c(h.key,d.key,x)})]})},h.key)})]},d.key))})]})})]})]})}function I_({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 rt=E.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})});rt.displayName="Button";async function M_(e,t,n){try{const r=await ve(e,t);return r.ok?(await n(),{success:!0}):{success:!1,error:(await r.json()).error}}catch{return{success:!1,error:"Network error"}}}const Nn=In((e,t)=>({defaults:[],userItems:[],projectItems:[],items:[],selectedDirectory:null,diagnostics:[],loading:!1,fetchSkills:async()=>{e({loading:!0});try{const r=await(await ve("/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 ve(`/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 ve(`/api/skills/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/skills/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createSkill:async(n,r)=>{const a=await fi("POST","/api/skills",{...n,destination:r});return a.success&&await t().fetchSkills(),a},updateSkill:async(n,r)=>{const a=await fi("PUT",`/api/skills/${n}`,r);return a.success&&await t().fetchSkills(),a},deleteSkill:async n=>{try{const r=await ve(`/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)=>Cd(`/api/skills/${n}/duplicate`,()=>t().fetchSkills(),r),selectDirectory:async n=>M_("/api/skills/library",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})},t().fetchSkills),removeDirectory:async()=>{await ve("/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 M_("/api/skills/install",{method:"POST",body:r},t().fetchSkills)}}));function Yl(){const[e,t]=E.useState({id:null,type:null}),n=E.useCallback(l=>t({id:l,type:"delete"}),[]),r=E.useCallback(()=>t({id:null,type:null}),[]),a=E.useCallback((l,u)=>e.id===l&&e.type===u,[e.id,e.type]);return{requestDelete:n,clearConfirm:r,isConfirming:a}}function Qu({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 Ju({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(ea,{})})}function Il({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(Rl,{})})}function Cr({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 NT({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(rt,{variant:"secondary",onClick:e,children:"Cancel"}),i.jsx(rt,{variant:"primary",onClick:t,disabled:n||r,children:n?"Saving...":"Save"})]})}function eo({message:e}){return i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Nd({value:e,onChange:t}){return 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:e,onChange:n=>t(n.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/)"})]})]})}function I1({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(rt,{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 M1({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 P1({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(rt,{variant:"primary",size:"sm",onClick:t,children:n})})]})}function ug({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 B1({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(Cr,{label:n,value:e,onChange:h,placeholder:a,hint:u}),i.jsx(Cr,{label:r,value:t,onChange:p,readOnly:c,placeholder:l,hint:c?d:void 0,mono:!0})]})}function $1(e={}){const{initialData:t={}}=e,[n,r]=E.useState("list"),[a,l]=E.useState(null),[u,c]=E.useState(""),[d,h]=E.useState(!1),[p,m]=E.useState(t),x=E.useCallback(()=>{m(t),c(""),l(null)},[t]),y=E.useCallback(S=>{r(S),S==="list"&&x()},[x]),w=E.useCallback(S=>{m(v=>typeof S=="function"?S(v):S)},[]),C=E.useCallback((S,v={})=>{l(S),r("edit"),m({...v}),c("")},[]),_=E.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 Ml({isOpen:e,onClose:t,onConfirm:n,title:r,message:a,confirmLabel:l="Confirm",confirmVariant:u="primary",disabled:c=!1}){return i.jsx(jt,{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(rt,{variant:"secondary",onClick:t,disabled:c,children:"Cancel"}),i.jsx(rt,{variant:u,onClick:n,disabled:c,autoFocus:!0,children:l})]})]})})}const TT={sm:"w-4 h-4",md:"w-8 h-8",lg:"w-12 h-12"};function pi({size:e="md",className:t=""}){return i.jsx("div",{className:`animate-spin border-2 border-accent-primary border-t-transparent rounded-full ${TT[e]} ${t}`})}function AT({text:e,...t}){return i.jsxs("div",{className:"text-center",children:[i.jsx(pi,{...t,className:"mx-auto mb-4"}),e&&i.jsx("div",{className:"text-text-secondary",children:e})]})}function z1(e){return e.split(/[\\/]/).filter(Boolean).pop()??""}function LT(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 H1(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 ui=E.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}));ui.displayName="Input";function Td({onSelect:e,onClose:t,initialPath:n}){const[r,a]=E.useState(null),[l,u]=E.useState(!0),[c,d]=E.useState(""),[h,p]=E.useState(-1),m=E.useRef(null),x=E.useRef(null),y=E.useCallback(async b=>{u(!0),d(""),p(-1);try{const j=b?`/api/directories?path=${encodeURIComponent(b)}`:"/api/directories",T=await(await ve(j)).json();a(T)}catch(j){console.error("Failed to load directories:",j)}finally{u(!1)}},[]);E.useEffect(()=>{y(n)},[n,y]);const w=LT((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}))];E.useEffect(()=>{p(c?0:-1)},[c,C.length]),E.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 j;if(b.key==="ArrowDown")b.preventDefault(),p(N=>Math.min(N+1,_.length-1));else if(b.key==="ArrowUp")b.preventDefault(),p(N=>Math.max(N-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(""),(j=m.current)==null||j.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(jt,{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,j)=>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 ${j===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(Xi,{})}),i.jsx(ui,{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(pi,{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,j)=>i.jsxs("div",{"data-index":j,className:`group flex items-center ${j===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(tT,{className:"w-5 h-5 text-text-muted shrink-0"}):i.jsx(Rr,{className:"w-5 h-5 shrink-0"}),i.jsx("span",{className:"truncate",children:b.name}),b.type==="dir"&&i.jsx(hn,{className:`w-5 h-5 text-text-muted shrink-0 ml-1 ${j===h?"opacity-100":"opacity-0 group-hover:opacity-100"}`,rotate:-90})]}),b.type==="dir"&&i.jsx("button",{"data-select":"true",tabIndex:j===h?0:-1,onClick:N=>{N.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 ${j===h?"opacity-100":"opacity-0 group-hover:opacity-100"}`,"aria-label":`Select ${b.name}`,children:"Select"})]},b.path))})})]})})}function U1(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 DT(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 U1(r,t.map(a=>({path:a.webkitRelativePath.slice(r.length+1),file:a})))}function RT(e){return new Promise((t,n)=>e.file(t,n))}async function F1(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?F1(l,u):[{path:u,file:await RT(l)}]}))).flat()}async function OT(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 U1(n.name,await F1(n))}function IT({selectedDirectory:e,onSelect:t,onRemove:n,onRefresh:r,onInstall:a}){const[l,u]=E.useState(!1),[c,d]=E.useState(!1),[h,p]=E.useState(""),[m,x]=E.useState(null),[y,w]=E.useState(!1),C=E.useRef(null);E.useEffect(()=>{var j;(j=C.current)==null||j.setAttribute("webkitdirectory","")},[]);const _=j=>{x(j)},S=async()=>{if(!m||y)return;w(!0);const j=await t(m);if(j&&!j.success){p(j.error??"Cannot use selected folder."),w(!1);return}x(null),u(!1),w(!1)},v=async j=>{d(!0),p("");const N=await a(j);d(!1),N.success||p(N.error??"Failed to install skill package.")},b=async j=>{if(j.preventDefault(),!(!(e!=null&&e.available)||c))try{await v(await OT(j.dataTransfer))}catch(N){p(N instanceof Error?N.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(rt,{variant:"secondary",onClick:()=>u(!0),children:"Change folder"}),e&&i.jsxs(i.Fragment,{children:[i.jsx(rt,{variant:"secondary",onClick:r,children:"Refresh"}),e.custom&&i.jsx(rt,{variant:"secondary",onClick:n,children:"Use default"})]})]})]}),i.jsx("button",{type:"button",disabled:!(e!=null&&e.available)||c,onClick:()=>{var j;return(j=C.current)==null?void 0:j.click()},onDragOver:j=>j.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:j=>{var N;if((N=j.target.files)!=null&&N.length)try{v(DT(j.target.files))}catch(T){p(T instanceof Error?T.message:"Invalid skill folder.")}finally{j.target.value=""}}}),h&&i.jsx("p",{className:"mt-2 text-xs text-error",children:h}),l&&i.jsx(Td,{initialPath:(e==null?void 0:e.resolvedPath)??void 0,onSelect:_,onClose:()=>u(!1)}),i.jsx(Ml,{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 Kr({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 V1({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(ig,{})}),i.jsx(Il,{onClick:a}),!e&&r&&i.jsx(ci,{onClick:r}),!e&&l&&(t?i.jsx(Qu,{onConfirm:()=>{l==null||l()},onCancel:()=>u==null?void 0:u()}):i.jsx(Ju,{onClick:()=>l==null?void 0:l()})),c]})]})}function MT({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(V1,{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 P_({skill:e,isBuiltIn:t,isConfirmingDelete:n,onView:r,onEdit:a,onDuplicate:l,onDelete:u,onToggle:c,readOnly:d=!1}){return i.jsx(MT,{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(Kr,{enabled:e.enabled,onClick:c,label:`Activation for ${e.name}`})})}function PT({skill:e,deleting:t,error:n,onClose:r,onConfirm:a}){return i.jsxs(jt,{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(rt,{variant:"secondary",onClick:r,disabled:t,children:"Cancel"}),i.jsx(rt,{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 BT({isOpen:e}){const t=Nn(J=>J.defaults),n=Nn(J=>J.userItems),r=Nn(J=>J.projectItems),a=Nn(J=>J.items),l=Nn(J=>J.selectedDirectory),u=Nn(J=>J.diagnostics),c=Nn(J=>J.loading),d=Nn(J=>J.fetchSkills),h=Nn(J=>J.fetchSkill),p=Nn(J=>J.fetchDefaultContent),m=Nn(J=>J.createSkill),x=Nn(J=>J.updateSkill),y=Nn(J=>J.deleteSkill),w=Nn(J=>J.selectDirectory),C=Nn(J=>J.removeDirectory),_=Nn(J=>J.installSkill),S=Nn(J=>J.toggleSkill),[v,b]=E.useState(null),[j,N]=E.useState(!1),[T,D]=E.useState(""),{view:L,editingId:O,formError:M,saving:W,formData:U,setView:R,setEditingId:H,setFormError:G,setFormData:V,setSaving:Z}=$1(),{clearConfirm:X}=Yl();E.useEffect(()=>{e&&(d(),R("list"),H(null),X())},[e,d,X]);const $=(J,ie,he,ce)=>{V({name:ce??J.metadata.name,id:he??J.metadata.id,description:J.metadata.description??"",version:J.metadata.version??"1.0.0",prompt:J.prompt,isReadOnly:ie,destination:"user"})},I=async J=>{if(t.some(he=>he.id===J)){const he=await p(J);if(!he)return;$(he,!0),H(J),G(""),R("edit")}else{const he=await h(J);if(!he)return;$(he,!0),H(J),G(""),R("edit")}},B=async J=>{const he=t.some(De=>De.id===J)?await p(J):await h(J);if(!he)return;const ce=`${J}-copy-${Date.now()}`;$(he,!1,ce,`${he.metadata.name} (copy)`),H(null),G(""),R("edit")},q=()=>{V({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1,destination:"user"}),R("edit")},z=async J=>{const ie=await h(J);ie&&($(ie,!1),H(J),G(""),R("edit"))},ne=async()=>{if(!v)return;N(!0),D("");const J=await y(v.id);if(N(!1),!J.success){D(J.error??"Failed to delete skill.");return}await d(),b(null),X()},re=async()=>{const J=O??U.id;if(!J||!U.name||!U.prompt){G("Name, ID, and prompt are required.");return}Z(!0),G("");const ie={metadata:{id:J,name:U.name,description:U.description,version:U.version},prompt:U.prompt},he=O?await x(O,ie):await m(ie,U.destination);if(Z(!1),!he.success){G(he.error??"Failed to save skill.");return}R("list")},Q=J=>{V(ie=>({...ie,name:J})),O||V(ie=>({...ie,id:J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},K=U.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?U.name:O?"Edit Skill":"New Skill"}),i.jsx("button",{onClick:()=>R("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),M&&i.jsx(eo,{message:M}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(B1,{name:U.name,id:U.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:Q,onIdChange:()=>{}}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Description",value:U.description,onChange:J=>V(ie=>({...ie,description:J})),placeholder:"What this skill does...",readOnly:K}),i.jsx(Cr,{label:"Version",value:U.version,onChange:J=>V(ie=>({...ie,version:J})),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:U.prompt,onChange:J=>V(ie=>({...ie,prompt:J.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"})]}),!O&&i.jsx(Nd,{value:U.destination,onChange:J=>V(ie=>({...ie,destination:J}))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[i.jsx(rt,{variant:"secondary",onClick:()=>R("list"),children:"Cancel"}),K?i.jsx(rt,{variant:"primary",onClick:()=>{V(J=>({...J,name:J.name+" (copy)",id:`${O}-copy-${Date.now()}`,isReadOnly:!1})),H(null)},children:"Duplicate & Customize"}):i.jsx(rt,{variant:"primary",onClick:re,disabled:W||!U.name||!U.id||!U.prompt,children:W?"Saving...":"Save"})]})]});function P({items:J}){return J.map(ie=>i.jsx(P_,{skill:ie,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>I(ie.id),onEdit:()=>z(ie.id),onDuplicate:()=>B(ie.id),onDelete:()=>{D(""),b(ie)},onToggle:()=>S(ie.id),readOnly:ie.readOnly},ie.id))}return i.jsxs("div",{children:[i.jsx(PT,{skill:v,deleting:j,error:T,onClose:()=>{j||b(null)},onConfirm:ne}),i.jsx(IT,{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((J,ie)=>i.jsx("p",{children:J},`${J}-${ie}`))}),i.jsx(P1,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:q}),i.jsxs(ug,{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(J=>i.jsx(P_,{skill:J,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>I(J.id),onDuplicate:()=>B(J.id),onToggle:()=>S(J.id)},J.id))})]}),n.length>0&&i.jsx(M1,{children:i.jsx(P,{items:n})}),a.some(J=>["global-shared","selected","project-shared"].includes(J.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(P,{items:a.filter(J=>["global-shared","selected","project-shared"].includes(J.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(P,{items:r})})]})]})]})}function ta(){const e=Ft(a=>a.settings),t=Ft(a=>a.loading),n=Ft(a=>a.getSetting),r=Ft(a=>a.setSetting);return{settings:e,loading:t,getSetting:n,setSetting:r}}function $T({isOpen:e}){const{settings:t,loading:n,getSetting:r,setSetting:a}=ta(),l=t[Te.GLOBAL_INSTRUCTIONS]??"",u=n[Te.GLOBAL_INSTRUCTIONS]??!1,[c,d]=E.useState(l),[h,p]=E.useState(!1),[m,x]=E.useState(!1);E.useEffect(()=>{e&&r(Te.GLOBAL_INSTRUCTIONS)},[e,r]),E.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(rt,{variant:"secondary",onClick:w,disabled:!h,children:"Discard"}),i.jsx(rt,{variant:"primary",onClick:y,disabled:!h||C,children:m?"Saving...":"Save"})]})]})}function zT(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 Vu(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 HT({isOpen:e,isNew:t,basePresetId:n,presetName:r,mode:a,initialTokens:l,onClose:u,onSave:c}){const[d,h]=E.useState(l),[p,m]=E.useState(r),[x,y]=E.useState(a);E.useEffect(()=>{h(l),m(r)},[l,r]);const w=(b,j)=>{const N=j.startsWith("#")?zT(j):j;h(T=>({...T,[b]:N}))},C=()=>{c(p.trim()||"Untitled",{...d},x)},_=w1.reduce((b,j)=>{const N=j.category;return b[N]||(b[N]=[]),b[N].push(j),b},{}),S={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},v=$n.find(b=>b.id===n);return i.jsx(jt,{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,j])=>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:j.map(N=>i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("label",{htmlFor:N.key,className:"text-xs text-text-muted",children:N.label}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"color",id:N.key,value:Vu(d[N.key]??N.defaultValue),onChange:T=>w(N.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[N.key]??N.defaultValue,onChange:T=>w(N.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"})]})]},N.key))})]},b))]})})}function B_({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":Vu(e.tokens["color-bg-primary"]??"#000"),borderColor:Vu(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:Vu(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 UT(){const[e,t]=E.useState(null),n=Bt(U=>U.currentPreset),r=Bt(U=>U.isCustom),a=Bt(U=>U.basePreset),l=Bt(U=>U.isSystem),u=Bt(U=>U.systemDarkPreset),c=Bt(U=>U.systemLightPreset),d=Bt(U=>U.applyPreset),h=Bt(U=>U.applyUserPreset),p=Bt(U=>U.deleteUserPreset),m=Bt(U=>U.saveTheme),x=Bt(U=>U.setSystemDarkPreset),y=Bt(U=>U.setSystemLightPreset),w=Bt(U=>U.activeUserPresetId),C=Bt(U=>U.userPresets),_=$n.filter(U=>U.mode==="dark"),S=$n.filter(U=>U.mode==="light"),v=U=>{var R;if(l){const H=C[U];if(!H)return;const G=H.mode??((R=$n.find(V=>V.id===H.basePreset))==null?void 0:R.mode);G==="dark"?x(H.id):G==="light"&&y(H.id)}else h(U)},b=U=>{const R=$n.find(H=>H.id===U);R&&t({type:"new",presetIndex:C.length,basePresetId:U,presetName:R.name+" Copy",mode:R.mode??"dark",tokens:{...R.tokens}})},j=U=>{const R=C[U];if(!R)return;const H=$n.find(V=>V.id===R.basePreset),G=H?{...H.tokens,...R.tokens}:R.tokens;t({type:"edit",presetIndex:U,basePresetId:R.basePreset,presetName:R.name,mode:R.mode??"dark",tokens:G})},N=(U,R,H)=>{if(!e)return;const G=[...C];if(e.type==="new"){const V={id:"custom-"+Date.now(),name:U,basePreset:e.basePresetId,mode:H,tokens:R};G.push(V);const Z=G.length-1;Bt.setState({userPresets:G}),Bt.getState().saveUserPresets(),Bt.getState().applyUserPreset(Z)}else{const V=G[e.presetIndex];V&&(G[e.presetIndex]={...V,name:U,mode:H,tokens:R}),Bt.setState({userPresets:G}),Bt.getState().saveUserPresets(),Bt.getState().applyUserPreset(e.presetIndex)}t(null)},T=()=>{t(null)},D=(U,R)=>{U.stopPropagation(),p(R)},L=l?"system":r?a:n,O=()=>{l?(d(n),m(JSON.stringify({preset:n})).catch(()=>{})):(d("system"),m(JSON.stringify({preset:"system"})).catch(()=>{}))},M=U=>{if(l){const R=$n.find(H=>H.id===U);(R==null?void 0:R.mode)==="dark"?x(U):(R==null?void 0:R.mode)==="light"&&y(U)}else d(U),m(JSON.stringify({preset:U})).catch(()=>{})},W=U=>{const R=$n.find(H=>H.id===U.basePreset);return R?{...R.tokens,...U.tokens}:U.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:O,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:U,mode:R})=>{const H=R==="dark"?_:S,G=C.filter(V=>{var X;return(V.mode??((X=$n.find($=>$.id===V.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:U}),i.jsxs("div",{className:"flex flex-wrap gap-2",children:[H.map(V=>i.jsx(B_,{preset:V,isActive:V.id===L&&!r,isUnderlying:l&&(V.id===u||V.id===c),onClick:()=>M(V.id),onNewFrom:()=>b(V.id)},V.id)),G.map(V=>{const Z=C.indexOf(V),X=W(V);return i.jsx(B_,{preset:{id:V.id,name:V.name,tokens:X},isActive:w===V.id,isUnderlying:l&&(V.id===u||V.id===c),onClick:()=>v(Z),onEdit:()=>j(Z),onDelete:$=>D($,Z)},V.id)})]})]},U)}),e&&i.jsx(HT,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,mode:e.mode,initialTokens:e.tokens,onClose:T,onSave:N})]})}function FT(){return i.jsx(UT,{})}function VT(){const{settings:e,loading:t,getSetting:n,setSetting:r}=ta(),a=t[Te.DISPLAY_SHOW_THINKING]??!1,l=e[Te.DISPLAY_MAX_VISIBLE_ITEMS]??"300",[u,c]=E.useState(l);E.useEffect(()=>{n(Te.DISPLAY_MAX_VISIBLE_ITEMS)},[n]),E.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]=E.useState(()=>Object.fromEntries(h.map(w=>[w.key,p[w.key]==="true"])));E.useEffect(()=>{h.forEach(w=>n(w.key))},[n]),E.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(FT,{}),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(GT,{})]}),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 $_=[{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(`
62
62
  `)},{label:"Always visible scrollbar",css:["/* Force scrollbar to always show — no layout shift, no surprises */",".scrollbar-stable { overflow-y: scroll; }"].join(`
@@ -244,14 +244,14 @@ XID_Continue XIDC
244
244
  XID_Start XIDS`.split(/\s/).map(e=>[Wd(e),e])),WP=new Map([["s",xn(383)],[xn(383),"s"]]),qP=new Map([[xn(223),xn(7838)],[xn(107),xn(8490)],[xn(229),xn(8491)],[xn(969),xn(8486)]]),KP=new Map([ni(453),ni(456),ni(459),ni(498),...Jm(8072,8079),...Jm(8088,8095),...Jm(8104,8111),ni(8124),ni(8140),ni(8188)]),YP=new Map([["alnum",ht`[\p{Alpha}\p{Nd}]`],["alpha",ht`\p{Alpha}`],["ascii",ht`\p{ASCII}`],["blank",ht`[\p{Zs}\t]`],["cntrl",ht`\p{Cc}`],["digit",ht`\p{Nd}`],["graph",ht`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],["lower",ht`\p{Lower}`],["print",ht`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],["punct",ht`[\p{P}\p{S}]`],["space",ht`\p{space}`],["upper",ht`\p{Upper}`],["word",ht`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],["xdigit",ht`\p{AHex}`]]);function XP(e,t){const n=[];for(let r=e;r<=t;r++)n.push(r);return n}function ni(e){const t=xn(e);return[t.toLowerCase(),t]}function Jm(e,t){return XP(e,t).map(n=>ni(n))}var dk=new Set(["Lower","Lowercase","Upper","Uppercase","Ll","Lowercase_Letter","Lt","Titlecase_Letter","Lu","Uppercase_Letter"]);function QP(e,t){const n={accuracy:"default",asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:"ES2025",...t};hk(e);const r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:Xp(n.bestEffortTarget,"ES2024"),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};Al(e,JP,r);const a={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},l={currentFlags:a,prevFlags:null,globalFlags:a,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};Al(e,ZP,l);const u={groupsByName:l.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:l.reffedNodesByReferencer};return Al(e,e6,u),e._originMap=l.groupOriginByCopy,e._strategy=r.strategy,e}var JP={AbsenceFunction({node:e,parent:t,replaceWith:n}){const{body:r,kind:a}=e;if(a==="repeater"){const l=Dr();l.body[0].body.push(Fi({negate:!0,body:r}),Ja("Any"));const u=Dr();u.body[0].body.push(rk("greedy",0,1/0,l)),n(nn(u,t),{traverse:!0})}else throw new Error('Unsupported absence function "(?~|"')},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){const a=e.body.filter(l=>l.kind==="flags");for(let l=n+1;l<t.body.length;l++){const u=t.body[l];Fl(r,u,[]).push(...a)}},exit({node:e},{flagDirectivesByAlt:t}){var n;if((n=t.get(e))!=null&&n.length){const r=mk(t.get(e));if(r){const a=Dr({flags:r});a.body[0].body=e.body,e.body=[nn(a,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:a,remove:l,replaceWith:u},c){const{kind:d,negate:h}=e,{asciiWordBoundaries:p,avoidSubclass:m,supportedGNodes:x,wordIsAscii:y}=c;if(d==="text_segment_boundary")throw new Error(`Unsupported text segment boundary "\\${h?"Y":"y"}"`);if(d==="line_end")u(nn(Fi({body:[Ji({body:[Wp("string_end")]}),Ji({body:[Gd(10)]})]}),t));else if(d==="line_start")u(nn(xs(ht`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(d==="search_start")if(x.has(e))a.flags.sticky=!0,l();else{const w=r[n-1];if(w&&a6(w))u(nn(Fi({negate:!0}),t));else{if(m)throw new Error(ht`Uses "\G" in a way that requires a subclass`);u(ri(Wp("string_start"),t)),c.strategy="clip_search"}}else if(!(d==="string_end"||d==="string_start"))if(d==="string_end_newline")u(nn(xs(ht`(?=\n?\z)`),t));else if(d==="word_boundary"){if(!y&&!p){const w=`(?:(?<=${gs})(?!${gs})|(?<!${gs})(?=${gs}))`,C=`(?:(?<=${gs})(?=${gs})|(?<!${gs})(?!${gs}))`;u(nn(xs(h?C:w),t))}}else throw new Error(`Unexpected assertion kind "${d}"`)},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n=="string"&&!ep(n)&&(n=Zm(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!ep(r)&&(r=Zm(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){if(t.kind==="intersection"){const r=Ku({body:[e]});n(nn(r,t),{traverse:!0})}},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:a,digitIsAscii:l,spaceIsAscii:u,wordIsAscii:c}){const{kind:d,negate:h,value:p}=e;if(l&&(d==="digit"||p==="digit")){n(ri(Kp("digit",{negate:h}),t));return}if(u&&(d==="space"||p==="space")){n(nn(tp(xs(VP),h),t));return}if(c&&(d==="word"||p==="word")){n(ri(Kp("word",{negate:h}),t));return}if(d==="any")n(ri(Ja("Any"),t));else if(d==="digit")n(ri(Ja("Nd",{negate:h}),t));else if(d!=="dot")if(d==="text_segment"){if(r==="strict")throw new Error(ht`Use of "\X" requires non-strict accuracy`);const m="\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?",x=ht`\p{RI}{2}|${m}(?:\u200D${m})*`;n(nn(xs(ht`(?>\r\n|${a?ht`\p{RGI_Emoji}`:x}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(d==="hex")n(ri(Ja("AHex",{negate:h}),t));else if(d==="newline")n(nn(xs(h?`[^
245
245
  ]`:`(?>\r
246
246
  ?|[
247
- \v\f…\u2028\u2029])`),t));else if(d==="posix")if(!a&&(p==="graph"||p==="print")){if(r==="strict")throw new Error(`POSIX class "${p}" requires min target ES2024 or non-strict accuracy`);let m={graph:"!-~",print:" -~"}[p];h&&(m=`\0-${xn(m.codePointAt(0)-1)}${xn(m.codePointAt(2)+1)}-􏿿`),n(nn(xs(`[${m}]`),t))}else n(nn(tp(xs(YP.get(p)),h),t));else if(d==="property")Gg.has(Wd(p))||(e.key="sc");else if(d==="space")n(ri(Ja("space",{negate:h}),t));else if(d==="word")n(nn(tp(xs(gs),h),t));else throw new Error(`Unexpected character set kind "${d}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:a,removeAllPrevSiblings:l,removeAllNextSiblings:u}){const{kind:c,flags:d}=e;if(c==="flags")if(!d.enable&&!d.disable)r();else{const h=Dr({flags:d});h.body[0].body=u(),a(nn(h,t),{traverse:!0})}else if(c==="keep"){const h=n.body[0],m=n.body.length===1&&ek(h,{type:"Group"})&&h.body[0].body.length===1?h.body[0]:n;if(t.parent!==m||m.body.length>1)throw new Error(ht`Uses "\K" in a way that's unsupported`);const x=Fi({behind:!0});x.body[0].body=l(),a(nn(x,t))}else throw new Error(`Unexpected directive kind "${c}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw new Error('Unsupported flag "P"');if(e.textSegmentMode==="word")throw new Error('Unsupported flag "y{w}"');["digitIsAscii","extended","posixIsAscii","spaceIsAscii","wordIsAscii","textSegmentMode"].forEach(n=>delete e[n]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;const{enable:t,disable:n}=e.flags;t!=null&&t.extended&&delete t.extended,n!=null&&n.extended&&delete n.extended,t!=null&&t.dotAll&&(n!=null&&n.dotAll)&&delete t.dotAll,t!=null&&t.ignoreCase&&(n!=null&&n.ignoreCase)&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){const{kind:n}=e;n==="lookbehind"&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){const{kind:r}=e;if(r==="fail")n(nn(Fi({negate:!0}),t));else throw new Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type==="Quantifier"){const t=Dr();t.body[0].body.push(e.body),e.body=nn(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){const n=[];let r=!1,a=!1;for(const l of e.body)if(l.body.length===1&&l.body[0].kind==="search_start")l.body.pop();else{const u=gk(l.body);u?(r=!0,Array.isArray(u)?n.push(...u):n.push(u)):a=!0}r&&!a&&n.forEach(l=>t.add(l))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t==="strict"&&n&&r)throw new Error(ht`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n=="string"&&!ep(n)&&(n=Zm(n,t),e.ref=n)}},ZP={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){const{orphan:r,ref:a}=e;r||n.set(e,[...t.get(a).map(({node:l})=>l)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:a,groupsByName:l,multiplexCapturesToLeftByRef:u,openRefs:c,reffedNodesByReferencer:d}){const h=a.get(e);if(h&&c.has(e.number)){const m=ri(mS(e.number),t);d.set(m,c.get(e.number)),n(m);return}c.set(e.number,e),u.set(e.number,[]),e.name&&Fl(u,e.name,[]);const p=u.get(e.name??e.number);for(let m=0;m<p.length;m++){const x=p[m];if(h===x.node||h&&h===x.origin||e===x.origin){p.splice(m,1);break}}if(u.get(e.number).push({node:e,origin:h}),e.name&&u.get(e.name).push({node:e,origin:h}),e.name){const m=Fl(l,e.name,new Map);let x=!1;if(h)x=!0;else for(const y of m.values())if(!y.hasDuplicateNameToRemove){x=!0;break}l.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:x})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=fd(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){const{isRecursive:a,ref:l}=e;if(a){let p=t;for(;(p=p.parent)&&!(p.type==="CapturingGroup"&&(p.name===l||p.number===l)););r.reffedNodesByReferencer.set(e,p);return}const u=r.subroutineRefMap.get(l),c=l===0,d=c?mS(0):fk(u,r.groupOriginByCopy,null);let h=d;if(!c){const p=mk(r6(u,x=>x.type==="Group"&&!!x.flags)),m=p?fd(r.globalFlags,p):r.globalFlags;t6(m,r.currentFlags)||(h=Dr({flags:s6(m)}),h.body[0].body.push(d))}n(nn(h,t),{traverse:!c})}},e6={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}const l=r.reffedNodesByReferencer.get(e).filter(u=>n6(u,e));if(!l.length)n(nn(Fi({negate:!0}),t));else if(l.length>1){const u=Dr({atomic:!0,body:l.reverse().map(c=>Ji({body:[qp(c.number)]}))});n(nn(u,t))}else e.ref=l[0].number},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){const n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let r=0;r<n;r++){const a=nk();e.body.at(-1).body.push(a)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function hk(e){Al(e,{"*"({node:t,parent:n}){t.parent=n}})}function t6(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function n6(e,t){let n=t;do{if(n.type==="Regex")return!1;if(n.type==="Alternative")continue;if(n===e)return!1;const r=pk(n.parent);for(const a of r){if(a===n)break;if(a===e||xk(a,e))return!0}}while(n=n.parent);throw new Error("Unexpected path")}function fk(e,t,n,r){const a=Array.isArray(e)?[]:{};for(const[l,u]of Object.entries(e))l==="parent"?a.parent=Array.isArray(n)?r:n:u&&typeof u=="object"?a[l]=fk(u,t,a,n):(l==="type"&&u==="CapturingGroup"&&t.set(a,t.get(e)??e),a[l]=u);return a}function mS(e){const t=sk(e);return t.isRecursive=!0,t}function r6(e,t){const n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function Zm(e,t){if(t.has(e))return t.get(e);const n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/ug,"_")}`;return t.set(e,n),n}function mk(e){const t=["dotAll","ignoreCase"],n={enable:{},disable:{}};return e.forEach(({flags:r})=>{t.forEach(a=>{var l,u;(l=r.enable)!=null&&l[a]&&(delete n.disable[a],n.enable[a]=!0),(u=r.disable)!=null&&u[a]&&(n.disable[a]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function s6({dotAll:e,ignoreCase:t}){const n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function pk(e){if(!e)throw new Error("Node expected");const{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function gk(e){const t=e.find(n=>n.kind==="search_start"||o6(n,{negate:!1})||!i6(n));if(!t)return null;if(t.kind==="search_start")return t;if(t.type==="LookaroundAssertion")return t.body[0].body[0];if(t.type==="CapturingGroup"||t.type==="Group"){const n=[];for(const r of t.body){const a=gk(r.body);if(!a)return null;Array.isArray(a)?n.push(...a):n.push(a)}return n}return null}function xk(e,t){const n=pk(e)??[];for(const r of n)if(r===t||xk(r,t))return!0;return!1}function i6({type:e}){return e==="Assertion"||e==="Directive"||e==="LookaroundAssertion"}function a6(e){const t=["Character","CharacterClass","CharacterSet"];return t.includes(e.type)||e.type==="Quantifier"&&e.min&&t.includes(e.body.type)}function o6(e,t){const n={negate:null,...t};return e.type==="LookaroundAssertion"&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&ek(e.body[0],{type:"Assertion",kind:"search_start"})}function ep(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function xs(e,t){const r=tk(e,{...t,unicodePropertyMap:Gg}).body;return r.length>1||r[0].body.length>1?Dr({body:r}):r[0].body[0]}function tp(e,t){return e.negate=t,e}function ri(e,t){return e.parent=t,e}function nn(e,t){return hk(e),e.parent=t,e}function l6(e,t){const n=ck(t),r=Xp(n.target,"ES2024"),a=Xp(n.target,"ES2025"),l=n.rules.recursionLimit;if(!Number.isInteger(l)||l<2||l>20)throw new Error("Invalid recursionLimit; use 2-20");let u=null,c=null;if(!a){const y=[e.flags.ignoreCase];Al(e,c6,{getCurrentModI:()=>y.at(-1),popModI(){y.pop()},pushModI(w){y.push(w)},setHasCasedChar(){y.at(-1)?u=!0:c=!0}})}const d={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||u)&&!c)};let h=e;const p={accuracy:n.accuracy,appliedGlobalFlags:d,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:h,originMap:e._originMap,recursionLimit:l,useAppliedIgnoreCase:!!(!a&&u&&c),useFlagMods:a,useFlagV:r,verbose:n.verbose};function m(y){return p.lastNode=h,h=y,UP(u6[y.type],`Unexpected node type "${y.type}"`)(y,p,m)}const x={pattern:e.body.map(m).join("|"),flags:m(e.flags),options:{...e.options}};return r||(delete x.options.force.v,x.options.disable.v=!0,x.options.unicodeSetsPlugin=null),x._captureTransfers=new Map,x._hiddenCaptures=[],p.captureMap.forEach((y,w)=>{y.hidden&&x._hiddenCaptures.push(w),y.transferTo&&Fl(x._captureTransfers,y.transferTo,[]).push(w)}),x}var c6={"*":{enter({node:e},t){if(gS(e)){const n=t.getCurrentModI();t.pushModI(e.flags?fd({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){gS(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){Wg(xn(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),yk(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind==="property"&&dk.has(e.value)&&t.setHasCasedChar()}},u6={Alternative({body:e},t,n){return e.map(n).join("")},Assertion({kind:e,negate:t}){if(e==="string_end")return"$";if(e==="string_start")return"^";if(e==="word_boundary")return t?ht`\B`:ht`\b`;throw new Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!="number")throw new Error("Unexpected named backref in transformed AST");if(!t.useFlagMods&&t.accuracy==="strict"&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw new Error("Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy");return"\\"+e},CapturingGroup(e,t,n){const{body:r,name:a,number:l}=e,u={ignoreCase:t.currentFlags.ignoreCase},c=t.originMap.get(e);return c&&(u.hidden=!0,l>c.number&&(u.transferTo=c.number)),t.captureMap.set(l,u),`(${a?`?<${a}>`:""}${r.map(n).join("|")})`},Character({value:e},t){const n=xn(e),r=Va(e,{escDigit:t.lastNode.type==="Backreference",inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&Wg(n)){const a=uk(n);return t.inCharClass?a.join(""):a.length>1?`[${a.join("")}]`:a[0]}return n},CharacterClass(e,t,n){const{kind:r,negate:a,parent:l}=e;let{body:u}=e;if(r==="intersection"&&!t.useFlagV)throw new Error("Use of character class intersection requires min target ES2024");Ir.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&u.some(xS)&&(u=[Gd(45),...u.filter(h=>!xS(h))]);const c=()=>`[${a?"^":""}${u.map(n).join(r==="intersection"?"&&":"")}]`;if(!t.inCharClass){if((!t.useFlagV||Ir.bugNestedClassIgnoresNegation)&&!a){const p=u.filter(m=>m.type==="CharacterClass"&&m.kind==="union"&&m.negate);if(p.length){const m=Dr(),x=m.body[0];return m.parent=l,x.parent=m,u=u.filter(y=>!p.includes(y)),e.body=u,u.length?(e.parent=x,x.body.push(e)):m.body.pop(),p.forEach(y=>{const w=Ji({body:[y]});y.parent=w,w.parent=m,m.body.push(w)}),n(m)}}t.inCharClass=!0;const h=c();return t.inCharClass=!1,h}const d=u[0];if(r==="union"&&!a&&d&&((!t.useFlagV||!t.verbose)&&l.kind==="union"&&!(Ir.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&l.kind==="intersection"&&u.length===1&&d.type!=="CharacterClassRange"))return u.map(n).join("");if(!t.useFlagV&&l.type==="CharacterClass")throw new Error("Uses nested character class in a way that requires min target ES2024");return c()},CharacterClassRange(e,t){const n=e.min.value,r=e.max.value,a={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},l=Va(n,a),u=Va(r,a),c=new Set;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){const d=yk(e);p6(d).forEach(p=>{c.add(Array.isArray(p)?`${Va(p[0],a)}-${Va(p[1],a)}`:Va(p,a))})}return`${l}-${u}${[...c].join("")}`},CharacterSet({kind:e,negate:t,value:n,key:r},a){if(e==="dot")return a.currentFlags.dotAll?a.appliedGlobalFlags.dotAll||a.useFlagMods?".":"[^]":ht`[^\n]`;if(e==="digit")return t?ht`\D`:ht`\d`;if(e==="property"){if(a.useAppliedIgnoreCase&&a.currentFlags.ignoreCase&&dk.has(n))throw new Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?ht`\P`:ht`\p`}{${r?`${r}=`:""}${n}}`}if(e==="word")return t?ht`\W`:ht`\w`;throw new Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?"i":"")+(e.dotAll?"s":"")+(e.sticky?"y":"")},Group({atomic:e,body:t,flags:n,parent:r},a,l){const u=a.currentFlags;n&&(a.currentFlags=fd(u,n));const c=t.map(l).join("|"),d=!a.verbose&&t.length===1&&r.type!=="Quantifier"&&!e&&(!a.useFlagMods||!n)?c:`(?${g6(e,n,a.useFlagMods)}${c})`;return a.currentFlags=u,d},LookaroundAssertion({body:e,kind:t,negate:n},r,a){return`(?${`${t==="lookahead"?"":"<"}${n?"!":"="}`}${e.map(a).join("|")})`},Quantifier(e,t,n){return n(e.body)+x6(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw new Error("Unexpected non-recursive subroutine in transformed AST");const r=n.recursionLimit;return t===0?`(?R=${r})`:ht`\g<${t}&R=${r}>`}},d6=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),h6=new Set(["-","\\","]","^","["]),f6=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),pS=new Map([[9,ht`\t`],[10,ht`\n`],[11,ht`\v`],[12,ht`\f`],[13,ht`\r`],[8232,ht`\u2028`],[8233,ht`\u2029`],[65279,ht`\uFEFF`]]),m6=new RegExp("^\\p{Cased}$","u");function Wg(e){return m6.test(e)}function yk(e,t){const n=!!(t!=null&&t.firstOnly),r=e.min.value,a=e.max.value,l=[];if(r<65&&(a===65535||a>=131071)||r===65536&&a>=131071)return l;for(let u=r;u<=a;u++){const c=xn(u);if(!Wg(c))continue;const d=uk(c).filter(h=>{const p=h.codePointAt(0);return p<r||p>a});if(d.length&&(l.push(...d),n))break}return l}function Va(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(pS.has(e))return pS.get(e);if(e<32||e>126&&e<160||e>262143||t&&y6(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,"0")}`;const a=n?r?f6:h6:d6,l=xn(e);return(a.has(l)?"\\":"")+l}function p6(e){const t=e.map(a=>a.codePointAt(0)).sort((a,l)=>a-l),n=[];let r=null;for(let a=0;a<t.length;a++)t[a+1]===t[a]+1?r??(r=t[a]):r===null?n.push(t[a]):(n.push([r,t[a]]),r=null);return n}function g6(e,t,n){if(e)return">";let r="";if(t&&n){const{enable:a,disable:l}=t;r=(a!=null&&a.ignoreCase?"i":"")+(a!=null&&a.dotAll?"s":"")+(l?"-":"")+(l!=null&&l.ignoreCase?"i":"")+(l!=null&&l.dotAll?"s":"")}return`${r}:`}function x6({kind:e,max:t,min:n}){let r;return!n&&t===1?r="?":!n&&t===1/0?r="*":n===1&&t===1/0?r="+":n===t?r=`{${n}}`:r=`{${n},${t===1/0?"":t}}`,r+{greedy:"",lazy:"?",possessive:"+"}[e]}function gS({type:e}){return e==="CapturingGroup"||e==="Group"||e==="LookaroundAssertion"}function y6(e){return e>47&&e<58}function xS({type:e,value:t}){return e==="Character"&&t===45}var si,_s,Wi,ii,qi,Wl,Qp,hi,b6=(hi=class extends RegExp{constructor(n,r,a){var t=(...z9)=>(super(...z9),Ii(this,Wl),Ii(this,si,new Map),Ii(this,_s,null),Ii(this,Wi),Ii(this,ii,null),Ii(this,qi,null),_e(this,"rawOptions",{}),this);const l=!!(a!=null&&a.lazyCompile);if(n instanceof RegExp){if(a)throw new Error("Cannot provide options when copying a regexp");const u=n;t(u,r),Tr(this,Wi,u.source),u instanceof hi&&(Tr(this,si,Bn(u,si)),Tr(this,ii,Bn(u,ii)),Tr(this,qi,Bn(u,qi)),this.rawOptions=u.rawOptions)}else{const u={hiddenCaptures:[],strategy:null,transfers:[],...a};t(l?"":n,r),Tr(this,Wi,n),Tr(this,si,_6(u.hiddenCaptures,u.transfers)),Tr(this,qi,u.strategy),this.rawOptions=a??{}}l||Tr(this,_s,this)}get source(){return Bn(this,Wi)||"(?:)"}exec(n){if(!Bn(this,_s)){const{lazyCompile:l,...u}=this.rawOptions;Tr(this,_s,new hi(Bn(this,Wi),this.flags,u))}const r=this.global||this.sticky,a=this.lastIndex;if(Bn(this,qi)==="clip_search"&&r&&a){this.lastIndex=0;const l=cm(this,Wl,Qp).call(this,n.slice(a));return l&&(v6(l,a,n,this.hasIndices),this.lastIndex+=a),l}return cm(this,Wl,Qp).call(this,n)}},si=new WeakMap,_s=new WeakMap,Wi=new WeakMap,ii=new WeakMap,qi=new WeakMap,Wl=new WeakSet,Qp=function(n){Bn(this,_s).lastIndex=this.lastIndex;const r=Qv(hi.prototype,this,"exec").call(Bn(this,_s),n);if(this.lastIndex=Bn(this,_s).lastIndex,!r||!Bn(this,si).size)return r;const a=[...r];r.length=1;let l;this.hasIndices&&(l=[...r.indices],r.indices.length=1);const u=[0];for(let c=1;c<a.length;c++){const{hidden:d,transferTo:h}=Bn(this,si).get(c)??{};if(d?u.push(null):(u.push(r.length),r.push(a[c]),this.hasIndices&&r.indices.push(l[c])),h&&a[c]!==void 0){const p=u[h];if(!p)throw new Error(`Invalid capture transfer to "${p}"`);if(r[p]=a[c],this.hasIndices&&(r.indices[p]=l[c]),r.groups){Bn(this,ii)||Tr(this,ii,S6(this.source));const m=Bn(this,ii).get(h);m&&(r.groups[m]=a[c],this.hasIndices&&(r.indices.groups[m]=l[c]))}}}return r},hi);function v6(e,t,n,r){if(e.index+=t,e.input=n,r){const a=e.indices;for(let u=0;u<a.length;u++){const c=a[u];c&&(a[u]=[c[0]+t,c[1]+t])}const l=a.groups;l&&Object.keys(l).forEach(u=>{const c=l[u];c&&(l[u]=[c[0]+t,c[1]+t])})}}function _6(e,t){const n=new Map;for(const r of e)n.set(r,{hidden:!0});for(const[r,a]of t)for(const l of a)Fl(n,l,{}).transferTo=r;return n}function S6(e){const t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map;let r=0,a=0,l;for(;l=t.exec(e);){const{0:u,groups:{capture:c,name:d}}=l;u==="["?r++:r?u==="]"&&r--:c&&(a++,d&&n.set(a,d))}return n}function w6(e,t){const n=C6(e,t);return n.options?new b6(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function C6(e,t){const n=ck(t),r=tk(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:Gg}),a=QP(r,{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),l=l6(a,n),u=zP(l.pattern,{captureTransfers:l._captureTransfers,hiddenCaptures:l._hiddenCaptures,mode:"external"}),c=BP(u.pattern),d=PP(c.pattern,{captureTransfers:u.captureTransfers,hiddenCaptures:u.hiddenCaptures}),h={pattern:d.pattern,flags:`${n.hasIndices?"d":""}${n.global?"g":""}${l.flags}${l.options.disable.v?"u":"v"}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw new Error("Lazy compilation requires subclass")}else{const p=d.hiddenCaptures.sort((w,C)=>w-C),m=Array.from(d.captureTransfers),x=a._strategy,y=h.pattern.length>=n.lazyCompileLength;(p.length||m.length||x||y)&&(h.options={...p.length&&{hiddenCaptures:p},...m.length&&{transfers:m},...x&&{strategy:x},...y&&{lazyCompile:y}})}return h}function bk(e,t){return w6(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function k6(e={}){const t={target:"auto",cache:new Map,...e};return t.regexConstructor||(t.regexConstructor=n=>bk(n,{target:t.target})),{createScanner(n){return new HM(n,t)},createString(n){return{content:n}}}}Xw(Tg({bundledLanguages:()=>Md,bundledLanguagesAlias:()=>Lg,bundledLanguagesBase:()=>Ag,bundledLanguagesInfo:()=>Id,bundledThemes:()=>Rg,bundledThemesInfo:()=>Dg,codeToHast:()=>FC,codeToHtml:()=>UC,codeToTokens:()=>VC,codeToTokensBase:()=>GC,codeToTokensWithThemes:()=>WC,createHighlighter:()=>Vd,createJavaScriptRegexEngine:()=>k6,createOnigurumaEngine:()=>Zw,defaultJavaScriptRegexConstructor:()=>bk,getLastGrammarState:()=>KC,getSingletonHighlighter:()=>qC,loadWasm:()=>Ig}),zM);let np=null;const Ll=new Set,Lu=new Map,yS=["typescript","javascript","tsx","jsx","python","bash","json","css","html","sql","yaml","markdown","diff","rust","go","java","c","cpp","ruby","toml","scss","graphql","docker","powershell"],j6=["github-dark-default","vitesse-light","monokai","dracula","nord","everforest-light","rose-pine-dawn","synthwave-84","one-dark-pro","night-owl","catppuccin-mocha","rose-pine","kanagawa-wave","light-plus"],rp={dark:"github-dark-default",light:"vitesse-light",monokai:"monokai",dracula:"dracula",nord:"nord","rose-pine-dawn":"rose-pine-dawn","everforest-light":"everforest-light","synthwave-84":"synthwave-84","one-dark-pro":"one-dark-pro","night-owl":"night-owl","catppuccin-mocha":"catppuccin-mocha","rose-pine":"rose-pine","kanagawa-wave":"kanagawa-wave","light-plus":"light-plus"};function E6(){return{name:"line-numbers",line(e,t){e.properties["data-line"]=String(t+1)}}}async function vk(){return np||(np=Vd({themes:j6,langs:yS}).then(e=>(yS.forEach(t=>Ll.add(t)),e))),np}async function N6(e){if(Ll.has(e))return;if(Lu.has(e))return Lu.get(e);const t=(async()=>{const n=await vk(),r=Md[e];if(r){await n.loadLanguage(r),Ll.add(e);return}try{const a=await ee(()=>import(`shiki/langs/${e}.mjs`),[]);a.default&&(await n.loadLanguage(a.default),Ll.add(e))}catch(a){console.warn(`Failed to load language ${e}:`,a)}})();Lu.set(e,t),await t,Lu.delete(e)}const xl=new Map,T6=50;function A6(e,t,n){return`${e}|${t}|${n}`}async function _k(e,t,n="github-dark-default"){t!=="text"&&!Ll.has(t)&&await N6(t);const r=A6(e,t,n),a=xl.get(r);if(a)return a;const u=(await vk()).codeToHtml(e,{lang:t,theme:n,transformers:[E6()]});if(xl.size>=T6){const c=xl.keys().next().value;c&&xl.delete(c)}return xl.set(r,u),u}const L6={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",swift:"swift",kt:"kotlin",scala:"scala",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",md:"markdown",markdown:"markdown",toml:"toml",ini:"ini",conf:"ini",dockerfile:"docker",makefile:"makefile",cmake:"cmake",graphql:"graphql",gql:"graphql",vue:"vue",svelte:"svelte"};function Yd(e){var a;if(!e)return"text";const t=e.split("/").pop()??"",n=t.toLowerCase();if(n==="dockerfile")return"docker";if(n==="makefile")return"makefile";if(n==="cmakelists.txt")return"cmake";const r=(a=t.split(".").pop())==null?void 0:a.toLowerCase();return r?L6[r]??"text":"text"}function Sk(){const e=Pt(r=>r.currentPreset),t=Pt(r=>r.isCustom),n=Pt(r=>r.basePreset);return D6(e,t,n)}function D6(e,t,n){return t?n&&n!=="system"&&rp[n]?rp[n]??"github-dark-default":"github-dark-default":rp[e]??"github-dark-default"}function wk(e=2e3){const[t,n]=E.useState(!1),r=E.useCallback(async a=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(a);else{const l=document.createElement("textarea");l.value=a,l.style.position="fixed",l.style.left="-9999px",document.body.appendChild(l),l.select(),document.execCommand("copy"),document.body.removeChild(l)}n(!0),setTimeout(()=>n(!1),e)}catch(l){console.error("Failed to copy:",l)}},[e]);return{copied:t,copy:r}}const R6=E.memo(function({language:t,codeString:n,showSyntaxHighlighting:r}){const{copied:a,copy:l}=wk(),[u,c]=E.useState(null),d=Sk(),h=E.useRef(n);return E.useEffect(()=>{r&&(h.current=n,_k(n,t,d).then(p=>{h.current===n&&c(p)}))},[n,t,d,r]),i.jsxs("div",{className:"relative group my-1.5 rounded overflow-hidden",children:[i.jsxs("div",{className:"absolute bottom-0 right-0 flex items-center gap-2 px-2 py-1 text-xs text-text-muted/70 bg-bg-tertiary/60 rounded-tl rounded-tr z-10",children:[i.jsx("span",{children:t}),i.jsx("button",{type:"button",onClick:p=>{p.preventDefault(),p.stopPropagation(),l(n)},className:"opacity-0 group-hover:opacity-100 transition-opacity hover:text-text-primary p-0.5",title:"Copy code",children:a?i.jsx(Mr,{}):i.jsx(Rl,{})})]}),r&&u?i.jsx("div",{className:"min-w-0",dangerouslySetInnerHTML:{__html:u}}):i.jsx("div",{className:"overflow-x-auto",children:i.jsx("pre",{className:"my-0 px-4 py-3 overflow-x-auto font-mono text-sm whitespace-pre-wrap break-word",children:i.jsx("code",{className:`language-${t}`,children:n})})})]})});function O6(e,t){const n=e?"text-text-muted":"text-text-heading",r=e?"text-text-secondary":"text-text-bold";return{code({className:a,children:l,...u}){const c=/language-(\w+)/.exec(a||"");if(!c&&!String(l).includes(`
247
+ \v\f…\u2028\u2029])`),t));else if(d==="posix")if(!a&&(p==="graph"||p==="print")){if(r==="strict")throw new Error(`POSIX class "${p}" requires min target ES2024 or non-strict accuracy`);let m={graph:"!-~",print:" -~"}[p];h&&(m=`\0-${xn(m.codePointAt(0)-1)}${xn(m.codePointAt(2)+1)}-􏿿`),n(nn(xs(`[${m}]`),t))}else n(nn(tp(xs(YP.get(p)),h),t));else if(d==="property")Gg.has(Wd(p))||(e.key="sc");else if(d==="space")n(ri(Ja("space",{negate:h}),t));else if(d==="word")n(nn(tp(xs(gs),h),t));else throw new Error(`Unexpected character set kind "${d}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:a,removeAllPrevSiblings:l,removeAllNextSiblings:u}){const{kind:c,flags:d}=e;if(c==="flags")if(!d.enable&&!d.disable)r();else{const h=Dr({flags:d});h.body[0].body=u(),a(nn(h,t),{traverse:!0})}else if(c==="keep"){const h=n.body[0],m=n.body.length===1&&ek(h,{type:"Group"})&&h.body[0].body.length===1?h.body[0]:n;if(t.parent!==m||m.body.length>1)throw new Error(ht`Uses "\K" in a way that's unsupported`);const x=Fi({behind:!0});x.body[0].body=l(),a(nn(x,t))}else throw new Error(`Unexpected directive kind "${c}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw new Error('Unsupported flag "P"');if(e.textSegmentMode==="word")throw new Error('Unsupported flag "y{w}"');["digitIsAscii","extended","posixIsAscii","spaceIsAscii","wordIsAscii","textSegmentMode"].forEach(n=>delete e[n]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;const{enable:t,disable:n}=e.flags;t!=null&&t.extended&&delete t.extended,n!=null&&n.extended&&delete n.extended,t!=null&&t.dotAll&&(n!=null&&n.dotAll)&&delete t.dotAll,t!=null&&t.ignoreCase&&(n!=null&&n.ignoreCase)&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){const{kind:n}=e;n==="lookbehind"&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){const{kind:r}=e;if(r==="fail")n(nn(Fi({negate:!0}),t));else throw new Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type==="Quantifier"){const t=Dr();t.body[0].body.push(e.body),e.body=nn(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){const n=[];let r=!1,a=!1;for(const l of e.body)if(l.body.length===1&&l.body[0].kind==="search_start")l.body.pop();else{const u=gk(l.body);u?(r=!0,Array.isArray(u)?n.push(...u):n.push(u)):a=!0}r&&!a&&n.forEach(l=>t.add(l))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t==="strict"&&n&&r)throw new Error(ht`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n=="string"&&!ep(n)&&(n=Zm(n,t),e.ref=n)}},ZP={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){const{orphan:r,ref:a}=e;r||n.set(e,[...t.get(a).map(({node:l})=>l)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:a,groupsByName:l,multiplexCapturesToLeftByRef:u,openRefs:c,reffedNodesByReferencer:d}){const h=a.get(e);if(h&&c.has(e.number)){const m=ri(mS(e.number),t);d.set(m,c.get(e.number)),n(m);return}c.set(e.number,e),u.set(e.number,[]),e.name&&Fl(u,e.name,[]);const p=u.get(e.name??e.number);for(let m=0;m<p.length;m++){const x=p[m];if(h===x.node||h&&h===x.origin||e===x.origin){p.splice(m,1);break}}if(u.get(e.number).push({node:e,origin:h}),e.name&&u.get(e.name).push({node:e,origin:h}),e.name){const m=Fl(l,e.name,new Map);let x=!1;if(h)x=!0;else for(const y of m.values())if(!y.hasDuplicateNameToRemove){x=!0;break}l.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:x})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=fd(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){const{isRecursive:a,ref:l}=e;if(a){let p=t;for(;(p=p.parent)&&!(p.type==="CapturingGroup"&&(p.name===l||p.number===l)););r.reffedNodesByReferencer.set(e,p);return}const u=r.subroutineRefMap.get(l),c=l===0,d=c?mS(0):fk(u,r.groupOriginByCopy,null);let h=d;if(!c){const p=mk(r6(u,x=>x.type==="Group"&&!!x.flags)),m=p?fd(r.globalFlags,p):r.globalFlags;t6(m,r.currentFlags)||(h=Dr({flags:s6(m)}),h.body[0].body.push(d))}n(nn(h,t),{traverse:!c})}},e6={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}const l=r.reffedNodesByReferencer.get(e).filter(u=>n6(u,e));if(!l.length)n(nn(Fi({negate:!0}),t));else if(l.length>1){const u=Dr({atomic:!0,body:l.reverse().map(c=>Ji({body:[qp(c.number)]}))});n(nn(u,t))}else e.ref=l[0].number},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){const n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let r=0;r<n;r++){const a=nk();e.body.at(-1).body.push(a)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function hk(e){Al(e,{"*"({node:t,parent:n}){t.parent=n}})}function t6(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function n6(e,t){let n=t;do{if(n.type==="Regex")return!1;if(n.type==="Alternative")continue;if(n===e)return!1;const r=pk(n.parent);for(const a of r){if(a===n)break;if(a===e||xk(a,e))return!0}}while(n=n.parent);throw new Error("Unexpected path")}function fk(e,t,n,r){const a=Array.isArray(e)?[]:{};for(const[l,u]of Object.entries(e))l==="parent"?a.parent=Array.isArray(n)?r:n:u&&typeof u=="object"?a[l]=fk(u,t,a,n):(l==="type"&&u==="CapturingGroup"&&t.set(a,t.get(e)??e),a[l]=u);return a}function mS(e){const t=sk(e);return t.isRecursive=!0,t}function r6(e,t){const n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function Zm(e,t){if(t.has(e))return t.get(e);const n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/ug,"_")}`;return t.set(e,n),n}function mk(e){const t=["dotAll","ignoreCase"],n={enable:{},disable:{}};return e.forEach(({flags:r})=>{t.forEach(a=>{var l,u;(l=r.enable)!=null&&l[a]&&(delete n.disable[a],n.enable[a]=!0),(u=r.disable)!=null&&u[a]&&(n.disable[a]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function s6({dotAll:e,ignoreCase:t}){const n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function pk(e){if(!e)throw new Error("Node expected");const{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function gk(e){const t=e.find(n=>n.kind==="search_start"||o6(n,{negate:!1})||!i6(n));if(!t)return null;if(t.kind==="search_start")return t;if(t.type==="LookaroundAssertion")return t.body[0].body[0];if(t.type==="CapturingGroup"||t.type==="Group"){const n=[];for(const r of t.body){const a=gk(r.body);if(!a)return null;Array.isArray(a)?n.push(...a):n.push(a)}return n}return null}function xk(e,t){const n=pk(e)??[];for(const r of n)if(r===t||xk(r,t))return!0;return!1}function i6({type:e}){return e==="Assertion"||e==="Directive"||e==="LookaroundAssertion"}function a6(e){const t=["Character","CharacterClass","CharacterSet"];return t.includes(e.type)||e.type==="Quantifier"&&e.min&&t.includes(e.body.type)}function o6(e,t){const n={negate:null,...t};return e.type==="LookaroundAssertion"&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&ek(e.body[0],{type:"Assertion",kind:"search_start"})}function ep(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function xs(e,t){const r=tk(e,{...t,unicodePropertyMap:Gg}).body;return r.length>1||r[0].body.length>1?Dr({body:r}):r[0].body[0]}function tp(e,t){return e.negate=t,e}function ri(e,t){return e.parent=t,e}function nn(e,t){return hk(e),e.parent=t,e}function l6(e,t){const n=ck(t),r=Xp(n.target,"ES2024"),a=Xp(n.target,"ES2025"),l=n.rules.recursionLimit;if(!Number.isInteger(l)||l<2||l>20)throw new Error("Invalid recursionLimit; use 2-20");let u=null,c=null;if(!a){const y=[e.flags.ignoreCase];Al(e,c6,{getCurrentModI:()=>y.at(-1),popModI(){y.pop()},pushModI(w){y.push(w)},setHasCasedChar(){y.at(-1)?u=!0:c=!0}})}const d={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||u)&&!c)};let h=e;const p={accuracy:n.accuracy,appliedGlobalFlags:d,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:h,originMap:e._originMap,recursionLimit:l,useAppliedIgnoreCase:!!(!a&&u&&c),useFlagMods:a,useFlagV:r,verbose:n.verbose};function m(y){return p.lastNode=h,h=y,UP(u6[y.type],`Unexpected node type "${y.type}"`)(y,p,m)}const x={pattern:e.body.map(m).join("|"),flags:m(e.flags),options:{...e.options}};return r||(delete x.options.force.v,x.options.disable.v=!0,x.options.unicodeSetsPlugin=null),x._captureTransfers=new Map,x._hiddenCaptures=[],p.captureMap.forEach((y,w)=>{y.hidden&&x._hiddenCaptures.push(w),y.transferTo&&Fl(x._captureTransfers,y.transferTo,[]).push(w)}),x}var c6={"*":{enter({node:e},t){if(gS(e)){const n=t.getCurrentModI();t.pushModI(e.flags?fd({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){gS(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){Wg(xn(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),yk(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind==="property"&&dk.has(e.value)&&t.setHasCasedChar()}},u6={Alternative({body:e},t,n){return e.map(n).join("")},Assertion({kind:e,negate:t}){if(e==="string_end")return"$";if(e==="string_start")return"^";if(e==="word_boundary")return t?ht`\B`:ht`\b`;throw new Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!="number")throw new Error("Unexpected named backref in transformed AST");if(!t.useFlagMods&&t.accuracy==="strict"&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw new Error("Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy");return"\\"+e},CapturingGroup(e,t,n){const{body:r,name:a,number:l}=e,u={ignoreCase:t.currentFlags.ignoreCase},c=t.originMap.get(e);return c&&(u.hidden=!0,l>c.number&&(u.transferTo=c.number)),t.captureMap.set(l,u),`(${a?`?<${a}>`:""}${r.map(n).join("|")})`},Character({value:e},t){const n=xn(e),r=Va(e,{escDigit:t.lastNode.type==="Backreference",inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&Wg(n)){const a=uk(n);return t.inCharClass?a.join(""):a.length>1?`[${a.join("")}]`:a[0]}return n},CharacterClass(e,t,n){const{kind:r,negate:a,parent:l}=e;let{body:u}=e;if(r==="intersection"&&!t.useFlagV)throw new Error("Use of character class intersection requires min target ES2024");Ir.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&u.some(xS)&&(u=[Gd(45),...u.filter(h=>!xS(h))]);const c=()=>`[${a?"^":""}${u.map(n).join(r==="intersection"?"&&":"")}]`;if(!t.inCharClass){if((!t.useFlagV||Ir.bugNestedClassIgnoresNegation)&&!a){const p=u.filter(m=>m.type==="CharacterClass"&&m.kind==="union"&&m.negate);if(p.length){const m=Dr(),x=m.body[0];return m.parent=l,x.parent=m,u=u.filter(y=>!p.includes(y)),e.body=u,u.length?(e.parent=x,x.body.push(e)):m.body.pop(),p.forEach(y=>{const w=Ji({body:[y]});y.parent=w,w.parent=m,m.body.push(w)}),n(m)}}t.inCharClass=!0;const h=c();return t.inCharClass=!1,h}const d=u[0];if(r==="union"&&!a&&d&&((!t.useFlagV||!t.verbose)&&l.kind==="union"&&!(Ir.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&l.kind==="intersection"&&u.length===1&&d.type!=="CharacterClassRange"))return u.map(n).join("");if(!t.useFlagV&&l.type==="CharacterClass")throw new Error("Uses nested character class in a way that requires min target ES2024");return c()},CharacterClassRange(e,t){const n=e.min.value,r=e.max.value,a={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},l=Va(n,a),u=Va(r,a),c=new Set;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){const d=yk(e);p6(d).forEach(p=>{c.add(Array.isArray(p)?`${Va(p[0],a)}-${Va(p[1],a)}`:Va(p,a))})}return`${l}-${u}${[...c].join("")}`},CharacterSet({kind:e,negate:t,value:n,key:r},a){if(e==="dot")return a.currentFlags.dotAll?a.appliedGlobalFlags.dotAll||a.useFlagMods?".":"[^]":ht`[^\n]`;if(e==="digit")return t?ht`\D`:ht`\d`;if(e==="property"){if(a.useAppliedIgnoreCase&&a.currentFlags.ignoreCase&&dk.has(n))throw new Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?ht`\P`:ht`\p`}{${r?`${r}=`:""}${n}}`}if(e==="word")return t?ht`\W`:ht`\w`;throw new Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?"i":"")+(e.dotAll?"s":"")+(e.sticky?"y":"")},Group({atomic:e,body:t,flags:n,parent:r},a,l){const u=a.currentFlags;n&&(a.currentFlags=fd(u,n));const c=t.map(l).join("|"),d=!a.verbose&&t.length===1&&r.type!=="Quantifier"&&!e&&(!a.useFlagMods||!n)?c:`(?${g6(e,n,a.useFlagMods)}${c})`;return a.currentFlags=u,d},LookaroundAssertion({body:e,kind:t,negate:n},r,a){return`(?${`${t==="lookahead"?"":"<"}${n?"!":"="}`}${e.map(a).join("|")})`},Quantifier(e,t,n){return n(e.body)+x6(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw new Error("Unexpected non-recursive subroutine in transformed AST");const r=n.recursionLimit;return t===0?`(?R=${r})`:ht`\g<${t}&R=${r}>`}},d6=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),h6=new Set(["-","\\","]","^","["]),f6=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),pS=new Map([[9,ht`\t`],[10,ht`\n`],[11,ht`\v`],[12,ht`\f`],[13,ht`\r`],[8232,ht`\u2028`],[8233,ht`\u2029`],[65279,ht`\uFEFF`]]),m6=new RegExp("^\\p{Cased}$","u");function Wg(e){return m6.test(e)}function yk(e,t){const n=!!(t!=null&&t.firstOnly),r=e.min.value,a=e.max.value,l=[];if(r<65&&(a===65535||a>=131071)||r===65536&&a>=131071)return l;for(let u=r;u<=a;u++){const c=xn(u);if(!Wg(c))continue;const d=uk(c).filter(h=>{const p=h.codePointAt(0);return p<r||p>a});if(d.length&&(l.push(...d),n))break}return l}function Va(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(pS.has(e))return pS.get(e);if(e<32||e>126&&e<160||e>262143||t&&y6(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,"0")}`;const a=n?r?f6:h6:d6,l=xn(e);return(a.has(l)?"\\":"")+l}function p6(e){const t=e.map(a=>a.codePointAt(0)).sort((a,l)=>a-l),n=[];let r=null;for(let a=0;a<t.length;a++)t[a+1]===t[a]+1?r??(r=t[a]):r===null?n.push(t[a]):(n.push([r,t[a]]),r=null);return n}function g6(e,t,n){if(e)return">";let r="";if(t&&n){const{enable:a,disable:l}=t;r=(a!=null&&a.ignoreCase?"i":"")+(a!=null&&a.dotAll?"s":"")+(l?"-":"")+(l!=null&&l.ignoreCase?"i":"")+(l!=null&&l.dotAll?"s":"")}return`${r}:`}function x6({kind:e,max:t,min:n}){let r;return!n&&t===1?r="?":!n&&t===1/0?r="*":n===1&&t===1/0?r="+":n===t?r=`{${n}}`:r=`{${n},${t===1/0?"":t}}`,r+{greedy:"",lazy:"?",possessive:"+"}[e]}function gS({type:e}){return e==="CapturingGroup"||e==="Group"||e==="LookaroundAssertion"}function y6(e){return e>47&&e<58}function xS({type:e,value:t}){return e==="Character"&&t===45}var si,_s,Wi,ii,qi,Wl,Qp,hi,b6=(hi=class extends RegExp{constructor(n,r,a){var t=(...H9)=>(super(...H9),Ii(this,Wl),Ii(this,si,new Map),Ii(this,_s,null),Ii(this,Wi),Ii(this,ii,null),Ii(this,qi,null),_e(this,"rawOptions",{}),this);const l=!!(a!=null&&a.lazyCompile);if(n instanceof RegExp){if(a)throw new Error("Cannot provide options when copying a regexp");const u=n;t(u,r),Tr(this,Wi,u.source),u instanceof hi&&(Tr(this,si,Bn(u,si)),Tr(this,ii,Bn(u,ii)),Tr(this,qi,Bn(u,qi)),this.rawOptions=u.rawOptions)}else{const u={hiddenCaptures:[],strategy:null,transfers:[],...a};t(l?"":n,r),Tr(this,Wi,n),Tr(this,si,_6(u.hiddenCaptures,u.transfers)),Tr(this,qi,u.strategy),this.rawOptions=a??{}}l||Tr(this,_s,this)}get source(){return Bn(this,Wi)||"(?:)"}exec(n){if(!Bn(this,_s)){const{lazyCompile:l,...u}=this.rawOptions;Tr(this,_s,new hi(Bn(this,Wi),this.flags,u))}const r=this.global||this.sticky,a=this.lastIndex;if(Bn(this,qi)==="clip_search"&&r&&a){this.lastIndex=0;const l=cm(this,Wl,Qp).call(this,n.slice(a));return l&&(v6(l,a,n,this.hasIndices),this.lastIndex+=a),l}return cm(this,Wl,Qp).call(this,n)}},si=new WeakMap,_s=new WeakMap,Wi=new WeakMap,ii=new WeakMap,qi=new WeakMap,Wl=new WeakSet,Qp=function(n){Bn(this,_s).lastIndex=this.lastIndex;const r=Qv(hi.prototype,this,"exec").call(Bn(this,_s),n);if(this.lastIndex=Bn(this,_s).lastIndex,!r||!Bn(this,si).size)return r;const a=[...r];r.length=1;let l;this.hasIndices&&(l=[...r.indices],r.indices.length=1);const u=[0];for(let c=1;c<a.length;c++){const{hidden:d,transferTo:h}=Bn(this,si).get(c)??{};if(d?u.push(null):(u.push(r.length),r.push(a[c]),this.hasIndices&&r.indices.push(l[c])),h&&a[c]!==void 0){const p=u[h];if(!p)throw new Error(`Invalid capture transfer to "${p}"`);if(r[p]=a[c],this.hasIndices&&(r.indices[p]=l[c]),r.groups){Bn(this,ii)||Tr(this,ii,S6(this.source));const m=Bn(this,ii).get(h);m&&(r.groups[m]=a[c],this.hasIndices&&(r.indices.groups[m]=l[c]))}}}return r},hi);function v6(e,t,n,r){if(e.index+=t,e.input=n,r){const a=e.indices;for(let u=0;u<a.length;u++){const c=a[u];c&&(a[u]=[c[0]+t,c[1]+t])}const l=a.groups;l&&Object.keys(l).forEach(u=>{const c=l[u];c&&(l[u]=[c[0]+t,c[1]+t])})}}function _6(e,t){const n=new Map;for(const r of e)n.set(r,{hidden:!0});for(const[r,a]of t)for(const l of a)Fl(n,l,{}).transferTo=r;return n}function S6(e){const t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map;let r=0,a=0,l;for(;l=t.exec(e);){const{0:u,groups:{capture:c,name:d}}=l;u==="["?r++:r?u==="]"&&r--:c&&(a++,d&&n.set(a,d))}return n}function w6(e,t){const n=C6(e,t);return n.options?new b6(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function C6(e,t){const n=ck(t),r=tk(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:Gg}),a=QP(r,{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),l=l6(a,n),u=zP(l.pattern,{captureTransfers:l._captureTransfers,hiddenCaptures:l._hiddenCaptures,mode:"external"}),c=BP(u.pattern),d=PP(c.pattern,{captureTransfers:u.captureTransfers,hiddenCaptures:u.hiddenCaptures}),h={pattern:d.pattern,flags:`${n.hasIndices?"d":""}${n.global?"g":""}${l.flags}${l.options.disable.v?"u":"v"}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw new Error("Lazy compilation requires subclass")}else{const p=d.hiddenCaptures.sort((w,C)=>w-C),m=Array.from(d.captureTransfers),x=a._strategy,y=h.pattern.length>=n.lazyCompileLength;(p.length||m.length||x||y)&&(h.options={...p.length&&{hiddenCaptures:p},...m.length&&{transfers:m},...x&&{strategy:x},...y&&{lazyCompile:y}})}return h}function bk(e,t){return w6(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function k6(e={}){const t={target:"auto",cache:new Map,...e};return t.regexConstructor||(t.regexConstructor=n=>bk(n,{target:t.target})),{createScanner(n){return new HM(n,t)},createString(n){return{content:n}}}}Xw(Tg({bundledLanguages:()=>Md,bundledLanguagesAlias:()=>Lg,bundledLanguagesBase:()=>Ag,bundledLanguagesInfo:()=>Id,bundledThemes:()=>Rg,bundledThemesInfo:()=>Dg,codeToHast:()=>FC,codeToHtml:()=>UC,codeToTokens:()=>VC,codeToTokensBase:()=>GC,codeToTokensWithThemes:()=>WC,createHighlighter:()=>Vd,createJavaScriptRegexEngine:()=>k6,createOnigurumaEngine:()=>Zw,defaultJavaScriptRegexConstructor:()=>bk,getLastGrammarState:()=>KC,getSingletonHighlighter:()=>qC,loadWasm:()=>Ig}),zM);let np=null;const Ll=new Set,Lu=new Map,yS=["typescript","javascript","tsx","jsx","python","bash","json","css","html","sql","yaml","markdown","diff","rust","go","java","c","cpp","ruby","toml","scss","graphql","docker","powershell"],j6=["github-dark-default","vitesse-light","monokai","dracula","nord","everforest-light","rose-pine-dawn","synthwave-84","one-dark-pro","night-owl","catppuccin-mocha","rose-pine","kanagawa-wave","light-plus"],rp={dark:"github-dark-default",light:"vitesse-light",monokai:"monokai",dracula:"dracula",nord:"nord","rose-pine-dawn":"rose-pine-dawn","everforest-light":"everforest-light","synthwave-84":"synthwave-84","one-dark-pro":"one-dark-pro","night-owl":"night-owl","catppuccin-mocha":"catppuccin-mocha","rose-pine":"rose-pine","kanagawa-wave":"kanagawa-wave","light-plus":"light-plus"};function E6(){return{name:"line-numbers",line(e,t){e.properties["data-line"]=String(t+1)}}}async function vk(){return np||(np=Vd({themes:j6,langs:yS}).then(e=>(yS.forEach(t=>Ll.add(t)),e))),np}async function N6(e){if(Ll.has(e))return;if(Lu.has(e))return Lu.get(e);const t=(async()=>{const n=await vk(),r=Md[e];if(r){await n.loadLanguage(r),Ll.add(e);return}try{const a=await ee(()=>import(`shiki/langs/${e}.mjs`),[]);a.default&&(await n.loadLanguage(a.default),Ll.add(e))}catch(a){console.warn(`Failed to load language ${e}:`,a)}})();Lu.set(e,t),await t,Lu.delete(e)}const xl=new Map,T6=50;function A6(e,t,n){return`${e}|${t}|${n}`}async function _k(e,t,n="github-dark-default"){t!=="text"&&!Ll.has(t)&&await N6(t);const r=A6(e,t,n),a=xl.get(r);if(a)return a;const u=(await vk()).codeToHtml(e,{lang:t,theme:n,transformers:[E6()]});if(xl.size>=T6){const c=xl.keys().next().value;c&&xl.delete(c)}return xl.set(r,u),u}const L6={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",swift:"swift",kt:"kotlin",scala:"scala",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",md:"markdown",markdown:"markdown",toml:"toml",ini:"ini",conf:"ini",dockerfile:"docker",makefile:"makefile",cmake:"cmake",graphql:"graphql",gql:"graphql",vue:"vue",svelte:"svelte"};function Yd(e){var a;if(!e)return"text";const t=e.split("/").pop()??"",n=t.toLowerCase();if(n==="dockerfile")return"docker";if(n==="makefile")return"makefile";if(n==="cmakelists.txt")return"cmake";const r=(a=t.split(".").pop())==null?void 0:a.toLowerCase();return r?L6[r]??"text":"text"}function Sk(){const e=Bt(r=>r.currentPreset),t=Bt(r=>r.isCustom),n=Bt(r=>r.basePreset);return D6(e,t,n)}function D6(e,t,n){return t?n&&n!=="system"&&rp[n]?rp[n]??"github-dark-default":"github-dark-default":rp[e]??"github-dark-default"}function wk(e=2e3){const[t,n]=E.useState(!1),r=E.useCallback(async a=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(a);else{const l=document.createElement("textarea");l.value=a,l.style.position="fixed",l.style.left="-9999px",document.body.appendChild(l),l.select(),document.execCommand("copy"),document.body.removeChild(l)}n(!0),setTimeout(()=>n(!1),e)}catch(l){console.error("Failed to copy:",l)}},[e]);return{copied:t,copy:r}}const R6=E.memo(function({language:t,codeString:n,showSyntaxHighlighting:r}){const{copied:a,copy:l}=wk(),[u,c]=E.useState(null),d=Sk(),h=E.useRef(n);return E.useEffect(()=>{r&&(h.current=n,_k(n,t,d).then(p=>{h.current===n&&c(p)}))},[n,t,d,r]),i.jsxs("div",{className:"relative group my-1.5 rounded overflow-hidden",children:[i.jsxs("div",{className:"absolute bottom-0 right-0 flex items-center gap-2 px-2 py-1 text-xs text-text-muted/70 bg-bg-tertiary/60 rounded-tl rounded-tr z-10",children:[i.jsx("span",{children:t}),i.jsx("button",{type:"button",onClick:p=>{p.preventDefault(),p.stopPropagation(),l(n)},className:"opacity-0 group-hover:opacity-100 transition-opacity hover:text-text-primary p-0.5",title:"Copy code",children:a?i.jsx(Mr,{}):i.jsx(Rl,{})})]}),r&&u?i.jsx("div",{className:"min-w-0",dangerouslySetInnerHTML:{__html:u}}):i.jsx("div",{className:"overflow-x-auto",children:i.jsx("pre",{className:"my-0 px-4 py-3 overflow-x-auto font-mono text-sm whitespace-pre-wrap break-word",children:i.jsx("code",{className:`language-${t}`,children:n})})})]})});function O6(e,t){const n=e?"text-text-muted":"text-text-heading",r=e?"text-text-secondary":"text-text-bold";return{code({className:a,children:l,...u}){const c=/language-(\w+)/.exec(a||"");if(!c&&!String(l).includes(`
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(R6,{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 zn=E.memo(function({content:t,className:n="",muted:r=!1}){const{showSyntaxHighlighting:a}=Zi(),l=E.useMemo(()=>{let c=I6(t);return c=M6(c),c},[t]),u=E.useMemo(()=>O6(r,a),[r,a]);return i.jsx("div",{className:`markdown-content [&_li>p]:inline ${n}`,children:i.jsx(s5,{remarkPlugins:[xO],components:u,children:l})})});function I6(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 M6(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 Ck({isOpen:e,onClose:t}){const[n,r]=E.useState(null),[a,l]=E.useState(!1),{settings:u,getSetting:c,setSetting:d}=ta(),h=u[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]!=="false";E.useEffect(()=>{e&&c(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE)},[e,c]),E.useEffect(()=>{e&&(l(!0),ve("/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=E.useCallback(()=>{const m=h?"false":"true";d(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,m)},[h,d]);return i.jsx(jt,{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(Kr,{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(zn,{content:n??""})})})})}async function kk(e,t,n){t({loading:!0});try{const a=await(await ve(e)).json();t({defaults:a.defaults??[],userItems:a.userItems??[],...n?{projectItems:a.projectItems??[]}:{},loading:!1})}catch{t({loading:!1})}}const P6="#6b7280";function Vl(e,t){var n;return((n=e.find(r=>r.id===t))==null?void 0:n.color)??P6}const xt=In(e=>{const t=async()=>{await kk("/api/agents",e,!0)};return{defaults:[],userItems:[],projectItems:[],loading:!1,fetchAgents:t,fetchAgent:async n=>{try{const r=await ve(`/api/agents/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/agents/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createAgent:async(n,r)=>{const a=await fi("POST","/api/agents",{...n,destination:r});return a.success&&await t(),a},updateAgent:async(n,r)=>{const a=await fi("PUT",`/api/agents/${n}`,r);return a.success&&await t(),a},deleteAgent:async n=>{try{const r=await ve(`/api/agents/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n),projectItems:l.projectItems.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)=>Cd(`/api/agents/${n}/duplicate`,t,r)}});function B6({onClose:e}){const[,t]=Tn(),{settings:n,getSetting:r,setSetting:a}=ta(),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]=E.useState({openInEditor:l,dynamicPrompt:u,cacheWarming:c}),[p,m]=E.useState({patterns:[],maxRetriesPerTurn:10}),[x,y]=E.useState(""),[w,C]=E.useState(""),[_,S]=E.useState(!1),[v,b,j,N]=_p(),[T,D]=E.useState(!1),[L,O]=E.useState(!1),M=Xt(P=>P.version),W=Cs(P=>P.status),U=Cs(P=>P.latest),R=Cs(P=>P.check),H=M&&U?{current:M,latest:U}:null,[G,V]=E.useState(!1),Z=xt(P=>P.defaults),X=xt(P=>P.userItems),$=xt(P=>P.fetchAgents),I=[...Z,...X].filter(P=>!P.subagent);E.useEffect(()=>{h({openInEditor:l,dynamicPrompt:u,cacheWarming:c})},[l,u,c]),E.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]),E.useEffect(()=>{const P=n[Te.RETRY_PATTERNS];if(P)try{m(JSON.parse(P))}catch{}},[n]),E.useEffect(()=>{const P=n[Te.PROXY_URL];P!==void 0&&y(P)},[n]),E.useEffect(()=>{$().catch(()=>{})},[$]),E.useEffect(()=>{r(Te.DEFAULT_AGENT)},[r]),E.useEffect(()=>{const P=n[Te.DEFAULT_AGENT];P!==void 0&&(C(P),S(!0))},[n]);const B=E.useCallback(P=>{m(P),a(Te.RETRY_PATTERNS,JSON.stringify(P))},[a]),q=P=>{y(P),a(Te.PROXY_URL,P)};function z(){N(async()=>(await ve("/api/proxy/test",{method:"POST"})).json())}const ne=()=>{const P=!d.openInEditor;h(J=>({...J,openInEditor:P})),a(Te.DISPLAY_SHOW_OPEN_IN_EDITOR,String(P))},re=()=>{const P=!d.dynamicPrompt;h(J=>({...J,dynamicPrompt:P})),a(Te.LLM_DYNAMIC_SYSTEM_PROMPT,String(P))},Q=()=>{const P=!d.cacheWarming;h(J=>({...J,cacheWarming:P})),a(Te.CACHE_WARMING,String(P))};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:M?i.jsxs(i.Fragment,{children:["Current version: ",i.jsxs("span",{className:"font-mono",children:["v",M]})]}):"Check for a new OpenFox version."}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(rt,{variant:"secondary",onClick:()=>{V(!0),R()},disabled:W==="checking",children:W==="checking"?"Checking…":"Check for Updates"}),G&&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",U," →"]})]})]}),i.jsx(G1,{isOpen:T,onClose:()=>D(!1),versionInfo:H}),i.jsxs("div",{className:"flex items-center justify-between pt-2",children:[i.jsx("button",{onClick:()=>O(!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(Kr,{enabled:(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true",onClick:()=>{const J=(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true"?"false":"true";a(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,J)}})]})]}),i.jsx(Ck,{isOpen:L,onClose:()=>O(!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:P=>{const J=P.target.value;C(J),a(Te.DEFAULT_AGENT,J)},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)"}),I.map(P=>i.jsx("option",{value:P.id,children:P.name},P.id))]}),I.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(rt,{variant:"secondary",onClick:K,children:"Launch Onboarding"})]}),i.jsx("hr",{className:"border-border"}),i.jsx("div",{children:i.jsx(sp,{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:ne})}),i.jsx("hr",{className:"border-border"}),i.jsx(sp,{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:Q,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(ui,{type:"text",value:x,onChange:P=>q(P.target.value),placeholder:"http://proxy:8080",className:"flex-1"}),i.jsx(rt,{variant:"secondary",onClick:z,style:j?{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(qT,{value:p,onChange:B})]}),i.jsx("hr",{className:"border-border"}),i.jsx(sp,{title:"Dynamic System Prompt",description:"Rebuild the system prompt on every turn. Recommended value: off.",enabled:d.dynamicPrompt,onToggle:re,boldTitle:!0})]})}function sp({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(Kr,{enabled:n,onClick:r})})]})}function $6(e,t){return e===null&&t===null?!0:e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}function z6({label:e,binding:t,defaultBinding:n,isRecording:r,onStartRecording:a,onBindingRecorded:l,onClear:u,onReset:c,onCancelRecording:d}){const h=E.useRef(null),p=E.useRef(0),m=E.useRef("");return E.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:R_(_),modifiers:b});return}const S=Date.now(),v=R_(_);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?Xu(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(lg,{className:"w-3.5 h-3.5"})}),!$6(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(jd,{className:"w-3.5 h-3.5"})})]})})]})}function H6(){const{settings:e,loading:t,setSetting:n}=ta(),r=e[Te.KEYBINDINGS],a=t[Te.KEYBINDINGS]??!1,l=vp(r),[u,c]=E.useState(null),d=[{id:"terminalToggle",label:"Toggle Terminal",binding:l.terminalToggle,defaultBinding:Wr.terminalToggle},{id:"quickAction",label:"Quick Action",binding:l.quickAction,defaultBinding:Wr.quickAction},{id:"modelSelector",label:"Select Model",binding:l.modelSelector,defaultBinding:Wr.modelSelector},{id:"sessionSearch",label:"Search Sessions",binding:l.sessionSearch,defaultBinding:Wr.sessionSearch},{id:"criteriaSidebar",label:"Toggle Criteria Sidebar",binding:l.criteriaSidebar,defaultBinding:Wr.criteriaSidebar},...l.agentSwitching.map((y,w)=>({id:`agentSwitching.${w}`,label:`Switch to Agent ${w+1}`,binding:y,defaultBinding:Wr.agentSwitching[w]??null}))],h=y=>{c(y)},p=E.useCallback((y,w)=>{const C=vp(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=E.useCallback(y=>{u&&(c(null),p(u,y))},[u,p]),x=()=>{n(Te.KEYBINDINGS,JSON.stringify(Wr))};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(z6,{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 qg(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 Kg(e){switch(e){case"connected":return"●";case"error":return"✕";default:return"○"}}function md(e){return e>=1e3?`~${(e/1e3).toFixed(1)}K`:`~${e}`}function jk({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]=E.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:[md(e.estimatedTokens)," tokens"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Kr,{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(hn,{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:md(w.estimatedTokens)}),i.jsx(Kr,{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 bS(e){const t={};return e.split(`
251
+ Failed to load changelog.`)}).finally(()=>l(!1)))},[e]);const p=E.useCallback(()=>{const m=h?"false":"true";d(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,m)},[h,d]);return i.jsx(jt,{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(Kr,{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(zn,{content:n??""})})})})}async function kk(e,t,n){t({loading:!0});try{const a=await(await ve(e)).json();t({defaults:a.defaults??[],userItems:a.userItems??[],...n?{projectItems:a.projectItems??[]}:{},loading:!1})}catch{t({loading:!1})}}const P6="#6b7280";function Vl(e,t){var n;return((n=e.find(r=>r.id===t))==null?void 0:n.color)??P6}const xt=In(e=>{const t=async()=>{await kk("/api/agents",e,!0)};return{defaults:[],userItems:[],projectItems:[],loading:!1,fetchAgents:t,fetchAgent:async n=>{try{const r=await ve(`/api/agents/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/agents/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createAgent:async(n,r)=>{const a=await fi("POST","/api/agents",{...n,destination:r});return a.success&&await t(),a},updateAgent:async(n,r)=>{const a=await fi("PUT",`/api/agents/${n}`,r);return a.success&&await t(),a},deleteAgent:async n=>{try{const r=await ve(`/api/agents/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n),projectItems:l.projectItems.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)=>Cd(`/api/agents/${n}/duplicate`,t,r)}});function B6({onClose:e}){const[,t]=Tn(),{settings:n,getSetting:r,setSetting:a}=ta(),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]=E.useState({openInEditor:l,dynamicPrompt:u,cacheWarming:c}),[p,m]=E.useState({patterns:[],maxRetriesPerTurn:10}),[x,y]=E.useState(""),[w,C]=E.useState(""),[_,S]=E.useState(!1),[v,b,j,N]=_p(),[T,D]=E.useState(!1),[L,O]=E.useState(!1),M=Xt(P=>P.version),W=Cs(P=>P.status),U=Cs(P=>P.latest),R=Cs(P=>P.check),H=M&&U?{current:M,latest:U}:null,[G,V]=E.useState(!1),Z=xt(P=>P.defaults),X=xt(P=>P.userItems),$=xt(P=>P.fetchAgents),I=[...Z,...X].filter(P=>!P.subagent);E.useEffect(()=>{h({openInEditor:l,dynamicPrompt:u,cacheWarming:c})},[l,u,c]),E.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]),E.useEffect(()=>{const P=n[Te.RETRY_PATTERNS];if(P)try{m(JSON.parse(P))}catch{}},[n]),E.useEffect(()=>{const P=n[Te.PROXY_URL];P!==void 0&&y(P)},[n]),E.useEffect(()=>{$().catch(()=>{})},[$]),E.useEffect(()=>{r(Te.DEFAULT_AGENT)},[r]),E.useEffect(()=>{const P=n[Te.DEFAULT_AGENT];P!==void 0&&(C(P),S(!0))},[n]);const B=E.useCallback(P=>{m(P),a(Te.RETRY_PATTERNS,JSON.stringify(P))},[a]),q=P=>{y(P),a(Te.PROXY_URL,P)};function z(){N(async()=>(await ve("/api/proxy/test",{method:"POST"})).json())}const ne=()=>{const P=!d.openInEditor;h(J=>({...J,openInEditor:P})),a(Te.DISPLAY_SHOW_OPEN_IN_EDITOR,String(P))},re=()=>{const P=!d.dynamicPrompt;h(J=>({...J,dynamicPrompt:P})),a(Te.LLM_DYNAMIC_SYSTEM_PROMPT,String(P))},Q=()=>{const P=!d.cacheWarming;h(J=>({...J,cacheWarming:P})),a(Te.CACHE_WARMING,String(P))};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:M?i.jsxs(i.Fragment,{children:["Current version: ",i.jsxs("span",{className:"font-mono",children:["v",M]})]}):"Check for a new OpenFox version."}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(rt,{variant:"secondary",onClick:()=>{V(!0),R()},disabled:W==="checking",children:W==="checking"?"Checking…":"Check for Updates"}),G&&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",U," →"]})]})]}),i.jsx(G1,{isOpen:T,onClose:()=>D(!1),versionInfo:H}),i.jsxs("div",{className:"flex items-center justify-between pt-2",children:[i.jsx("button",{onClick:()=>O(!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(Kr,{enabled:(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true",onClick:()=>{const J=(n[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE]??"true")==="true"?"false":"true";a(Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE,J)}})]})]}),i.jsx(Ck,{isOpen:L,onClose:()=>O(!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:P=>{const J=P.target.value;C(J),a(Te.DEFAULT_AGENT,J)},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)"}),I.map(P=>i.jsx("option",{value:P.id,children:P.name},P.id))]}),I.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(rt,{variant:"secondary",onClick:K,children:"Launch Onboarding"})]}),i.jsx("hr",{className:"border-border"}),i.jsx("div",{children:i.jsx(sp,{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:ne})}),i.jsx("hr",{className:"border-border"}),i.jsx(sp,{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:Q,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:"Network"}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"HTTP Proxy"}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx(ui,{type:"text",value:x,onChange:P=>q(P.target.value),placeholder:"http://proxy:8080",className:"flex-1"}),i.jsx(rt,{variant:"secondary",onClick:z,style:j?{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("p",{className:"text-xs text-text-muted mt-1",children:"Proxy server all OpenFox network requests (AI, model fetching, web search, terminal). Leave empty for direct connection."})]})]}),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(qT,{value:p,onChange:B})]}),i.jsx("hr",{className:"border-border"}),i.jsx(sp,{title:"Dynamic System Prompt",description:"Rebuild the system prompt on every turn. Recommended value: off.",enabled:d.dynamicPrompt,onToggle:re,boldTitle:!0})]})}function sp({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(Kr,{enabled:n,onClick:r})})]})}function $6(e,t){return e===null&&t===null?!0:e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}function z6({label:e,binding:t,defaultBinding:n,isRecording:r,onStartRecording:a,onBindingRecorded:l,onClear:u,onReset:c,onCancelRecording:d}){const h=E.useRef(null),p=E.useRef(0),m=E.useRef("");return E.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:R_(_),modifiers:b});return}const S=Date.now(),v=R_(_);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?Xu(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(lg,{className:"w-3.5 h-3.5"})}),!$6(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(jd,{className:"w-3.5 h-3.5"})})]})})]})}function H6(){const{settings:e,loading:t,setSetting:n}=ta(),r=e[Te.KEYBINDINGS],a=t[Te.KEYBINDINGS]??!1,l=vp(r),[u,c]=E.useState(null),d=[{id:"terminalToggle",label:"Toggle Terminal",binding:l.terminalToggle,defaultBinding:Wr.terminalToggle},{id:"quickAction",label:"Quick Action",binding:l.quickAction,defaultBinding:Wr.quickAction},{id:"modelSelector",label:"Select Model",binding:l.modelSelector,defaultBinding:Wr.modelSelector},{id:"sessionSearch",label:"Search Sessions",binding:l.sessionSearch,defaultBinding:Wr.sessionSearch},{id:"criteriaSidebar",label:"Toggle Criteria Sidebar",binding:l.criteriaSidebar,defaultBinding:Wr.criteriaSidebar},...l.agentSwitching.map((y,w)=>({id:`agentSwitching.${w}`,label:`Switch to Agent ${w+1}`,binding:y,defaultBinding:Wr.agentSwitching[w]??null}))],h=y=>{c(y)},p=E.useCallback((y,w)=>{const C=vp(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=E.useCallback(y=>{u&&(c(null),p(u,y))},[u,p]),x=()=>{n(Te.KEYBINDINGS,JSON.stringify(Wr))};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(z6,{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 qg(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 Kg(e){switch(e){case"connected":return"●";case"error":return"✕";default:return"○"}}function md(e){return e>=1e3?`~${(e/1e3).toFixed(1)}K`:`~${e}`}function jk({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]=E.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:[md(e.estimatedTokens)," tokens"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Kr,{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(hn,{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:md(w.estimatedTokens)}),i.jsx(Kr,{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 bS(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 vS({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(Cr,{label:"Command",value:e.command,onChange:n=>t({...e,command:n}),placeholder:"e.g. npx"}),i.jsx(Cr,{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(Cr,{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(Cr,{label:"Timeout (seconds)",value:e.timeout,onChange:n=>t({...e,timeout:n}),placeholder:"optional, e.g. 30"})]})}function ip(e,t,n,r=250){const a=E.useRef(!0);E.useEffect(()=>{if(a.current){a.current=!1;return}const l=setTimeout(()=>{n(t,e)},r);return()=>clearTimeout(l)},[e,t,r,n])}function _S({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(rt,{variant:"secondary",onClick:r,disabled:e,children:"Cancel"}),i.jsx(rt,{variant:"primary",onClick:a,disabled:e,children:e?n:t})]})}function U6(){const{settings:e,getSetting:t,setSetting:n}=ta(),[r,a]=E.useState(""),[l,u]=E.useState(""),[c,d]=E.useState(""),[h,p]=E.useState("");ip(l,Te.SEARCH_TAVILY_API_KEY,n),ip(c,Te.SEARCH_SEARXNG_URL,n),ip(h,Te.SEARCH_SEARXNG_API_KEY,n);const[m,x,y,w]=_p(),[C,_,S,v]=_p();E.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]),E.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(we){a(we),n(Te.SEARCH_ENGINE,we)}function j(){w(async()=>(await ve("/api/search/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({engine:"tavily",tavilyApiKey:l||void 0})})).json())}function N(){v(async()=>(await ve("/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]=E.useState("checking");E.useEffect(()=>{ve("/api/tools/rtk-check").then(we=>we.json()).then(we=>D(we.available?"available":"unavailable")).catch(()=>D("unavailable"))},[]);const[L,O]=E.useState([]);E.useEffect(()=>{t(Te.TOOLS_SHELL),ve("/api/tools/shells").then(we=>we.json()).then(we=>O(we.shells??[])).catch(()=>O([]))},[t]);const M=e[Te.TOOLS_SHELL]||"cmd",[W,U]=E.useState([]),[R,H]=E.useState(!0),[G,V]=E.useState(!1),[Z,X]=E.useState(null),[$,I]=E.useState(new Set),[B,q]=E.useState({name:"",transport:"stdio",command:"",args:"",env:"",url:"",headers:"",timeout:""}),[z,ne]=E.useState(""),[re,Q]=E.useState(""),[K,P]=E.useState(!1),{requestDelete:J,clearConfirm:ie,isConfirming:he}=Yl(),ce=E.useCallback(async()=>{try{const qe=((await(await ve("/api/mcp/servers")).json()).servers??[]).sort((te,ae)=>te.name.localeCompare(ae.name));U(qe)}catch{}H(!1)},[]);E.useEffect(()=>{ce()},[ce]),E.useEffect(()=>{const we=()=>ce();return window.addEventListener("mcp-servers-changed",we),()=>window.removeEventListener("mcp-servers-changed",we)},[ce]);const De=we=>{I(Ie=>{const qe=new Set(Ie);return qe.has(we)?(qe.delete(we),qe):(qe.add(we),qe)})};function Re(){if(B.transport==="stdio"&&!B.command)return"Command is required for stdio transport";if(B.transport==="http"&&!B.url)return"URL is required for HTTP transport";if(B.timeout){const we=parseFloat(B.timeout);if(isNaN(we)||we<=0)return"Timeout must be a positive number"}return null}function ze(we){const Ie=we?{name:B.name,transport:B.transport}:{transport:B.transport};if(B.transport==="stdio"?(Ie.command=B.command,Ie.args=B.args?B.args.split(" ").filter(Boolean):[],Ie.env=bS(B.env)):(Ie.url=B.url,Ie.headers=bS(B.headers)),B.timeout){const qe=parseFloat(B.timeout);!isNaN(qe)&&qe>0&&(Ie.timeout=qe)}return Ie}const Fe={name:"",transport:"stdio",command:"",args:"",env:"",url:"",headers:"",timeout:""},Ee=async()=>{if(ne(""),!B.name){ne("Name is required");return}const we=Re();if(we){ne(we);return}P(!0);try{const Ie=ze(!0),qe=await ve("/api/mcp/servers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ie)});if(!qe.ok){const te=await qe.json();throw new Error(te.error??"Failed to add server")}V(!1),q(Fe),await ce()}catch(Ie){ne(Ie instanceof Error?Ie.message:String(Ie))}finally{P(!1)}},st=we=>{var Ie;q({name:we.name,transport:we.config.transport,command:we.config.command??"",args:((Ie=we.config.args)==null?void 0:Ie.join(" "))??"",env:we.config.env?Object.entries(we.config.env).map(([qe,te])=>`${qe}=${te}`).join(`
253
253
  `):"",url:we.config.url??"",headers:we.config.headers?Object.entries(we.config.headers).map(([qe,te])=>`${qe}=${te}`).join(`
254
- `):"",timeout:we.config.timeout!==void 0?String(we.config.timeout):""}),ne(""),X(we.name)},ot=async()=>{ne("");const we=Re();if(we){ne(we);return}P(!0);try{const Ie=ze(!1),qe=await ve(`/api/mcp/servers/${encodeURIComponent(Z)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ie)});if(!qe.ok){const te=await qe.json();throw new Error(te.error??"Failed to update server")}X(null),q(Fe),await ce()}catch(Ie){ne(Ie instanceof Error?Ie.message:String(Ie))}finally{P(!1)}},je=async we=>{try{const Ie=await ve(`/api/mcp/servers/${encodeURIComponent(we)}`,{method:"DELETE"});if(!Ie.ok){const qe=await Ie.json().catch(()=>({}));throw new Error(qe.error??"Failed to remove server")}ie(),Q(""),await ce()}catch(Ie){Q(Ie instanceof Error?Ie.message:String(Ie))}},Me=async(we,Ie,qe)=>{try{const te=await ve(`/api/mcp/servers/${encodeURIComponent(we)}/tools/${encodeURIComponent(Ie)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:qe})});if(!te.ok){const ae=await te.json().catch(()=>({}));throw new Error(ae.error??"Failed to toggle tool")}Q(""),await ce()}catch(te){Q(te instanceof Error?te.message:String(te))}},lt=async(we,Ie)=>{try{const qe=await ve(`/api/mcp/servers/${encodeURIComponent(we)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabled:Ie})});if(!qe.ok){const te=await qe.json().catch(()=>({}));throw new Error(te.error??"Failed to toggle server")}Q(""),await ce()}catch(qe){Q(qe instanceof Error?qe.message:String(qe))}};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(we=>i.jsx("button",{onClick:()=>b(we),className:`px-3 py-1.5 rounded text-sm border transition-colors ${r===we?"bg-accent-primary/10 border-accent-primary text-accent-primary":"border-border text-text-muted hover:text-text-primary"}`,children:we||"Off"},we))})]}),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(ui,{type:"password",value:l,onChange:we=>u(we.target.value),placeholder:"tvly-...",className:"flex-1"}),i.jsx(rt,{variant:"secondary",onClick:j,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(ui,{type:"url",value:c,onChange:we=>d(we.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(ui,{type:"password",value:h,onChange:we=>p(we.target.value),placeholder:"Optional API key",className:"w-full"})]}),i.jsx(rt,{variant:"secondary",onClick:N,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(we=>i.jsxs("button",{onClick:()=>n(Te.TOOLS_SHELL,we.id),disabled:!we.available,title:we.available?void 0:"Not found on this machine",className:`px-3 py-1.5 rounded text-sm border transition-colors ${M===we.id?"bg-accent-primary/10 border-accent-primary text-accent-primary":we.available?"border-border text-text-muted hover:text-text-primary":"border-border text-text-muted opacity-50 cursor-not-allowed"}`,children:[we.label,!we.available&&" (not found)"]},we.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(Kr,{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(Kr,{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(rt,{variant:"primary",size:"sm",onClick:()=>V(!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(Kr,{enabled:e[Te.FEATURES_PER_SESSION_MCP]==="true",onClick:()=>n(Te.FEATURES_PER_SESSION_MCP,e[Te.FEATURES_PER_SESSION_MCP]==="true"?"false":"true")})]}),re&&i.jsx(eo,{message:re}),i.jsx(ug,{loading:R,hasItems:W.length>0,loadingLabel:"Loading MCP servers...",emptyLabel:"No MCP servers configured.",children:W.map(we=>{const Ie=$.has(we.name)?he(we.name,"delete")?i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:te=>{te.stopPropagation(),je(we.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:te=>{te.stopPropagation(),ie()},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:te=>{te.stopPropagation(),st(we)},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:te=>{te.stopPropagation(),J(we.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,qe=we.status==="error"&&we.error?i.jsx("span",{className:"text-xs text-accent-error truncate max-w-[200px]",title:we.error,children:we.error}):null;return i.jsx(jk,{server:we,expanded:$.has(we.name),onToggleExpand:De,serverToggleEnabled:!we.config.disabled,onServerToggle:()=>lt(we.name,!we.config.disabled),tools:we.tools,onToolToggle:te=>{var ae;return Me(we.name,te,!((ae=we.tools.find(se=>se.name===te))!=null&&ae.enabled))},statusDot:Kg(we.status),statusColor:qg(we.status),actions:i.jsxs(i.Fragment,{children:[qe,Ie]})},we.name)})}),G&&i.jsx(jt,{isOpen:G,onClose:()=>{V(!1),ne("")},title:"Add MCP Server",size:"sm",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(Cr,{label:"Name",value:B.name,onChange:we=>q({...B,name:we}),placeholder:"e.g. filesystem"}),i.jsx(vS,{formData:B,onChange:q}),z&&i.jsx(eo,{message:z}),i.jsx(_S,{saving:K,saveLabel:"Add",savingLabel:"Adding...",onCancel:()=>{V(!1),ne(""),P(!1),q(Fe)},onSave:Ee})]})}),Z!==null&&i.jsx(jt,{isOpen:!0,onClose:()=>{X(null),ne("")},title:`Edit MCP Server: ${Z}`,size:"sm",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(vS,{formData:B,onChange:q}),z&&i.jsx(eo,{message:z}),i.jsx(_S,{saving:K,saveLabel:"Save",savingLabel:"Saving...",onCancel:()=>{X(null),ne(""),P(!1),q(Fe)},onSave:ot})]})})]})]})}const Ek="openfox_user_plugins";function F6(e){const t=e.match(/github\.com\/([^/]+)\/([^/]+?)(?:\/|$)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,"")}:null}async function ap(e){const t=F6(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 Du(){try{return JSON.parse(localStorage.getItem(Ek)??"[]")}catch{return[]}}function SS(e){localStorage.setItem(Ek,JSON.stringify(e))}function V6({onAdd:e}){const[t,n]=E.useState(""),[r,a]=E.useState(""),[l,u]=E.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(rt,{type:"submit",variant:"primary",size:"sm",children:l?"Added":"Add"})]})}function G6({plugin:e,initiallyInstalled:t,installedVersion:n,onRemove:r,onOpenFolder:a}){const[l,u]=E.useState(t?"installed":"idle"),[c,d]=E.useState(!1),[h,p]=E.useState(""),[m,x]=E.useState(n),[y,w]=E.useState(!1),[C,_]=E.useState(!1);E.useEffect(()=>{x(n)},[n]);const S=E.useCallback(async()=>{const M=await ve("/api/plugins/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({githubUrl:e.githubUrl})}),W=await M.json();if(M.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(M){u("error"),p(M instanceof Error?M.message:"Connection error")}},b=()=>{w(!0)},j=async()=>{_(!0);try{(await ve(`/api/plugins/${e.name}`,{method:"DELETE"})).ok&&(u("idle"),r(e.name))}catch{}_(!1),w(!1)},N=async()=>{d(!0),p("");try{await S()}catch(M){p(M instanceof Error?M.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",O=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(rt,{variant:l==="installed"?"secondary":"primary",size:"sm",onClick:v,disabled:O,children:L}),D&&i.jsx(rt,{variant:"primary",size:"sm",onClick:N,children:"Update"}),l==="installed"&&i.jsx(rt,{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(Ml,{isOpen:y,onClose:()=>w(!1),onConfirm:j,title:`Remove "${e.displayName}"?`,message:`Remove the "${e.displayName}" plugin from your installation.`,confirmLabel:"Remove",confirmVariant:"danger",disabled:C})]})}function W6(){const[e,t]=E.useState([]),[n,r]=E.useState([]),[a,l]=E.useState({}),[u,c]=E.useState(!0),[d,h]=E.useState(""),[p,m]=E.useState("");E.useEffect(()=>{let S=!1;Promise.all([ve("/api/plugins/registry").then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}`);return b.json()}),ve("/api/plugins/installed").then(b=>b.ok?b.json():{installed:[]})]).then(([b,j])=>{if(S)return;const N={},T=j.installed;for(const W of T)N[W.name]=W.version;l(N);const D=b.plugins.map(W=>({...W,latestVersion:null,versionLoading:!0}));t(D),D.forEach(W=>{ap(W.githubUrl).then(U=>{S||t(R=>R.map(H=>H.name===W.name?{...H,latestVersion:U,versionLoading:!1}:H))})});const L=new Set(D.map(W=>W.name)),O=Du(),M=[];for(const W of T)!L.has(W.name)&&!O.some(U=>U.name===W.name)&&M.push({name:W.name,displayName:W.name,description:"Found on disk",githubUrl:"",latestVersion:null,versionLoading:!1});M.length>0&&r(W=>[...W,...M])}).catch(b=>{S||h(b instanceof Error?b.message:"Failed to load plugins")}).finally(()=>{S||c(!1)});const v=Du();return v.length>0&&(r(v.map(b=>({...b,latestVersion:null,versionLoading:!0}))),v.forEach(b=>{ap(b.githubUrl).then(j=>{S||r(N=>N.map(T=>T.name===b.name?{...T,latestVersion:j,versionLoading:!1}:T))})})),()=>{S=!0}},[]);const x=async S=>{try{S?await ve(`/api/plugins/${S}/open-folder`):await ve("/api/plugins/open-folder")}catch{}},y=E.useCallback(S=>{l(j=>{const N={...j};return delete N[S],N});const v=Du(),b=v.filter(j=>j.name!==S);b.length!==v.length&&SS(b),r(j=>j.filter(N=>N.name!==S))},[]),w=E.useCallback(S=>{if(new Set(e.map(j=>j.name)).has(S.name)){m(`"${S.displayName}" is already listed in the registry and won't be added again.`);return}const b=Du();SS([...b,S]),r(j=>[...j,{...S,latestVersion:null,versionLoading:!0}]),ap(S.githubUrl).then(j=>{r(N=>N.map(T=>T.name===S.name?{...T,latestVersion:j,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(V6,{onAdd:w})]}),_.length===0&&!d&&i.jsx("div",{className:"text-sm text-text-muted",children:"No plugins found."}),_.map(S=>i.jsx(G6,{plugin:S,initiallyInstalled:S.name in a,installedVersion:a[S.name]??null,onRemove:y,onOpenFolder:x},S.name))]})}function q6({isOpen:e,onClose:t}){const[n,r]=E.useState("instructions"),a=Cs(u=>u.status==="available"),l=()=>{try{Bt.send("context.checkDynamic",{})}catch{}t()};return i.jsx(jt,{isOpen:e,onClose:l,title:"Settings",size:"xl",minHeight:"500px",scrollable:!1,children:i.jsxs("div",{"data-global-settings":!0,className:"flex flex-col h-full min-h-0 -m-4",children:[i.jsxs("div",{className:"flex border-b border-border mb-4 overflow-x-auto scrollbar-hide flex-shrink-0 px-4 pt-4",children:[i.jsx(ti,{label:"Instructions",active:n==="instructions",onClick:()=>r("instructions")}),i.jsx(ti,{label:"Tools",active:n==="tools",onClick:()=>r("tools")}),i.jsx(ti,{label:"Skills",active:n==="skills",onClick:()=>r("skills")}),i.jsx(ti,{label:"Plugins",active:n==="plugins",onClick:()=>r("plugins")}),i.jsx(ti,{label:"Notifications",active:n==="notifications",onClick:()=>r("notifications")}),i.jsx(ti,{label:"Display",active:n==="display",onClick:()=>r("display")}),i.jsx(ti,{label:"Keybindings",active:n==="keybindings",onClick:()=>r("keybindings")}),i.jsx(ti,{label:"Advanced",active:n==="advanced",onClick:()=>r("advanced"),showDot:a})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0 px-4 pb-4",children:[n==="instructions"&&i.jsx($T,{isOpen:e}),n==="skills"&&i.jsx(BT,{isOpen:e}),n==="plugins"&&i.jsx(W6,{}),n==="notifications"&&i.jsx(ET,{}),n==="display"&&i.jsx(VT,{}),n==="keybindings"&&i.jsx(H6,{}),n==="tools"&&i.jsx(U6,{}),n==="advanced"&&i.jsx(B6,{onClose:t})]})]})})}function ti({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 op={exports:{}},wS;function K6(){return wS||(wS=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,j,N){var T,D=arguments.length,L=D<3?b:N===null?N=Object.getOwnPropertyDescriptor(b,j):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(v,b,j,N);else for(var O=v.length-1;O>=0;O--)(T=v[O])&&(L=(D<3?T(L):D>3?T(b,j,L):T(b,j))||L);return D>3&&L&&Object.defineProperty(b,j,L),L},p=this&&this.__param||function(v,b){return function(j,N){b(j,N,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,j,N){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=N,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(`
254
+ `):"",timeout:we.config.timeout!==void 0?String(we.config.timeout):""}),ne(""),X(we.name)},ot=async()=>{ne("");const we=Re();if(we){ne(we);return}P(!0);try{const Ie=ze(!1),qe=await ve(`/api/mcp/servers/${encodeURIComponent(Z)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ie)});if(!qe.ok){const te=await qe.json();throw new Error(te.error??"Failed to update server")}X(null),q(Fe),await ce()}catch(Ie){ne(Ie instanceof Error?Ie.message:String(Ie))}finally{P(!1)}},je=async we=>{try{const Ie=await ve(`/api/mcp/servers/${encodeURIComponent(we)}`,{method:"DELETE"});if(!Ie.ok){const qe=await Ie.json().catch(()=>({}));throw new Error(qe.error??"Failed to remove server")}ie(),Q(""),await ce()}catch(Ie){Q(Ie instanceof Error?Ie.message:String(Ie))}},Me=async(we,Ie,qe)=>{try{const te=await ve(`/api/mcp/servers/${encodeURIComponent(we)}/tools/${encodeURIComponent(Ie)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:qe})});if(!te.ok){const ae=await te.json().catch(()=>({}));throw new Error(ae.error??"Failed to toggle tool")}Q(""),await ce()}catch(te){Q(te instanceof Error?te.message:String(te))}},lt=async(we,Ie)=>{try{const qe=await ve(`/api/mcp/servers/${encodeURIComponent(we)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabled:Ie})});if(!qe.ok){const te=await qe.json().catch(()=>({}));throw new Error(te.error??"Failed to toggle server")}Q(""),await ce()}catch(qe){Q(qe instanceof Error?qe.message:String(qe))}};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(we=>i.jsx("button",{onClick:()=>b(we),className:`px-3 py-1.5 rounded text-sm border transition-colors ${r===we?"bg-accent-primary/10 border-accent-primary text-accent-primary":"border-border text-text-muted hover:text-text-primary"}`,children:we||"Off"},we))})]}),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(ui,{type:"password",value:l,onChange:we=>u(we.target.value),placeholder:"tvly-...",className:"flex-1"}),i.jsx(rt,{variant:"secondary",onClick:j,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(ui,{type:"url",value:c,onChange:we=>d(we.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(ui,{type:"password",value:h,onChange:we=>p(we.target.value),placeholder:"Optional API key",className:"w-full"})]}),i.jsx(rt,{variant:"secondary",onClick:N,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(we=>i.jsxs("button",{onClick:()=>n(Te.TOOLS_SHELL,we.id),disabled:!we.available,title:we.available?void 0:"Not found on this machine",className:`px-3 py-1.5 rounded text-sm border transition-colors ${M===we.id?"bg-accent-primary/10 border-accent-primary text-accent-primary":we.available?"border-border text-text-muted hover:text-text-primary":"border-border text-text-muted opacity-50 cursor-not-allowed"}`,children:[we.label,!we.available&&" (not found)"]},we.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(Kr,{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(Kr,{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(rt,{variant:"primary",size:"sm",onClick:()=>V(!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(Kr,{enabled:e[Te.FEATURES_PER_SESSION_MCP]==="true",onClick:()=>n(Te.FEATURES_PER_SESSION_MCP,e[Te.FEATURES_PER_SESSION_MCP]==="true"?"false":"true")})]}),re&&i.jsx(eo,{message:re}),i.jsx(ug,{loading:R,hasItems:W.length>0,loadingLabel:"Loading MCP servers...",emptyLabel:"No MCP servers configured.",children:W.map(we=>{const Ie=$.has(we.name)?he(we.name,"delete")?i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:te=>{te.stopPropagation(),je(we.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:te=>{te.stopPropagation(),ie()},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:te=>{te.stopPropagation(),st(we)},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:te=>{te.stopPropagation(),J(we.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,qe=we.status==="error"&&we.error?i.jsx("span",{className:"text-xs text-accent-error truncate max-w-[200px]",title:we.error,children:we.error}):null;return i.jsx(jk,{server:we,expanded:$.has(we.name),onToggleExpand:De,serverToggleEnabled:!we.config.disabled,onServerToggle:()=>lt(we.name,!we.config.disabled),tools:we.tools,onToolToggle:te=>{var ae;return Me(we.name,te,!((ae=we.tools.find(se=>se.name===te))!=null&&ae.enabled))},statusDot:Kg(we.status),statusColor:qg(we.status),actions:i.jsxs(i.Fragment,{children:[qe,Ie]})},we.name)})}),G&&i.jsx(jt,{isOpen:G,onClose:()=>{V(!1),ne("")},title:"Add MCP Server",size:"sm",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(Cr,{label:"Name",value:B.name,onChange:we=>q({...B,name:we}),placeholder:"e.g. filesystem"}),i.jsx(vS,{formData:B,onChange:q}),z&&i.jsx(eo,{message:z}),i.jsx(_S,{saving:K,saveLabel:"Add",savingLabel:"Adding...",onCancel:()=>{V(!1),ne(""),P(!1),q(Fe)},onSave:Ee})]})}),Z!==null&&i.jsx(jt,{isOpen:!0,onClose:()=>{X(null),ne("")},title:`Edit MCP Server: ${Z}`,size:"sm",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(vS,{formData:B,onChange:q}),z&&i.jsx(eo,{message:z}),i.jsx(_S,{saving:K,saveLabel:"Save",savingLabel:"Saving...",onCancel:()=>{X(null),ne(""),P(!1),q(Fe)},onSave:ot})]})})]})]})}const Ek="openfox_user_plugins";function F6(e){const t=e.match(/github\.com\/([^/]+)\/([^/]+?)(?:\/|$)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,"")}:null}async function ap(e){const t=F6(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 Du(){try{return JSON.parse(localStorage.getItem(Ek)??"[]")}catch{return[]}}function SS(e){localStorage.setItem(Ek,JSON.stringify(e))}function V6({onAdd:e}){const[t,n]=E.useState(""),[r,a]=E.useState(""),[l,u]=E.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(rt,{type:"submit",variant:"primary",size:"sm",children:l?"Added":"Add"})]})}function G6({plugin:e,initiallyInstalled:t,installedVersion:n,onRemove:r,onOpenFolder:a}){const[l,u]=E.useState(t?"installed":"idle"),[c,d]=E.useState(!1),[h,p]=E.useState(""),[m,x]=E.useState(n),[y,w]=E.useState(!1),[C,_]=E.useState(!1);E.useEffect(()=>{x(n)},[n]);const S=E.useCallback(async()=>{const M=await ve("/api/plugins/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({githubUrl:e.githubUrl})}),W=await M.json();if(M.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(M){u("error"),p(M instanceof Error?M.message:"Connection error")}},b=()=>{w(!0)},j=async()=>{_(!0);try{(await ve(`/api/plugins/${e.name}`,{method:"DELETE"})).ok&&(u("idle"),r(e.name))}catch{}_(!1),w(!1)},N=async()=>{d(!0),p("");try{await S()}catch(M){p(M instanceof Error?M.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",O=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(rt,{variant:l==="installed"?"secondary":"primary",size:"sm",onClick:v,disabled:O,children:L}),D&&i.jsx(rt,{variant:"primary",size:"sm",onClick:N,children:"Update"}),l==="installed"&&i.jsx(rt,{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(Ml,{isOpen:y,onClose:()=>w(!1),onConfirm:j,title:`Remove "${e.displayName}"?`,message:`Remove the "${e.displayName}" plugin from your installation.`,confirmLabel:"Remove",confirmVariant:"danger",disabled:C})]})}function W6(){const[e,t]=E.useState([]),[n,r]=E.useState([]),[a,l]=E.useState({}),[u,c]=E.useState(!0),[d,h]=E.useState(""),[p,m]=E.useState("");E.useEffect(()=>{let S=!1;Promise.all([ve("/api/plugins/registry").then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}`);return b.json()}),ve("/api/plugins/installed").then(b=>b.ok?b.json():{installed:[]})]).then(([b,j])=>{if(S)return;const N={},T=j.installed;for(const W of T)N[W.name]=W.version;l(N);const D=b.plugins.map(W=>({...W,latestVersion:null,versionLoading:!0}));t(D),D.forEach(W=>{ap(W.githubUrl).then(U=>{S||t(R=>R.map(H=>H.name===W.name?{...H,latestVersion:U,versionLoading:!1}:H))})});const L=new Set(D.map(W=>W.name)),O=Du(),M=[];for(const W of T)!L.has(W.name)&&!O.some(U=>U.name===W.name)&&M.push({name:W.name,displayName:W.name,description:"Found on disk",githubUrl:"",latestVersion:null,versionLoading:!1});M.length>0&&r(W=>[...W,...M])}).catch(b=>{S||h(b instanceof Error?b.message:"Failed to load plugins")}).finally(()=>{S||c(!1)});const v=Du();return v.length>0&&(r(v.map(b=>({...b,latestVersion:null,versionLoading:!0}))),v.forEach(b=>{ap(b.githubUrl).then(j=>{S||r(N=>N.map(T=>T.name===b.name?{...T,latestVersion:j,versionLoading:!1}:T))})})),()=>{S=!0}},[]);const x=async S=>{try{S?await ve(`/api/plugins/${S}/open-folder`):await ve("/api/plugins/open-folder")}catch{}},y=E.useCallback(S=>{l(j=>{const N={...j};return delete N[S],N});const v=Du(),b=v.filter(j=>j.name!==S);b.length!==v.length&&SS(b),r(j=>j.filter(N=>N.name!==S))},[]),w=E.useCallback(S=>{if(new Set(e.map(j=>j.name)).has(S.name)){m(`"${S.displayName}" is already listed in the registry and won't be added again.`);return}const b=Du();SS([...b,S]),r(j=>[...j,{...S,latestVersion:null,versionLoading:!0}]),ap(S.githubUrl).then(j=>{r(N=>N.map(T=>T.name===S.name?{...T,latestVersion:j,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(V6,{onAdd:w})]}),_.length===0&&!d&&i.jsx("div",{className:"text-sm text-text-muted",children:"No plugins found."}),_.map(S=>i.jsx(G6,{plugin:S,initiallyInstalled:S.name in a,installedVersion:a[S.name]??null,onRemove:y,onOpenFolder:x},S.name))]})}function q6({isOpen:e,onClose:t}){const[n,r]=E.useState("instructions"),a=Cs(u=>u.status==="available"),l=()=>{try{Dt.send("context.checkDynamic",{})}catch{}t()};return i.jsx(jt,{isOpen:e,onClose:l,title:"Settings",size:"xl",minHeight:"500px",scrollable:!1,children:i.jsxs("div",{"data-global-settings":!0,className:"flex flex-col h-full min-h-0 -m-4",children:[i.jsxs("div",{className:"flex border-b border-border mb-4 overflow-x-auto scrollbar-hide flex-shrink-0 px-4 pt-4",children:[i.jsx(ti,{label:"Instructions",active:n==="instructions",onClick:()=>r("instructions")}),i.jsx(ti,{label:"Tools",active:n==="tools",onClick:()=>r("tools")}),i.jsx(ti,{label:"Skills",active:n==="skills",onClick:()=>r("skills")}),i.jsx(ti,{label:"Plugins",active:n==="plugins",onClick:()=>r("plugins")}),i.jsx(ti,{label:"Notifications",active:n==="notifications",onClick:()=>r("notifications")}),i.jsx(ti,{label:"Display",active:n==="display",onClick:()=>r("display")}),i.jsx(ti,{label:"Keybindings",active:n==="keybindings",onClick:()=>r("keybindings")}),i.jsx(ti,{label:"Advanced",active:n==="advanced",onClick:()=>r("advanced"),showDot:a})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0 px-4 pb-4",children:[n==="instructions"&&i.jsx($T,{isOpen:e}),n==="skills"&&i.jsx(BT,{isOpen:e}),n==="plugins"&&i.jsx(W6,{}),n==="notifications"&&i.jsx(ET,{}),n==="display"&&i.jsx(VT,{}),n==="keybindings"&&i.jsx(H6,{}),n==="tools"&&i.jsx(U6,{}),n==="advanced"&&i.jsx(B6,{onClose:t})]})]})})}function ti({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 op={exports:{}},wS;function K6(){return wS||(wS=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,j,N){var T,D=arguments.length,L=D<3?b:N===null?N=Object.getOwnPropertyDescriptor(b,j):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(v,b,j,N);else for(var O=v.length-1;O>=0;O--)(T=v[O])&&(L=(D<3?T(L):D>3?T(b,j,L):T(b,j))||L);return D>3&&L&&Object.defineProperty(b,j,L),L},p=this&&this.__param||function(v,b){return function(j,N){b(j,N,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,j,N){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=N,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(`
255
255
  `)))),this.register(this._terminal.onA11yTab((T=>this._handleTab(T)))),this.register(this._terminal.onKey((T=>this._handleKey(T.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,_.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,y.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(v){for(let b=0;b<v;b++)this._handleChar(" ")}_handleChar(v){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==v&&(this._charsToAnnounce+=v):this._charsToAnnounce+=v,v===`
256
256
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(v){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(v)||this._charsToConsume.push(v)}_refreshRows(v,b){this._liveRegionDebouncer.refresh(v,b,this._terminal.rows)}_renderRows(v,b){const j=this._terminal.buffer,N=j.lines.length.toString();for(let T=v;T<=b;T++){const D=j.lines.get(j.ydisp+T),L=[],O=(D==null?void 0:D.translateToString(!0,void 0,void 0,L))||"",M=(j.ydisp+T+1).toString(),W=this._rowElements[T];W&&(O.length===0?(W.innerText=" ",this._rowColumns.set(W,[0,1])):(W.textContent=O,this._rowColumns.set(W,L)),W.setAttribute("aria-posinset",M),W.setAttribute("aria-setsize",N))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(v,b){const j=v.target,N=this._rowElements[b===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(b===0?"1":`${this._terminal.buffer.lines.length}`)||v.relatedTarget!==N)return;let T,D;if(b===0?(T=j,D=this._rowElements.pop(),this._rowContainer.removeChild(D)):(T=this._rowElements.shift(),D=j,this._rowContainer.removeChild(T)),T.removeEventListener("focus",this._topBoundaryFocusListener),D.removeEventListener("focus",this._bottomBoundaryFocusListener),b===0){const L=this._createAccessibilityTreeNode();this._rowElements.unshift(L),this._rowContainer.insertAdjacentElement("afterbegin",L)}else{const L=this._createAccessibilityTreeNode();this._rowElements.push(L),this._rowContainer.appendChild(L)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(b===0?-1:1),this._rowElements[b===0?1:this._rowElements.length-2].focus(),v.preventDefault(),v.stopImmediatePropagation()}_handleSelectionChange(){var O;if(this._rowElements.length===0)return;const v=document.getSelection();if(!v)return;if(v.isCollapsed)return void(this._rowContainer.contains(v.anchorNode)&&this._terminal.clearSelection());if(!v.anchorNode||!v.focusNode)return void console.error("anchorNode and/or focusNode are null");let b={node:v.anchorNode,offset:v.anchorOffset},j={node:v.focusNode,offset:v.focusOffset};if((b.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||b.node===j.node&&b.offset>j.offset)&&([b,j]=[j,b]),b.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(b={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(b.node))return;const N=this._rowElements.slice(-1)[0];if(j.node.compareDocumentPosition(N)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(j={node:N,offset:((O=N.textContent)==null?void 0:O.length)??0}),!this._rowContainer.contains(j.node))return;const T=({node:M,offset:W})=>{const U=M instanceof Text?M.parentNode:M;let R=parseInt(U==null?void 0:U.getAttribute("aria-posinset"),10)-1;if(isNaN(R))return console.warn("row is invalid. Race condition?"),null;const H=this._rowColumns.get(U);if(!H)return console.warn("columns is null. Race condition?"),null;let G=W<H.length?H[W]:H.slice(-1)[0]+1;return G>=this._terminal.cols&&(++R,G=0),{row:R,column:G}},D=T(b),L=T(j);if(D&&L){if(D.row>L.row||D.row===L.row&&D.column>=L.column)throw new Error("invalid range");this._terminal.select(D.column,D.row,(L.row-D.row)*this._terminal.cols-D.column+L.column)}}_handleResize(v){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let b=this._rowContainer.children.length;b<this._terminal.rows;b++)this._rowElements[b]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[b]);for(;this._rowElements.length>v;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const v=this._coreBrowserService.mainDocument.createElement("div");return v.setAttribute("role","listitem"),v.tabIndex=-1,this._refreshRowDimensions(v),v}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let v=0;v<this._terminal.rows;v++)this._refreshRowDimensions(this._rowElements[v])}}_refreshRowDimensions(v){v.style.height=`${this._renderService.dimensions.css.cell.height}px`}};c.AccessibilityManager=S=h([p(1,C.IInstantiationService),p(2,w.ICoreBrowserService),p(3,w.IRenderService)],S)},3614:(u,c)=>{function d(x){return x.replace(/\r?\n/g,"\r")}function h(x,y){return y?"\x1B[200~"+x+"\x1B[201~":x}function p(x,y,w,C){x=h(x=d(x),w.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),w.triggerDataEvent(x,!0),y.value=""}function m(x,y,w){const C=w.getBoundingClientRect(),_=x.clientX-C.left-10,S=x.clientY-C.top-10;y.style.width="20px",y.style.height="20px",y.style.left=`${_}px`,y.style.top=`${S}px`,y.style.zIndex="1000",y.focus()}Object.defineProperty(c,"__esModule",{value:!0}),c.rightClickHandler=c.moveTextAreaUnderMouseCursor=c.paste=c.handlePasteEvent=c.copyHandler=c.bracketTextForPaste=c.prepareTextForTerminal=void 0,c.prepareTextForTerminal=d,c.bracketTextForPaste=h,c.copyHandler=function(x,y){x.clipboardData&&x.clipboardData.setData("text/plain",y.selectionText),x.preventDefault()},c.handlePasteEvent=function(x,y,w,C){x.stopPropagation(),x.clipboardData&&p(x.clipboardData.getData("text/plain"),y,w,C)},c.paste=p,c.moveTextAreaUnderMouseCursor=m,c.rightClickHandler=function(x,y,w,C,_){m(x,y,w),_&&C.rightClickSelect(x),y.value=C.selectionText,y.select()}},7239:(u,c,d)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.ColorContrastCache=void 0;const h=d(1505);c.ColorContrastCache=class{constructor(){this._color=new h.TwoKeyMap,this._css=new h.TwoKeyMap}setCss(p,m,x){this._css.set(p,m,x)}getCss(p,m){return this._css.get(p,m)}setColor(p,m,x){this._color.set(p,m,x)}getColor(p,m){return this._color.get(p,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(u,c)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.addDisposableDomListener=void 0,c.addDisposableDomListener=function(d,h,p,m){d.addEventListener(h,p,m);let x=!1;return{dispose:()=>{x||(x=!0,d.removeEventListener(h,p,m))}}}},3551:function(u,c,d){var h=this&&this.__decorate||function(S,v,b,j){var N,T=arguments.length,D=T<3?v:j===null?j=Object.getOwnPropertyDescriptor(v,b):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(S,v,b,j);else for(var L=S.length-1;L>=0;L--)(N=S[L])&&(D=(T<3?N(D):T>3?N(v,b,D):N(v,b))||D);return T>3&&D&&Object.defineProperty(v,b,D),D},p=this&&this.__param||function(S,v){return function(b,j){v(b,j,S)}};Object.defineProperty(c,"__esModule",{value:!0}),c.Linkifier=void 0;const m=d(3656),x=d(8460),y=d(844),w=d(2585),C=d(4725);let _=c.Linkifier=class extends y.Disposable{get currentLink(){return this._currentLink}constructor(S,v,b,j,N){super(),this._element=S,this._mouseService=v,this._renderService=b,this._bufferService=j,this._linkProviderService=N,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new x.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new x.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,y.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,y.toDisposable)((()=>{var T;this._lastMouseEvent=void 0,(T=this._activeProviderReplies)==null||T.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(S){this._lastMouseEvent=S;const v=this._positionFromMouseEvent(S,this._element,this._mouseService);if(!v)return;this._isMouseOut=!1;const b=S.composedPath();for(let j=0;j<b.length;j++){const N=b[j];if(N.classList.contains("xterm"))break;if(N.classList.contains("xterm-hover"))return}this._lastBufferCell&&v.x===this._lastBufferCell.x&&v.y===this._lastBufferCell.y||(this._handleHover(v),this._lastBufferCell=v)}_handleHover(S){if(this._activeLine!==S.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(S,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,S)||(this._clearCurrentLink(),this._askForLink(S,!0))}_askForLink(S,v){var j,N;this._activeProviderReplies&&v||((j=this._activeProviderReplies)==null||j.forEach((T=>{T==null||T.forEach((D=>{D.link.dispose&&D.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=S.y);let b=!1;for(const[T,D]of this._linkProviderService.linkProviders.entries())v?(N=this._activeProviderReplies)!=null&&N.get(T)&&(b=this._checkLinkProviderResult(T,S,b)):D.provideLinks(S.y,(L=>{var M,W;if(this._isMouseOut)return;const O=L==null?void 0:L.map((U=>({link:U})));(M=this._activeProviderReplies)==null||M.set(T,O),b=this._checkLinkProviderResult(T,S,b),((W=this._activeProviderReplies)==null?void 0:W.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(S.y,this._activeProviderReplies)}))}_removeIntersectingLinks(S,v){const b=new Set;for(let j=0;j<v.size;j++){const N=v.get(j);if(N)for(let T=0;T<N.length;T++){const D=N[T],L=D.link.range.start.y<S?0:D.link.range.start.x,O=D.link.range.end.y>S?this._bufferService.cols:D.link.range.end.x;for(let M=L;M<=O;M++){if(b.has(M)){N.splice(T--,1);break}b.add(M)}}}}_checkLinkProviderResult(S,v,b){var T;if(!this._activeProviderReplies)return b;const j=this._activeProviderReplies.get(S);let N=!1;for(let D=0;D<S;D++)this._activeProviderReplies.has(D)&&!this._activeProviderReplies.get(D)||(N=!0);if(!N&&j){const D=j.find((L=>this._linkAtPosition(L.link,v)));D&&(b=!0,this._handleNewLink(D))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!b)for(let D=0;D<this._activeProviderReplies.size;D++){const L=(T=this._activeProviderReplies.get(D))==null?void 0:T.find((O=>this._linkAtPosition(O.link,v)));if(L){b=!0,this._handleNewLink(L);break}}return b}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(S){if(!this._currentLink)return;const v=this._positionFromMouseEvent(S,this._element,this._mouseService);v&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,v)&&this._currentLink.link.activate(S,this._currentLink.link.text)}_clearCurrentLink(S,v){this._currentLink&&this._lastMouseEvent&&(!S||!v||this._currentLink.link.range.start.y>=S&&this._currentLink.link.range.end.y<=v)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,y.disposeArray)(this._linkCacheDisposables))}_handleNewLink(S){if(!this._lastMouseEvent)return;const v=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);v&&this._linkAtPosition(S.link,v)&&(this._currentLink=S,this._currentLink.state={decorations:{underline:S.link.decorations===void 0||S.link.decorations.underline,pointerCursor:S.link.decorations===void 0||S.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,S.link,this._lastMouseEvent),S.link.decorations={},Object.defineProperties(S.link.decorations,{pointerCursor:{get:()=>{var b,j;return(j=(b=this._currentLink)==null?void 0:b.state)==null?void 0:j.decorations.pointerCursor},set:b=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==b&&(this._currentLink.state.decorations.pointerCursor=b,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",b))}},underline:{get:()=>{var b,j;return(j=(b=this._currentLink)==null?void 0:b.state)==null?void 0:j.decorations.underline},set:b=>{var j,N,T;(j=this._currentLink)!=null&&j.state&&((T=(N=this._currentLink)==null?void 0:N.state)==null?void 0:T.decorations.underline)!==b&&(this._currentLink.state.decorations.underline=b,this._currentLink.state.isHovered&&this._fireUnderlineEvent(S.link,b))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((b=>{if(!this._currentLink)return;const j=b.start===0?0:b.start+1+this._bufferService.buffer.ydisp,N=this._bufferService.buffer.ydisp+1+b.end;if(this._currentLink.link.range.start.y>=j&&this._currentLink.link.range.end.y<=N&&(this._clearCurrentLink(j,N),this._lastMouseEvent)){const T=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);T&&this._askForLink(T,!1)}}))))}_linkHover(S,v,b){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!0),this._currentLink.state.decorations.pointerCursor&&S.classList.add("xterm-cursor-pointer")),v.hover&&v.hover(b,v.text)}_fireUnderlineEvent(S,v){const b=S.range,j=this._bufferService.buffer.ydisp,N=this._createLinkUnderlineEvent(b.start.x-1,b.start.y-j-1,b.end.x,b.end.y-j-1,void 0);(v?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(N)}_linkLeave(S,v,b){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!1),this._currentLink.state.decorations.pointerCursor&&S.classList.remove("xterm-cursor-pointer")),v.leave&&v.leave(b,v.text)}_linkAtPosition(S,v){const b=S.range.start.y*this._bufferService.cols+S.range.start.x,j=S.range.end.y*this._bufferService.cols+S.range.end.x,N=v.y*this._bufferService.cols+v.x;return b<=N&&N<=j}_positionFromMouseEvent(S,v,b){const j=b.getCoords(S,v,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(S,v,b,j,N){return{x1:S,y1:v,x2:b,y2:j,cols:this._bufferService.cols,fg:N}}};c.Linkifier=_=h([p(1,C.IMouseService),p(2,C.IRenderService),p(3,w.IBufferService),p(4,C.ILinkProviderService)],_)},9042:(u,c)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.tooMuchOutput=c.promptLabel=void 0,c.promptLabel="Terminal input",c.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(u,c,d){var h=this&&this.__decorate||function(C,_,S,v){var b,j=arguments.length,N=j<3?_:v===null?v=Object.getOwnPropertyDescriptor(_,S):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(C,_,S,v);else for(var T=C.length-1;T>=0;T--)(b=C[T])&&(N=(j<3?b(N):j>3?b(_,S,N):b(_,S))||N);return j>3&&N&&Object.defineProperty(_,S,N),N},p=this&&this.__param||function(C,_){return function(S,v){_(S,v,C)}};Object.defineProperty(c,"__esModule",{value:!0}),c.OscLinkProvider=void 0;const m=d(511),x=d(2585);let y=c.OscLinkProvider=class{constructor(C,_,S){this._bufferService=C,this._optionsService=_,this._oscLinkService=S}provideLinks(C,_){var O;const S=this._bufferService.buffer.lines.get(C-1);if(!S)return void _(void 0);const v=[],b=this._optionsService.rawOptions.linkHandler,j=new m.CellData,N=S.getTrimmedLength();let T=-1,D=-1,L=!1;for(let M=0;M<N;M++)if(D!==-1||S.hasContent(M)){if(S.loadCell(M,j),j.hasExtendedAttrs()&&j.extended.urlId){if(D===-1){D=M,T=j.extended.urlId;continue}L=j.extended.urlId!==T}else D!==-1&&(L=!0);if(L||D!==-1&&M===N-1){const W=(O=this._oscLinkService.getLinkData(T))==null?void 0:O.uri;if(W){const U={start:{x:D+1,y:C},end:{x:M+(L||M!==N-1?0:1),y:C}};let R=!1;if(!(b!=null&&b.allowNonHttpProtocols))try{const H=new URL(W);["http:","https:"].includes(H.protocol)||(R=!0)}catch{R=!0}R||v.push({text:W,range:U,activate:(H,G)=>b?b.activate(H,G,U):w(0,G),hover:(H,G)=>{var V;return(V=b==null?void 0:b.hover)==null?void 0:V.call(b,H,G,U)},leave:(H,G)=>{var V;return(V=b==null?void 0:b.leave)==null?void 0:V.call(b,H,G,U)}})}L=!1,j.hasExtendedAttrs()&&j.extended.urlId?(D=M,T=j.extended.urlId):(D=-1,T=-1)}}_(v)}};function w(C,_){if(confirm(`Do you want to navigate to ${_}?
257
257
 
@@ -270,9 +270,9 @@ WARNING: This link could potentially be dangerous`)){const S=window.open();if(S)
270
270
  * Fabrice Bellard's javascript vt100 for jslinux:
271
271
  * http://bellard.org/jslinux/
272
272
  * Copyright (c) 2011 Fabrice Bellard
273
- */var X6=2,Q6=1,J6=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(X6,Math.floor(p/e.css.cell.width)),rows:Math.max(Q6,Math.floor(h/e.css.cell.height))}}};function Z6({sessionId:e,onClose:t,onEscape:n,autoFocus:r}){const a=E.useRef(null),l=E.useRef(e),u=E.useRef(null),c=E.useRef(null),d=Lr(p=>p.writeSession),h=Lr(p=>p.resizeSession);return E.useEffect(()=>{l.current=e},[e]),E.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]),E.useEffect(()=>{if(!a.current)return;const p=new Y6.Terminal({fontFamily:'"JetBrains Mono", monospace',fontSize:13,theme:{background:"#1a1a1a",foreground:"#e0e0e0",cursor:"#ffffff",cursorAccent:"#1a1a1a"},cursorBlink:!0,cursorStyle:"bar",convertEol:!0}),m=new J6;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=Bt.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(lg,{})})]}),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 Tk="openfox-chat-textarea";function Gl(e){const t=document.getElementById(Tk);t&&(e===void 0?t.focus():t.focus({preventScroll:e}))}function eB(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 tB({isOpen:e,onClose:t}){const n=Lr(C=>C.createSession),r=Lr(C=>C.killSession),a=Lr(C=>C.sessions),l=Lr(C=>C.setWorkdir),u=Lr(C=>C.fetchSessions),c=Gt(C=>C.currentProject),d=Le(C=>C.currentSession),[h,p]=E.useState(!0),m=E.useRef(null),x=E.useRef(!1),y=E.useRef(!1),w=E.useCallback(()=>{t()},[t]);return E.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]),E.useEffect(()=>{e?(p(!0),u(c==null?void 0:c.id).finally(()=>p(!1))):Gl()},[e,u,c==null?void 0:c.id]),E.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]),E.useEffect(()=>{e?(x.current=!0,setTimeout(()=>{var C;(C=m.current)==null||C.focus(),setTimeout(()=>{x.current=!1},200)},100)):y.current=!1},[e]),E.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(uT,{})}),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 ${eB(a.length)} gap-2 h-full auto-rows-fr`,children:a.map(C=>i.jsx(Z6,{sessionId:C.id,onClose:()=>r(C.id),onEscape:w,autoFocus:a.length===1},C.id))})})]})]}):null}function nc({items:e,footerItems:t=[],trigger:n,minWidth:r="120px",isOpen:a,onOpenChange:l}){const[u,c]=E.useState(!1),d=a!==void 0,h=d?a:u,p=R=>{if(d){const H=typeof R=="function"?R(u):R;l==null||l(H)}else c(R)},[m,x]=E.useState(null),y=E.useRef(null),w=E.useRef(null),[C,_]=E.useState(0),S=E.useRef(0),v=E.useMemo(()=>[...e,...t],[e,t]),b=E.useRef(v),j=E.useCallback(()=>{if(!y.current)return;const R=y.current.getBoundingClientRect(),H=200,V=window.innerHeight-R.bottom<H;x({top:V?R.top-H-4:R.bottom+4,left:R.left,alignToTop:V})},[]);E.useEffect(()=>{b.current=v},[v]),E.useEffect(()=>{function R(H){if(w.current){const G=H.target;w.current.contains(G)||p(!1)}}return h&&document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R)}},[h]),E.useEffect(()=>{h&&j()},[h,j]),E.useEffect(()=>{if(!h)return;setTimeout(()=>{var H;(H=w.current)==null||H.focus()},0);function R(H){const G=b.current,V=G.filter(X=>!N(X)),Z=T(S.current,G);switch(H.key){case"ArrowDown":if(H.preventDefault(),H.stopPropagation(),Z<V.length-1){const X=D(S.current+1,G);S.current=X,_(X)}break;case"ArrowUp":if(H.preventDefault(),H.stopPropagation(),Z>0){const X=L(S.current-1,G);S.current=X,_(X)}break;case"Enter":H.preventDefault(),H.stopPropagation(),O(S.current,G);break;case"Escape":H.preventDefault(),H.stopPropagation(),p(!1);break}}return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[h,v]);function N(R){var V;const H=R.label;return H?String(((V=H.props)==null?void 0:V.className)??"").includes("cursor-default"):!1}function T(R,H){let G=0;for(let V=0;V<R;V++){const Z=H[V];Z&&!N(Z)&&G++}return G}function D(R,H){for(let G=R;G<H.length;G++){const V=H[G];if(V&&!N(V))return G}return R}function L(R,H){for(let G=R;G>=0;G--){const V=H[G];if(V&&!N(V))return G}return R}function O(R,H){var V;const G=H[R];!G||N(G)||((V=G.onClick)==null||V.call(G),G.href&&(window.history.pushState(null,"",G.href),window.dispatchEvent(new PopStateEvent("popstate"))),p(!1))}E.useEffect(()=>{h&&(_(v.findIndex(R=>!N(R))),S.current=v.findIndex(R=>!N(R)))},[h,v]);const M=R=>{R.stopPropagation(),h||j(),p(!h)};function W(R,H,G,V){const X=!N(R)&&V===C,$=i.jsxs(i.Fragment,{children:[R.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0",children:R.icon}),R.label]}),I=H!==G-1;return R.href?i.jsx(Xn,{href:R.href,onClick:B=>{var q;(q=R.onClick)==null||q.call(R,B),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"} ${I?"border-b border-border":""}`,children:$},V):i.jsx("button",{onClick:B=>{var q;(q=R.onClick)==null||q.call(R,B),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"} ${I?"border-b border-border":""}`,children:$},V)}const U=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,H)=>W(R,H,e.length,H))}),t.length>0&&i.jsx("div",{className:"border-t border-border",children:t.map((R,H)=>W(R,H,t.length,e.length+H))})]});return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"relative",children:i.jsx("div",{ref:y,onClick:M,children:n})}),h&&mi.createPortal(U,document.body)]})}function nB(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 Ak({isOpen:e,onClose:t,path:n,onRetry:r}){const[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(null);E.useEffect(()=>{e&&p()},[e]);const p=async()=>{try{const j=await(await ve("/api/projects/check-permissions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})})).json();h({sudoAvailable:j.sudoAvailable,userInGroup:j.userInGroup,groupHasWrite:j.groupHasWrite,groupName:j.groupName||null})}catch{h({sudoAvailable:!1,userInGroup:!1,groupHasWrite:!1,groupName:null})}},m=E.useCallback(async b=>{l(!0),c(null);try{const N=await(await ve("/api/projects/fix-permissions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n,action:b})})).json();N.success?(r(),t()):N.sudoAvailable?c("Failed to fix permissions: "+(N.error||"Unknown error")):c(`Passwordless sudo is not available. Please fix permissions manually:
273
+ */var X6=2,Q6=1,J6=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(X6,Math.floor(p/e.css.cell.width)),rows:Math.max(Q6,Math.floor(h/e.css.cell.height))}}};function Z6({sessionId:e,onClose:t,onEscape:n,autoFocus:r}){const a=E.useRef(null),l=E.useRef(e),u=E.useRef(null),c=E.useRef(null),d=Lr(p=>p.writeSession),h=Lr(p=>p.resizeSession);return E.useEffect(()=>{l.current=e},[e]),E.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]),E.useEffect(()=>{if(!a.current)return;const p=new Y6.Terminal({fontFamily:'"JetBrains Mono", monospace',fontSize:13,theme:{background:"#1a1a1a",foreground:"#e0e0e0",cursor:"#ffffff",cursorAccent:"#1a1a1a"},cursorBlink:!0,cursorStyle:"bar",convertEol:!0}),m=new J6;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=Dt.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(lg,{})})]}),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 Tk="openfox-chat-textarea";function Gl(e){const t=document.getElementById(Tk);t&&(e===void 0?t.focus():t.focus({preventScroll:e}))}function eB(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 tB({isOpen:e,onClose:t}){const n=Lr(C=>C.createSession),r=Lr(C=>C.killSession),a=Lr(C=>C.sessions),l=Lr(C=>C.setWorkdir),u=Lr(C=>C.fetchSessions),c=Gt(C=>C.currentProject),d=Le(C=>C.currentSession),[h,p]=E.useState(!0),m=E.useRef(null),x=E.useRef(!1),y=E.useRef(!1),w=E.useCallback(()=>{t()},[t]);return E.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]),E.useEffect(()=>{e?(p(!0),u(c==null?void 0:c.id).finally(()=>p(!1))):Gl()},[e,u,c==null?void 0:c.id]),E.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]),E.useEffect(()=>{e?(x.current=!0,setTimeout(()=>{var C;(C=m.current)==null||C.focus(),setTimeout(()=>{x.current=!1},200)},100)):y.current=!1},[e]),E.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(uT,{})}),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 ${eB(a.length)} gap-2 h-full auto-rows-fr`,children:a.map(C=>i.jsx(Z6,{sessionId:C.id,onClose:()=>r(C.id),onEscape:w,autoFocus:a.length===1},C.id))})})]})]}):null}function nc({items:e,footerItems:t=[],trigger:n,minWidth:r="120px",isOpen:a,onOpenChange:l}){const[u,c]=E.useState(!1),d=a!==void 0,h=d?a:u,p=R=>{if(d){const H=typeof R=="function"?R(u):R;l==null||l(H)}else c(R)},[m,x]=E.useState(null),y=E.useRef(null),w=E.useRef(null),[C,_]=E.useState(0),S=E.useRef(0),v=E.useMemo(()=>[...e,...t],[e,t]),b=E.useRef(v),j=E.useCallback(()=>{if(!y.current)return;const R=y.current.getBoundingClientRect(),H=200,V=window.innerHeight-R.bottom<H;x({top:V?R.top-H-4:R.bottom+4,left:R.left,alignToTop:V})},[]);E.useEffect(()=>{b.current=v},[v]),E.useEffect(()=>{function R(H){if(w.current){const G=H.target;w.current.contains(G)||p(!1)}}return h&&document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R)}},[h]),E.useEffect(()=>{h&&j()},[h,j]),E.useEffect(()=>{if(!h)return;setTimeout(()=>{var H;(H=w.current)==null||H.focus()},0);function R(H){const G=b.current,V=G.filter(X=>!N(X)),Z=T(S.current,G);switch(H.key){case"ArrowDown":if(H.preventDefault(),H.stopPropagation(),Z<V.length-1){const X=D(S.current+1,G);S.current=X,_(X)}break;case"ArrowUp":if(H.preventDefault(),H.stopPropagation(),Z>0){const X=L(S.current-1,G);S.current=X,_(X)}break;case"Enter":H.preventDefault(),H.stopPropagation(),O(S.current,G);break;case"Escape":H.preventDefault(),H.stopPropagation(),p(!1);break}}return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[h,v]);function N(R){var V;const H=R.label;return H?String(((V=H.props)==null?void 0:V.className)??"").includes("cursor-default"):!1}function T(R,H){let G=0;for(let V=0;V<R;V++){const Z=H[V];Z&&!N(Z)&&G++}return G}function D(R,H){for(let G=R;G<H.length;G++){const V=H[G];if(V&&!N(V))return G}return R}function L(R,H){for(let G=R;G>=0;G--){const V=H[G];if(V&&!N(V))return G}return R}function O(R,H){var V;const G=H[R];!G||N(G)||((V=G.onClick)==null||V.call(G),G.href&&(window.history.pushState(null,"",G.href),window.dispatchEvent(new PopStateEvent("popstate"))),p(!1))}E.useEffect(()=>{h&&(_(v.findIndex(R=>!N(R))),S.current=v.findIndex(R=>!N(R)))},[h,v]);const M=R=>{R.stopPropagation(),h||j(),p(!h)};function W(R,H,G,V){const X=!N(R)&&V===C,$=i.jsxs(i.Fragment,{children:[R.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0",children:R.icon}),R.label]}),I=H!==G-1;return R.href?i.jsx(Xn,{href:R.href,onClick:B=>{var q;(q=R.onClick)==null||q.call(R,B),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"} ${I?"border-b border-border":""}`,children:$},V):i.jsx("button",{onClick:B=>{var q;(q=R.onClick)==null||q.call(R,B),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"} ${I?"border-b border-border":""}`,children:$},V)}const U=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,H)=>W(R,H,e.length,H))}),t.length>0&&i.jsx("div",{className:"border-t border-border",children:t.map((R,H)=>W(R,H,t.length,e.length+H))})]});return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"relative",children:i.jsx("div",{ref:y,onClick:M,children:n})}),h&&mi.createPortal(U,document.body)]})}function nB(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 Ak({isOpen:e,onClose:t,path:n,onRetry:r}){const[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(null);E.useEffect(()=>{e&&p()},[e]);const p=async()=>{try{const j=await(await ve("/api/projects/check-permissions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})})).json();h({sudoAvailable:j.sudoAvailable,userInGroup:j.userInGroup,groupHasWrite:j.groupHasWrite,groupName:j.groupName||null})}catch{h({sudoAvailable:!1,userInGroup:!1,groupHasWrite:!1,groupName:null})}},m=E.useCallback(async b=>{l(!0),c(null);try{const N=await(await ve("/api/projects/fix-permissions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n,action:b})})).json();N.success?(r(),t()):N.sudoAvailable?c("Failed to fix permissions: "+(N.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(j){c("Failed to fix permissions: "+(j instanceof Error?j.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(jt,{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(rt,{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(rt,{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(rt,{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(rt,{type:"button",variant:"secondary",onClick:t,disabled:a,children:"Cancel"})})]}):null]})})}function Lk({isOpen:e,onClose:t}){const[,n]=Tn(),r=Gt(N=>N.listProjects),[a,l]=E.useState(""),[u,c]=E.useState(null),[d,h]=E.useState(!1),[p,m]=E.useState(""),[x,y]=E.useState(null),w=E.useRef(null);E.useEffect(()=>{e&&(ve("/api/config").then(N=>N.json()).then(N=>{N.workdir&&m(N.workdir)}),l(""),c(null),h(!1),y(null),setTimeout(()=>{var N;(N=w.current)==null||N.focus()},100))},[e]);const C=E.useCallback(async N=>{N.preventDefault();const T=nB(a);if(!T.valid){c(T.error);return}const D=`${p}/${a}`;await v(D)},[a,n,t,p]),_=E.useCallback(()=>{y(null)},[]),S=E.useCallback(async()=>{const N=`${p}/${a}`;await v(N)},[p,a,n,t,y,c,h]);async function v(N){h(!0),c(null),y(null);try{const T=await ve("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,workdir:N})});if(!T.ok){const O=await T.json().catch(()=>({}));if(O.code==="EACCES"){y(N),h(!1);return}throw new Error(O.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=E.useCallback(()=>{l(""),c(null),t()},[t]),j=a?`${p}/${a}`:"";return i.jsxs(i.Fragment,{children:[i.jsx(jt,{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(ui,{ref:w,id:"project-name",value:a,onChange:N=>{l(N.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:j})]}),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(rt,{type:"button",variant:"secondary",onClick:b,disabled:d,children:"Cancel"}),i.jsx(rt,{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(Xr,{className:"h-4 w-4"}),"Creating..."]}):"Create"})]})]})}),x&&i.jsx(Ak,{isOpen:!!x,onClose:_,path:x,onRetry:S})]})}function Dk(){const[e,t]=E.useState(null);return E.useEffect(()=>{ve("/api/config").then(n=>n.json()).then(n=>{n.workdir&&t(n.workdir)})},[]),e}function CS({projects:e,currentProject:t}){const[,n]=Tn(),r=Gt(_=>_.loadProject),a=Gt(_=>_.toggleStar),l=Gt(_=>_.createProject),u=Gt(_=>_.listProjects),[c,d]=E.useState(!1),[h,p]=E.useState(!1),m=Dk(),x=E.useCallback(async _=>{const S=z1(_),v=await l(S,_);return v&&"id"in v?(await u(),p(!1),n(`/p/${v.id}`),!0):!1},[l,u,n]),w=E.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(L1,{className:"w-3.5 h-3.5 text-yellow-500"}):i.jsx(D1,{className:"w-3.5 h-3.5 text-text-muted hover:text-yellow-500"})})]}),icon:_.id===(t==null?void 0:t.id)?i.jsx(Mr,{}):void 0,href:`/p/${_.id}`,closeOnClick:!0,onClick:()=>{r(_.id)}})),C=[{label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Rr,{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(Xr,{className:"w-4 h-4"}),i.jsx("span",{children:"New Project"})]}),onClick:()=>d(!0)}];return i.jsxs(i.Fragment,{children:[i.jsx(nc,{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(hn,{})]}),minWidth:"250px"}),c&&i.jsx(Lk,{isOpen:c,onClose:()=>d(!1)}),h&&i.jsx(Td,{initialPath:m??void 0,onSelect:x,onClose:()=>p(!1)})]})}function Rk(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 Xd(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}:${r}`}function rB(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=Xd(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 Ok(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 sB(e){const{year:t,month:n,day:r}=Ok(e);return`${t}-${n}-${r}`}function Ik(e){const t=new Map;for(const a of e){const l=sB(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 iB(e){const{year:t,month:n,day:r}=Ok(e);return`${t}/${n}/${r} ${Xd(e)}`}function pd(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function aB({sessions:e,currentProject:t,currentSession:n,isOpen:r,onOpenChange:a}){var x;const l=Le(y=>y.loadSession),u=50,c=e.filter(y=>y.projectId===t.id).slice(0,15),d=Ik(c),h=E.useMemo(()=>{const y=[];y.push({label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xr,{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:Rk(_.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:pd(S.title??S.id.slice(0,8),u)}),i.jsx("div",{className:"text-text-muted text-xs",children:Xd(S.updatedAt)})]}),icon:S.id===(n==null?void 0:n.id)?i.jsx(Mr,{}):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?pd(p,u):"No session selected";return i.jsx(nc,{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(hn,{})]}),minWidth:"280px"})}function oB({items:e,trigger:t,isActive:n=!1}){const[r,a]=E.useState(!1),l=E.useRef(null);return E.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(hn,{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===Xn?u.label:null;if(d){const h=d.props.href||"";return i.jsxs(Xn,{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 lB({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(Xn,{href:`/p/${e.id}/new`,className:"flex items-center gap-2",children:[i.jsx(Xr,{className:"w-3 h-3 text-accent-primary"}),i.jsx("span",{className:"text-sm",children:"New Session"})]})},...a.map(u=>({label:i.jsx(Xn,{href:`/p/${e.id}/s/${u.id}`,className:"flex items-center gap-2 truncate text-sm",children:i.jsx("span",{children:pd(u.title??u.id.slice(0,8),50)})}),icon:u.id===(n==null?void 0:n.id)?i.jsx(Mr,{className:"w-3 h-3"}):void 0})),{label:i.jsxs(Xn,{href:"/",className:"flex items-center gap-2 text-text-muted hover:text-text-primary",children:[i.jsx(rT,{className:"w-3 h-3"}),i.jsx("span",{className:"text-sm",children:"Projects"})]})}];return i.jsx(oB,{items:l,trigger:i.jsx("span",{className:"text-sm text-text-secondary font-medium",children:e.name})})}function cB({onMenuClick:e,onCriteriaToggle:t}){const[n,r]=E.useState(!1),[a,l]=E.useState(!1),[u,c]=E.useState(!!document.fullscreenElement),[d,h]=Tn();E.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=Le(D=>D.currentSession),y=Le(D=>D.sessions),w=Gt(D=>D.currentProject),C=Gt(D=>D.projects),_=Xt(D=>D.startAutoRefresh),S=Xt(D=>D.stopAutoRefresh),v=Lr(D=>D.setOpen),b=Lr(D=>D.isOpen),j=Cs(D=>D.status==="available"),N=Cs(D=>D.check);E.useEffect(()=>{Cs.getState().status==="idle"&&N()},[N]),E.useEffect(()=>{const D=()=>l(!0);return window.addEventListener("open-session-dropdown",D),()=>window.removeEventListener("open-session-dropdown",D)},[]);const T=Kl();return Ol(T.terminalToggle,()=>{Lr.getState().toggleOpen()},{capture:!0}),E.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 (${Xu(T.sessionSearch)})`:"Toggle session list",children:i.jsx(A_,{})}),i.jsx(Xn,{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(CS,{projects:C,currentProject:w})}),i.jsx("span",{className:"md:hidden",children:i.jsx(lB,{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(aB,{sessions:y,currentProject:w,currentSession:x,isOpen:a,onOpenChange:l})})]}),!w&&i.jsx("span",{className:"hidden md:inline",children:i.jsx(CS,{projects:C})})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[m&&i.jsx("button",{onClick:()=>{var D,L,O;document.fullscreenElement?(D=document.exitFullscreen)==null||D.call(document):(O=(L=document.documentElement).requestFullscreen)==null||O.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(aT,{}):i.jsx(oT,{})}),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(mT,{})}),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:j?"Settings — update available":"Settings",children:[i.jsx(dT,{}),j&&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(cT,{})}),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 (${Xu(T.criteriaSidebar)})`:"Toggle criteria sidebar",children:i.jsx(A_,{})})]}),i.jsx(q6,{isOpen:n,onClose:()=>r(!1)}),i.jsx(tB,{isOpen:b,onClose:()=>v(!1)})]})}function Mk({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(rt,{variant:"secondary",onClick:e,children:a}),i.jsx(rt,{variant:"primary",onClick:t,disabled:r??n,children:l})]})}const Ru=In()(e=>({config:null,loading:!1,fetchConfig:async t=>{e({loading:!0});try{const r=await(await ve(`/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 ve(`/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})}})),uB=["/","/etc","/bin","/sbin","/lib","/lib64","/usr","/var","/opt","/root","/run","/tmp","/home","/mnt","/media"],dB=["/proc/","/sys/","/dev/","/boot/","/etc/","/lost+found/"];function hB(e,t=uB,n=dB){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 fB({isOpen:e,onClose:t,project:n}){const r=Gt(te=>te.updateProject),a=Ru(te=>te.config),l=Ru(te=>te.loading),u=Ru(te=>te.fetchConfig),c=Ru(te=>te.saveConfig),d=()=>{try{Bt.send("context.checkDynamic",{})}catch{}t()},[h,p]=E.useState(n.customInstructions??""),[m,x]=E.useState(n.dangerLevel??""),[y,w]=E.useState(!1),[C,_]=E.useState(!1),[S,v]=E.useState(!1),[b,j]=E.useState(null),[N,T]=E.useState(""),[D,L]=E.useState(!1),[O,M]=E.useState(""),[W,U]=E.useState(!1),[R,H]=E.useState(""),[G,V]=E.useState(!1),[Z,X]=E.useState(!1),[$,I]=E.useState([]),[B,q]=E.useState(""),[z,ne]=E.useState({}),[re,Q]=E.useState(!1),[K,P]=E.useState(new Set),J=y||C||D||W||re;E.useEffect(()=>{e&&(p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),U(!1),Q(!1),P(new Set),u(n.workdir))},[e,n,u]),E.useEffect(()=>{a!=null&&a.setup&&a.setup.length>0?T(a.setup.join(" && ")):T(""),M((a==null?void 0:a.rootDir)??""),ne((a==null?void 0:a.mcpOverrides)??{})},[a]);const ie=Dl(te=>te.servers),he=te=>z[te]??{},ce=te=>{var me;const ae=he(te);if(ae.disabled!==void 0)return ae.disabled;const se=ie.find(Ue=>Ue.name===te);return!!((me=se==null?void 0:se.config)!=null&&me.disabled)},De=(te,ae)=>{var me;return((me=he(te).disabledTools)==null?void 0:me.includes(ae))??!1},Re=te=>{ne(ae=>({...ae,[te]:{...ae[te],disabled:!ce(te)}})),Q(!0)},ze=(te,ae)=>{ne(se=>{const me=se[te]??{},Ue=me.disabledTools??[],He=Ue.includes(ae)?Ue.filter(Ye=>Ye!==ae):[...Ue,ae];return{...se,[te]:{...me,disabledTools:He.length>0?He:void 0}}}),Q(!0)},Fe=te=>{P(ae=>{if(ae.has(te)){const me=new Set(ae);return me.delete(te),me}const se=new Set(ae);return se.add(te),se})},Ee=te=>{p(te.target.value),w(!0)},st=te=>{x(te),_(!0)},ot=te=>{T(te.target.value),L(!0)},je=te=>{M(te.target.value),U(!0)},Me=E.useCallback(async()=>{const te=m===""?null:m;await r(n.id,{customInstructions:h||null,dangerLevel:te});const ae=N.trim()?N.split("&&").map(se=>se.trim()).filter(Boolean):[];await c(n.workdir,{...ae.length>0?{setup:ae}:{},rootDir:O.trim(),...Object.keys(z).length>0?{mcpOverrides:z}:{mcpOverrides:void 0}}),w(!1),_(!1),L(!1),U(!1),Q(!1),d()},[n.id,m,h,N,O,z,r,c,n.workdir,d]),lt=async()=>{const te=O.trim(),ae=(a==null?void 0:a.rootDir)??"";if(te){const se=hB(te);if(se==="exact"){const me=te.replace(/\/+$/,"")||"/";j(`Cannot use "${me}" directly as workspace root. Use a subdirectory like "${me}/${n.name}" instead.`);return}if(se==="virtual_fs"){j(`Cannot use paths under "${te}" for workspaces.`);return}}if(!W||!te||te===ae){v(!0),j(null);try{await Me()}catch(se){j(se instanceof Error?se.message:"Failed to save settings")}finally{v(!1)}return}H(te),v(!0),j(null);try{const se=await ve(`/api/workspace/config/validate?workdir=${encodeURIComponent(n.workdir)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rootDir:te,workdir:n.workdir,projectName:n.name})});if(!se.ok){const Ue=await se.json().catch(()=>({}));j((Ue==null?void 0:Ue.error)??"Failed to validate workspace root directory"),v(!1);return}const me=await se.json();if(!me.exists){q(me.resolvedPath),v(!1),V(!0);return}if(me.workspaces&&me.workspaces.length>0){I(me.workspaces),v(!1),X(!0);return}j(null),await Me()}catch(se){j(se instanceof Error?se.message:"Failed to validate settings"),v(!1)}},we=async()=>{V(!1),v(!0);try{const te=await ve(`/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(!te.ok){const se=await te.json().catch(()=>({}));j((se==null?void 0:se.error)??"Failed to create directory"),v(!1);return}const ae=await te.json();if(ae.workspaces&&ae.workspaces.length>0){I(ae.workspaces),X(!0),v(!1);return}await Me()}catch(te){j(te instanceof Error?te.message:"Failed to create directory")}finally{v(!1)}},Ie=async()=>{X(!1),v(!0),j(null);try{await Me()}catch(te){j(te instanceof Error?te.message:"Failed to save settings")}finally{v(!1)}},qe=()=>{V(!1),X(!1),p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),U(!1),d()};return i.jsxs(jt,{isOpen:e,onClose:qe,title:`${n.name} Settings`,size:"lg",footer:i.jsx(Mk,{onCancel:qe,onSave:lt,saving:S,saveDisabled:!J||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:()=>st(""),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:()=>st("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:()=>st("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:Ee,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:N,onChange:ot,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:O,onChange:je,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})]}),ie.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:ie.map(te=>{const ae=ce(te.name);return i.jsx(jk,{server:te,expanded:K.has(te.name),onToggleExpand:Fe,serverToggleEnabled:!ae,onServerToggle:()=>Re(te.name),tools:te.tools.map(se=>({...se,enabled:!De(te.name,se.name)})),onToolToggle:se=>ze(te.name,se),statusDot:Kg(ae?"disabled":te.status),statusColor:qg(ae?"disabled":te.status)},te.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})]}),G&&i.jsxs(jt,{isOpen:G,onClose:()=>V(!1),title:"Directory not found",size:"md",footer:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{type:"button",onClick:()=>V(!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:we,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:B})," does not exist."]}),i.jsx("p",{className:"text-sm text-text-muted mt-2",children:"Would you like to create it?"})]}),Z&&i.jsxs(jt,{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:Ie,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(te=>i.jsx("li",{className:"text-sm font-mono text-text-muted",children:te.name},te.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 mB={sm:"w-3 h-3",md:"w-4 h-4",lg:"w-5 h-5",xl:"w-6 h-6"},pB="M6 18L18 6M6 6l12 12";function rc({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(Ed,{onClick:e,icon:pB,iconSize:mB[n],className:`${a} ${t}`,title:"Close"})}function qr(e,t){const n=new Set(t.map(r=>r.id));return[...e.filter(r=>!n.has(r.id)),...t]}function Jp(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 li(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 Pk(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 Bk({projectId:e,isOpen:t=!0,onClose:n}){const[,r]=Tn(),[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(null),[p,m]=E.useState(""),[x,y]=E.useState(!1),w=Le(ce=>ce.sessions),C=Le(ce=>ce.currentSession),_=Le(ce=>ce.unreadSessionIds),S=Le(ce=>ce.deleteSession),v=Le(ce=>ce.deleteAllSessions),b=Le(ce=>ce.loadMoreSessions),j=Le(ce=>ce.sessionsHasMore),N=Le(ce=>ce.sessionsPaginationLoading),T=Le(ce=>ce.sessionsWithPendingConfirmations),D=Le(ce=>ce.pendingPathConfirmations),L=Gt(ce=>ce.currentProject),[O,M]=E.useState(""),[W,U]=E.useState(-1),R=E.useRef(null),H=E.useRef(null),G=E.useRef(!1),V=Kl();Ol(V.sessionSearch,()=>{var ce;if(t&&document.activeElement===R.current){n==null||n();return}t||(G.current=!0,n==null||n()),(ce=R.current)==null||ce.focus()});const Z=E.useRef(null),X=E.useCallback(()=>{j&&!N&&L&&b(L.id)},[j,N,L,b]);E.useEffect(()=>{if(!Z.current||!j)return;const ce=new IntersectionObserver(De=>{const Re=De[0];Re&&Re.isIntersecting&&X()},{threshold:.1});return ce.observe(Z.current),()=>ce.disconnect()},[j,X]);const $=w.filter(ce=>ce.projectId===(L==null?void 0:L.id)),I=E.useMemo(()=>O?$.filter(ce=>{var ze;const De=ce.title??"",Re=(((ze=ce.recentUserPrompts)==null?void 0:ze.map(Fe=>Fe.content))??[]).join(" ");return li(De,O)||li(Re,O)}):$,[$,O]),B=O.length>0,q=B&&I.length===0;E.useEffect(()=>{U(I.length>0?0:-1)},[I.length]),E.useEffect(()=>{var De;if(W<0)return;const ce=(De=H.current)==null?void 0:De.querySelector(`[data-sidx="${W}"]`);ce==null||ce.scrollIntoView({block:"nearest"})},[W]);const z=(ce,De)=>{De==null||De.stopPropagation(),c(ce)},ne=()=>{u&&(S(u),(C==null?void 0:C.id)===u&&r(`/p/${e}`),c(null))},re=(ce,De)=>{De==null||De.stopPropagation();const Re=w.find(Fe=>Fe.id===ce),ze=(Re==null?void 0:Re.title)??ce.slice(0,6);m(ze),h(ce)},Q=()=>{if(!d||p.trim()==="")return;const ce=Le.getState().renameSession;ce(d,p.trim()),h(null),m("")},K=()=>{y(!0)},P=()=>{v(e),r(`/p/${e}`),y(!1)},J=ce=>{if(!G.current)return;ce.target.closest('a[href*="/s/"]')&&(G.current=!1,n==null||n())},ie=()=>{var ce;M(""),(ce=R.current)==null||ce.focus()},he=ce=>{var De;switch(ce.key){case"Escape":M(""),(De=R.current)==null||De.blur();break;case"ArrowDown":ce.preventDefault(),U(Re=>Re<I.length-1?Re+1:Re);break;case"ArrowUp":ce.preventDefault(),U(Re=>Re>0?Re-1:0);break;case"Enter":{ce.preventDefault();const Re=I[W];Re&&(r(`/p/${e}/s/${Re.id}`),G.current&&(G.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 ce=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-4 border-b border-border flex gap-2",children:[i.jsx(Xn,{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(nc,{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(E1,{})})}),n&&i.jsx(rc,{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(Xi,{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:O,onChange:De=>M(De.target.value),onKeyDown:he,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"}),O&&i.jsx("button",{type:"button",onClick:ie,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"})})]}),B&&!q&&i.jsxs("div",{className:"mt-1 text-xs text-text-muted px-1",children:[I.length," ",I.length===1?"match":"matches"]})]}),L&&i.jsx(fB,{isOpen:a,onClose:()=>l(!1),project:L}),i.jsx(Ml,{isOpen:u!==null,onClose:()=>c(null),onConfirm:ne,title:"Delete session?",message:"This session will be permanently deleted.",confirmLabel:"Delete session",confirmVariant:"danger"}),i.jsx(Ml,{isOpen:x,onClose:()=>y(!1),onConfirm:P,title:"Delete all sessions?",message:"Delete all sessions in this project? This cannot be undone.",confirmLabel:"Delete all",confirmVariant:"danger"}),i.jsx(jt,{isOpen:d!==null,onClose:()=>{h(null),m("")},title:"Rename session",size:"sm",footer:i.jsx(Mk,{onCancel:()=>{h(null),m("")},onSave:Q,saving:!1,saveDisabled:p.trim()==="",saveLabel:"Rename"}),children:i.jsx("input",{type:"text",value:p,onChange:De=>m(De.target.value),onKeyDown:De=>{De.key==="Enter"&&Q()},onFocus:De=>De.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:I.length===0?i.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:B?"No matching sessions":"No sessions"}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"divide-y divide-border",ref:H,onClick:J,children:gB(I,C,_,z,re,e,T,D,O,W)}),N&&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(j){c("Failed to fix permissions: "+(j instanceof Error?j.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(jt,{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(rt,{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(rt,{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(rt,{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(rt,{type:"button",variant:"secondary",onClick:t,disabled:a,children:"Cancel"})})]}):null]})})}function Lk({isOpen:e,onClose:t}){const[,n]=Tn(),r=Gt(N=>N.listProjects),[a,l]=E.useState(""),[u,c]=E.useState(null),[d,h]=E.useState(!1),[p,m]=E.useState(""),[x,y]=E.useState(null),w=E.useRef(null);E.useEffect(()=>{e&&(ve("/api/config").then(N=>N.json()).then(N=>{N.workdir&&m(N.workdir)}),l(""),c(null),h(!1),y(null),setTimeout(()=>{var N;(N=w.current)==null||N.focus()},100))},[e]);const C=E.useCallback(async N=>{N.preventDefault();const T=nB(a);if(!T.valid){c(T.error);return}const D=`${p}/${a}`;await v(D)},[a,n,t,p]),_=E.useCallback(()=>{y(null)},[]),S=E.useCallback(async()=>{const N=`${p}/${a}`;await v(N)},[p,a,n,t,y,c,h]);async function v(N){h(!0),c(null),y(null);try{const T=await ve("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,workdir:N})});if(!T.ok){const O=await T.json().catch(()=>({}));if(O.code==="EACCES"){y(N),h(!1);return}throw new Error(O.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=E.useCallback(()=>{l(""),c(null),t()},[t]),j=a?`${p}/${a}`:"";return i.jsxs(i.Fragment,{children:[i.jsx(jt,{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(ui,{ref:w,id:"project-name",value:a,onChange:N=>{l(N.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:j})]}),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(rt,{type:"button",variant:"secondary",onClick:b,disabled:d,children:"Cancel"}),i.jsx(rt,{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(Xr,{className:"h-4 w-4"}),"Creating..."]}):"Create"})]})]})}),x&&i.jsx(Ak,{isOpen:!!x,onClose:_,path:x,onRetry:S})]})}function Dk(){const[e,t]=E.useState(null);return E.useEffect(()=>{ve("/api/config").then(n=>n.json()).then(n=>{n.workdir&&t(n.workdir)})},[]),e}function CS({projects:e,currentProject:t}){const[,n]=Tn(),r=Gt(_=>_.loadProject),a=Gt(_=>_.toggleStar),l=Gt(_=>_.createProject),u=Gt(_=>_.listProjects),[c,d]=E.useState(!1),[h,p]=E.useState(!1),m=Dk(),x=E.useCallback(async _=>{const S=z1(_),v=await l(S,_);return v&&"id"in v?(await u(),p(!1),n(`/p/${v.id}`),!0):!1},[l,u,n]),w=E.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(L1,{className:"w-3.5 h-3.5 text-yellow-500"}):i.jsx(D1,{className:"w-3.5 h-3.5 text-text-muted hover:text-yellow-500"})})]}),icon:_.id===(t==null?void 0:t.id)?i.jsx(Mr,{}):void 0,href:`/p/${_.id}`,closeOnClick:!0,onClick:()=>{r(_.id)}})),C=[{label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Rr,{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(Xr,{className:"w-4 h-4"}),i.jsx("span",{children:"New Project"})]}),onClick:()=>d(!0)}];return i.jsxs(i.Fragment,{children:[i.jsx(nc,{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(hn,{})]}),minWidth:"250px"}),c&&i.jsx(Lk,{isOpen:c,onClose:()=>d(!1)}),h&&i.jsx(Td,{initialPath:m??void 0,onSelect:x,onClose:()=>p(!1)})]})}function Rk(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 Xd(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}:${r}`}function rB(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=Xd(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 Ok(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 sB(e){const{year:t,month:n,day:r}=Ok(e);return`${t}-${n}-${r}`}function Ik(e){const t=new Map;for(const a of e){const l=sB(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 iB(e){const{year:t,month:n,day:r}=Ok(e);return`${t}/${n}/${r} ${Xd(e)}`}function pd(e,t){return e.length<=t?e:e.substring(0,t)+"..."}function aB({sessions:e,currentProject:t,currentSession:n,isOpen:r,onOpenChange:a}){var x;const l=Le(y=>y.loadSession),u=50,c=e.filter(y=>y.projectId===t.id).slice(0,15),d=Ik(c),h=E.useMemo(()=>{const y=[];y.push({label:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xr,{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:Rk(_.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:pd(S.title??S.id.slice(0,8),u)}),i.jsx("div",{className:"text-text-muted text-xs",children:Xd(S.updatedAt)})]}),icon:S.id===(n==null?void 0:n.id)?i.jsx(Mr,{}):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?pd(p,u):"No session selected";return i.jsx(nc,{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(hn,{})]}),minWidth:"280px"})}function oB({items:e,trigger:t,isActive:n=!1}){const[r,a]=E.useState(!1),l=E.useRef(null);return E.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(hn,{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===Xn?u.label:null;if(d){const h=d.props.href||"";return i.jsxs(Xn,{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 lB({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(Xn,{href:`/p/${e.id}/new`,className:"flex items-center gap-2",children:[i.jsx(Xr,{className:"w-3 h-3 text-accent-primary"}),i.jsx("span",{className:"text-sm",children:"New Session"})]})},...a.map(u=>({label:i.jsx(Xn,{href:`/p/${e.id}/s/${u.id}`,className:"flex items-center gap-2 truncate text-sm",children:i.jsx("span",{children:pd(u.title??u.id.slice(0,8),50)})}),icon:u.id===(n==null?void 0:n.id)?i.jsx(Mr,{className:"w-3 h-3"}):void 0})),{label:i.jsxs(Xn,{href:"/",className:"flex items-center gap-2 text-text-muted hover:text-text-primary",children:[i.jsx(rT,{className:"w-3 h-3"}),i.jsx("span",{className:"text-sm",children:"Projects"})]})}];return i.jsx(oB,{items:l,trigger:i.jsx("span",{className:"text-sm text-text-secondary font-medium",children:e.name})})}function cB({onMenuClick:e,onCriteriaToggle:t}){const[n,r]=E.useState(!1),[a,l]=E.useState(!1),[u,c]=E.useState(!!document.fullscreenElement),[d,h]=Tn();E.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=Le(D=>D.currentSession),y=Le(D=>D.sessions),w=Gt(D=>D.currentProject),C=Gt(D=>D.projects),_=Xt(D=>D.startAutoRefresh),S=Xt(D=>D.stopAutoRefresh),v=Lr(D=>D.setOpen),b=Lr(D=>D.isOpen),j=Cs(D=>D.status==="available"),N=Cs(D=>D.check);E.useEffect(()=>{Cs.getState().status==="idle"&&N()},[N]),E.useEffect(()=>{const D=()=>l(!0);return window.addEventListener("open-session-dropdown",D),()=>window.removeEventListener("open-session-dropdown",D)},[]);const T=Kl();return Ol(T.terminalToggle,()=>{Lr.getState().toggleOpen()},{capture:!0}),E.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 (${Xu(T.sessionSearch)})`:"Toggle session list",children:i.jsx(A_,{})}),i.jsx(Xn,{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(CS,{projects:C,currentProject:w})}),i.jsx("span",{className:"md:hidden",children:i.jsx(lB,{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(aB,{sessions:y,currentProject:w,currentSession:x,isOpen:a,onOpenChange:l})})]}),!w&&i.jsx("span",{className:"hidden md:inline",children:i.jsx(CS,{projects:C})})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[m&&i.jsx("button",{onClick:()=>{var D,L,O;document.fullscreenElement?(D=document.exitFullscreen)==null||D.call(document):(O=(L=document.documentElement).requestFullscreen)==null||O.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(aT,{}):i.jsx(oT,{})}),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(mT,{})}),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:j?"Settings — update available":"Settings",children:[i.jsx(dT,{}),j&&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(cT,{})}),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 (${Xu(T.criteriaSidebar)})`:"Toggle criteria sidebar",children:i.jsx(A_,{})})]}),i.jsx(q6,{isOpen:n,onClose:()=>r(!1)}),i.jsx(tB,{isOpen:b,onClose:()=>v(!1)})]})}function Mk({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(rt,{variant:"secondary",onClick:e,children:a}),i.jsx(rt,{variant:"primary",onClick:t,disabled:r??n,children:l})]})}const Ru=In()(e=>({config:null,loading:!1,fetchConfig:async t=>{e({loading:!0});try{const r=await(await ve(`/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 ve(`/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})}})),uB=["/","/etc","/bin","/sbin","/lib","/lib64","/usr","/var","/opt","/root","/run","/tmp","/home","/mnt","/media"],dB=["/proc/","/sys/","/dev/","/boot/","/etc/","/lost+found/"];function hB(e,t=uB,n=dB){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 fB({isOpen:e,onClose:t,project:n}){const r=Gt(te=>te.updateProject),a=Ru(te=>te.config),l=Ru(te=>te.loading),u=Ru(te=>te.fetchConfig),c=Ru(te=>te.saveConfig),d=()=>{try{Dt.send("context.checkDynamic",{})}catch{}t()},[h,p]=E.useState(n.customInstructions??""),[m,x]=E.useState(n.dangerLevel??""),[y,w]=E.useState(!1),[C,_]=E.useState(!1),[S,v]=E.useState(!1),[b,j]=E.useState(null),[N,T]=E.useState(""),[D,L]=E.useState(!1),[O,M]=E.useState(""),[W,U]=E.useState(!1),[R,H]=E.useState(""),[G,V]=E.useState(!1),[Z,X]=E.useState(!1),[$,I]=E.useState([]),[B,q]=E.useState(""),[z,ne]=E.useState({}),[re,Q]=E.useState(!1),[K,P]=E.useState(new Set),J=y||C||D||W||re;E.useEffect(()=>{e&&(p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),U(!1),Q(!1),P(new Set),u(n.workdir))},[e,n,u]),E.useEffect(()=>{a!=null&&a.setup&&a.setup.length>0?T(a.setup.join(" && ")):T(""),M((a==null?void 0:a.rootDir)??""),ne((a==null?void 0:a.mcpOverrides)??{})},[a]);const ie=Dl(te=>te.servers),he=te=>z[te]??{},ce=te=>{var me;const ae=he(te);if(ae.disabled!==void 0)return ae.disabled;const se=ie.find(Ue=>Ue.name===te);return!!((me=se==null?void 0:se.config)!=null&&me.disabled)},De=(te,ae)=>{var me;return((me=he(te).disabledTools)==null?void 0:me.includes(ae))??!1},Re=te=>{ne(ae=>({...ae,[te]:{...ae[te],disabled:!ce(te)}})),Q(!0)},ze=(te,ae)=>{ne(se=>{const me=se[te]??{},Ue=me.disabledTools??[],He=Ue.includes(ae)?Ue.filter(Ye=>Ye!==ae):[...Ue,ae];return{...se,[te]:{...me,disabledTools:He.length>0?He:void 0}}}),Q(!0)},Fe=te=>{P(ae=>{if(ae.has(te)){const me=new Set(ae);return me.delete(te),me}const se=new Set(ae);return se.add(te),se})},Ee=te=>{p(te.target.value),w(!0)},st=te=>{x(te),_(!0)},ot=te=>{T(te.target.value),L(!0)},je=te=>{M(te.target.value),U(!0)},Me=E.useCallback(async()=>{const te=m===""?null:m;await r(n.id,{customInstructions:h||null,dangerLevel:te});const ae=N.trim()?N.split("&&").map(se=>se.trim()).filter(Boolean):[];await c(n.workdir,{...ae.length>0?{setup:ae}:{},rootDir:O.trim(),...Object.keys(z).length>0?{mcpOverrides:z}:{mcpOverrides:void 0}}),w(!1),_(!1),L(!1),U(!1),Q(!1),d()},[n.id,m,h,N,O,z,r,c,n.workdir,d]),lt=async()=>{const te=O.trim(),ae=(a==null?void 0:a.rootDir)??"";if(te){const se=hB(te);if(se==="exact"){const me=te.replace(/\/+$/,"")||"/";j(`Cannot use "${me}" directly as workspace root. Use a subdirectory like "${me}/${n.name}" instead.`);return}if(se==="virtual_fs"){j(`Cannot use paths under "${te}" for workspaces.`);return}}if(!W||!te||te===ae){v(!0),j(null);try{await Me()}catch(se){j(se instanceof Error?se.message:"Failed to save settings")}finally{v(!1)}return}H(te),v(!0),j(null);try{const se=await ve(`/api/workspace/config/validate?workdir=${encodeURIComponent(n.workdir)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rootDir:te,workdir:n.workdir,projectName:n.name})});if(!se.ok){const Ue=await se.json().catch(()=>({}));j((Ue==null?void 0:Ue.error)??"Failed to validate workspace root directory"),v(!1);return}const me=await se.json();if(!me.exists){q(me.resolvedPath),v(!1),V(!0);return}if(me.workspaces&&me.workspaces.length>0){I(me.workspaces),v(!1),X(!0);return}j(null),await Me()}catch(se){j(se instanceof Error?se.message:"Failed to validate settings"),v(!1)}},we=async()=>{V(!1),v(!0);try{const te=await ve(`/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(!te.ok){const se=await te.json().catch(()=>({}));j((se==null?void 0:se.error)??"Failed to create directory"),v(!1);return}const ae=await te.json();if(ae.workspaces&&ae.workspaces.length>0){I(ae.workspaces),X(!0),v(!1);return}await Me()}catch(te){j(te instanceof Error?te.message:"Failed to create directory")}finally{v(!1)}},Ie=async()=>{X(!1),v(!0),j(null);try{await Me()}catch(te){j(te instanceof Error?te.message:"Failed to save settings")}finally{v(!1)}},qe=()=>{V(!1),X(!1),p(n.customInstructions??""),x(n.dangerLevel??""),w(!1),_(!1),L(!1),U(!1),d()};return i.jsxs(jt,{isOpen:e,onClose:qe,title:`${n.name} Settings`,size:"lg",footer:i.jsx(Mk,{onCancel:qe,onSave:lt,saving:S,saveDisabled:!J||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:()=>st(""),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:()=>st("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:()=>st("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:Ee,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:N,onChange:ot,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:O,onChange:je,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})]}),ie.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:ie.map(te=>{const ae=ce(te.name);return i.jsx(jk,{server:te,expanded:K.has(te.name),onToggleExpand:Fe,serverToggleEnabled:!ae,onServerToggle:()=>Re(te.name),tools:te.tools.map(se=>({...se,enabled:!De(te.name,se.name)})),onToolToggle:se=>ze(te.name,se),statusDot:Kg(ae?"disabled":te.status),statusColor:qg(ae?"disabled":te.status)},te.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})]}),G&&i.jsxs(jt,{isOpen:G,onClose:()=>V(!1),title:"Directory not found",size:"md",footer:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{type:"button",onClick:()=>V(!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:we,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:B})," does not exist."]}),i.jsx("p",{className:"text-sm text-text-muted mt-2",children:"Would you like to create it?"})]}),Z&&i.jsxs(jt,{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:Ie,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(te=>i.jsx("li",{className:"text-sm font-mono text-text-muted",children:te.name},te.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 mB={sm:"w-3 h-3",md:"w-4 h-4",lg:"w-5 h-5",xl:"w-6 h-6"},pB="M6 18L18 6M6 6l12 12";function rc({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(Ed,{onClick:e,icon:pB,iconSize:mB[n],className:`${a} ${t}`,title:"Close"})}function qr(e,t){const n=new Set(t.map(r=>r.id));return[...e.filter(r=>!n.has(r.id)),...t]}function Jp(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 li(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 Pk(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 Bk({projectId:e,isOpen:t=!0,onClose:n}){const[,r]=Tn(),[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(null),[p,m]=E.useState(""),[x,y]=E.useState(!1),w=Le(ce=>ce.sessions),C=Le(ce=>ce.currentSession),_=Le(ce=>ce.unreadSessionIds),S=Le(ce=>ce.deleteSession),v=Le(ce=>ce.deleteAllSessions),b=Le(ce=>ce.loadMoreSessions),j=Le(ce=>ce.sessionsHasMore),N=Le(ce=>ce.sessionsPaginationLoading),T=Le(ce=>ce.sessionsWithPendingConfirmations),D=Le(ce=>ce.pendingPathConfirmations),L=Gt(ce=>ce.currentProject),[O,M]=E.useState(""),[W,U]=E.useState(-1),R=E.useRef(null),H=E.useRef(null),G=E.useRef(!1),V=Kl();Ol(V.sessionSearch,()=>{var ce;if(t&&document.activeElement===R.current){n==null||n();return}t||(G.current=!0,n==null||n()),(ce=R.current)==null||ce.focus()});const Z=E.useRef(null),X=E.useCallback(()=>{j&&!N&&L&&b(L.id)},[j,N,L,b]);E.useEffect(()=>{if(!Z.current||!j)return;const ce=new IntersectionObserver(De=>{const Re=De[0];Re&&Re.isIntersecting&&X()},{threshold:.1});return ce.observe(Z.current),()=>ce.disconnect()},[j,X]);const $=w.filter(ce=>ce.projectId===(L==null?void 0:L.id)),I=E.useMemo(()=>O?$.filter(ce=>{var ze;const De=ce.title??"",Re=(((ze=ce.recentUserPrompts)==null?void 0:ze.map(Fe=>Fe.content))??[]).join(" ");return li(De,O)||li(Re,O)}):$,[$,O]),B=O.length>0,q=B&&I.length===0;E.useEffect(()=>{U(I.length>0?0:-1)},[I.length]),E.useEffect(()=>{var De;if(W<0)return;const ce=(De=H.current)==null?void 0:De.querySelector(`[data-sidx="${W}"]`);ce==null||ce.scrollIntoView({block:"nearest"})},[W]);const z=(ce,De)=>{De==null||De.stopPropagation(),c(ce)},ne=()=>{u&&(S(u),(C==null?void 0:C.id)===u&&r(`/p/${e}`),c(null))},re=(ce,De)=>{De==null||De.stopPropagation();const Re=w.find(Fe=>Fe.id===ce),ze=(Re==null?void 0:Re.title)??ce.slice(0,6);m(ze),h(ce)},Q=()=>{if(!d||p.trim()==="")return;const ce=Le.getState().renameSession;ce(d,p.trim()),h(null),m("")},K=()=>{y(!0)},P=()=>{v(e),r(`/p/${e}`),y(!1)},J=ce=>{if(!G.current)return;ce.target.closest('a[href*="/s/"]')&&(G.current=!1,n==null||n())},ie=()=>{var ce;M(""),(ce=R.current)==null||ce.focus()},he=ce=>{var De;switch(ce.key){case"Escape":M(""),(De=R.current)==null||De.blur();break;case"ArrowDown":ce.preventDefault(),U(Re=>Re<I.length-1?Re+1:Re);break;case"ArrowUp":ce.preventDefault(),U(Re=>Re>0?Re-1:0);break;case"Enter":{ce.preventDefault();const Re=I[W];Re&&(r(`/p/${e}/s/${Re.id}`),G.current&&(G.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 ce=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-4 border-b border-border flex gap-2",children:[i.jsx(Xn,{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(nc,{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(E1,{})})}),n&&i.jsx(rc,{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(Xi,{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:O,onChange:De=>M(De.target.value),onKeyDown:he,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"}),O&&i.jsx("button",{type:"button",onClick:ie,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"})})]}),B&&!q&&i.jsxs("div",{className:"mt-1 text-xs text-text-muted px-1",children:[I.length," ",I.length===1?"match":"matches"]})]}),L&&i.jsx(fB,{isOpen:a,onClose:()=>l(!1),project:L}),i.jsx(Ml,{isOpen:u!==null,onClose:()=>c(null),onConfirm:ne,title:"Delete session?",message:"This session will be permanently deleted.",confirmLabel:"Delete session",confirmVariant:"danger"}),i.jsx(Ml,{isOpen:x,onClose:()=>y(!1),onConfirm:P,title:"Delete all sessions?",message:"Delete all sessions in this project? This cannot be undone.",confirmLabel:"Delete all",confirmVariant:"danger"}),i.jsx(jt,{isOpen:d!==null,onClose:()=>{h(null),m("")},title:"Rename session",size:"sm",footer:i.jsx(Mk,{onCancel:()=>{h(null),m("")},onSave:Q,saving:!1,saveDisabled:p.trim()==="",saveLabel:"Rename"}),children:i.jsx("input",{type:"text",value:p,onChange:De=>m(De.target.value),onKeyDown:De=>{De.key==="Enter"&&Q()},onFocus:De=>De.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:I.length===0?i.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:B?"No matching sessions":"No sessions"}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"divide-y divide-border",ref:H,onClick:J,children:gB(I,C,_,z,re,e,T,D,O,W)}),N&&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,23 +281,23 @@ 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:ce})})()]})}function gB(e,t,n,r,a,l,u,c,d,h){const p=Ik(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:Rk(w.updatedAt)}),y.map(C=>{const _=m++,S=(t==null?void 0:t.id)===C.id,v=_===h,b=n.includes(C.id),j=C.isRunning,N=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(Xn,{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?Jp(C.title??C.id.slice(0,6),d):C.title??C.id.slice(0,6)}),i.jsx(nc,{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(E1,{})})})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[N?i.jsx("span",{title:"Awaiting confirmation",children:i.jsx(og,{className:"w-3 h-3 text-red-400 flex-shrink-0"})}):j?i.jsx(hT,{}):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:Xd(C.updatedAt)}),i.jsxs("span",{className:"text-text-muted text-xs flex-shrink-0",children:[C.messageCount," messages"]})]})]})},C.id)})]},x):null})}const kS=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧"];function xB(){var u;const e=Gt(c=>c.currentProject),t=Le(c=>c.currentSession),n=kd(),r=E.useRef(0),a=E.useRef(null);E.useEffect(()=>(n?(a.current||(r.current=0),a.current=window.setInterval(()=>{r.current=(r.current+1)%kS.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?`${kS[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 $k({isOpen:e,onClose:t,projectName:n,onConfirm:r}){const a=()=>{r(),t()};return i.jsx(Ml,{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 yB({isOpen:e,onClose:t}){const[,n]=Tn(),[r,a]=E.useState(!1),l=Dk(),[u,c]=E.useState(!1),d=Gt(L=>L.projects),h=Gt(L=>L.createProject),p=Gt(L=>L.listProjects),m=Gt(L=>L.deleteProject),[x,y]=E.useState(null),[w,C]=E.useState(null);E.useEffect(()=>{e&&p()},[e,p]);const _=L=>{n(`/p/${L}`),t()},S=(L,O)=>{O.stopPropagation(),y(L)},v=()=>{x&&(m(x.id),y(null))},b=async L=>N(L);function j(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 N(L){const O=z1(L),M=await h(O,L);return p(),j(M)?(C(M.error.path||L),!1):M&&"id"in M?(n(`/p/${M.id}`),t(),!0):!1}const T=E.useCallback(()=>{C(null)},[]),D=E.useCallback(async()=>{const L=w;C(null),L&&await N(L)},[w]);return e?i.jsxs(jt,{isOpen:e,onClose:t,title:"Open Project",size:"xl",footer:i.jsx("div",{className:"flex justify-end gap-2",children:i.jsx(rt,{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(Rr,{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:H1(L.workdir,32)})]})]}),i.jsx("button",{onClick:O=>S(L,O),className:"text-accent-error/70 hover:text-accent-error p-1",title:"Delete project",children:i.jsx(ea,{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(rt,{variant:"primary",onClick:()=>c(!0),children:"Select existing project"}),i.jsx(rt,{variant:"secondary",onClick:()=>a(!0),"data-testid":"open-project-create-button",children:"Create new project"})]})})]}),r&&i.jsx(Lk,{isOpen:r,onClose:()=>a(!1)}),x&&i.jsx($k,{isOpen:!0,onClose:()=>y(null),projectName:x.name,onConfirm:v}),u&&i.jsx(Td,{initialPath:l??void 0,onSelect:L=>{b(L)},onClose:()=>c(!1)}),w&&i.jsx(Ak,{isOpen:!0,onClose:T,path:w,onRetry:D})]}):null}function bB(){const[e,t]=E.useState(!1),[n,r]=E.useState(null),[a,l]=E.useState(""),[u,c]=E.useState(""),d=E.useRef(null),h=Le(H=>H.sessions),p=Gt(H=>H.projects),m=Gt(H=>H.loading),x=Gt(H=>H.listProjects),y=Le(H=>H.listSessions),w=Gt(H=>H.deleteProject),C=Le(H=>H.connectionStatus);E.useEffect(()=>{C==="connected"&&(x(),y())},[C,x,y]),E.useEffect(()=>{const H=setTimeout(()=>c(a),150);return()=>clearTimeout(H)},[a]);const{matchCount:_,filteredSessionIds:S,relevanceScores:v,matchTypes:b,promptSnippets:j}=E.useMemo(()=>{if(!u)return{matchCount:0,filteredSessionIds:null,relevanceScores:null,matchTypes:null,promptSnippets:null};const H=new Map(p.map($=>[$.id,$])),G=new Map,V=new Map,Z=new Map,X=h.filter($=>{var K;const I=H.get($.projectId),B=(I==null?void 0:I.name)??"",q=$.title??"",z=((K=$.recentUserPrompts)==null?void 0:K.map(P=>P.content))??[],ne=z.join(" ");let re=0,Q="";if(li(q,u)&&(re+=10,Q="title"),li(ne,u)){re+=3,Q=Q==="title"?"title":"prompts";const P=z.find(J=>li(J,u));if(P){const J=P.toLowerCase().indexOf(u.toLowerCase());if(J>=0){const ie=Math.max(0,J-30),he=Math.min(P.length,J+u.length+30);Z.set($.id,(ie>0?"…":"")+P.slice(ie,he)+(he<P.length?"…":""))}else Z.set($.id,P.slice(0,80)+(P.length>80?"…":""))}}return li(B,u)&&(re+=1,Q=Q||"project"),G.set($.id,re),V.set($.id,Q),re>0});return{matchCount:X.length,filteredSessionIds:new Set(X.map($=>$.id)),relevanceScores:G,matchTypes:V,promptSnippets:Z}},[h,u,p]),N=E.useMemo(()=>{const H=new Map;for(const G of h){const V=new Date(G.updatedAt).getTime(),Z=H.get(G.projectId)??0;V>Z&&H.set(G.projectId,V)}return H},[h]),T=E.useMemo(()=>{const H=new Map;for(const G of h){const V=H.get(G.projectId);V?V.push(G):H.set(G.projectId,[G])}for(const[,G]of H)G.sort((V,Z)=>new Date(Z.updatedAt).getTime()-new Date(V.updatedAt).getTime());return H},[h]),D=E.useMemo(()=>{let H=p;return u&&S&&(H=p.filter(G=>{const V=T.get(G.id);return V==null?void 0:V.some(Z=>S.has(Z.id))})),[...H].sort((G,V)=>{const Z=N.get(G.id)??new Date(G.updatedAt).getTime();return(N.get(V.id)??new Date(V.updatedAt).getTime())-Z})},[p,T,u,S,N]),L=E.useCallback(H=>{const G=T.get(H);return G?u&&S&&v?G.filter(V=>S.has(V.id)).sort((V,Z)=>{const X=(v.get(Z.id)??0)-(v.get(V.id)??0);return X!==0?X:new Date(Z.updatedAt).getTime()-new Date(V.updatedAt).getTime()}):G.slice(0,5):[]},[T,u,S,v]),O=()=>{t(!0)},M=()=>{var H;l(""),c(""),(H=d.current)==null||H.focus()},W=H=>{var G;H.key==="Escape"&&(M(),(G=d.current)==null||G.blur())},U=u.length>0,R=U&&_===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(rt,{variant:"primary",onClick:O,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(Xi,{className:"absolute left-3 w-4 h-4 text-text-muted pointer-events-none"}),i.jsx("input",{ref:d,type:"text",value:a,onChange:H=>l(H.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:M,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"})})]}),U&&!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(Xi,{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(H=>{const G=L(H.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(Xn,{href:`/p/${H.id}`,className:"flex items-center gap-2 cursor-pointer hover:opacity-80 transition-opacity flex-1",children:[i.jsx(Rr,{className:"w-5 h-5 text-accent-primary flex-shrink-0"}),i.jsx("span",{className:"text-text-primary font-semibold",children:H.name})]}),i.jsx(Xn,{href:`/p/${H.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:H.id,name:H.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(ea,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"divide-y divide-border",children:G.length>0?G.map(V=>{const Z=p.find(B=>V.projectId===B.id),X=Z?`/p/${Z.id}/s/${V.id}`:"#",$=V.title??V.id.slice(0,8),I=b==null?void 0:b.get(V.id);return i.jsx(Xn,{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:U&&I==="title"?Jp($,u):$}),U&&I&&I!=="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:I==="prompts"?"prompts":"project"}),I==="prompts"&&(j==null?void 0:j.get(V.id))&&i.jsx("span",{className:"text-[11px] text-text-muted truncate max-w-[250px]",children:Jp(j.get(V.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:rB(V.updatedAt)}),i.jsxs("span",{className:"text-text-muted text-xs",children:[V.messageCount," msgs"]})]})]})},V.id)}):i.jsx("div",{className:"p-3 md:p-4 text-text-muted text-sm",children:"No sessions yet"})})]})},H.id)}),!U&&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(pi,{})})]}),e&&i.jsx(yB,{isOpen:e,onClose:()=>t(!1)}),n&&i.jsx($k,{isOpen:!0,onClose:()=>r(null),projectName:n.name,onConfirm:()=>w(n.id)})]})}function vB(){const[,e]=uo("/p/:projectId/new"),[,t]=Tn(),n=e==null?void 0:e.projectId,r=Le(u=>u.createSession),a=Le(u=>u.resetPendingSessionCreate),l=E.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 E.useEffect(()=>{l()},[l]),i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx(pi,{})})}function _B(){const e=Gt(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(Xn,{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 yl=e=>Math.round(e*10)/10;function SB(e){return typeof e.totalTime=="number"&&!Number.isNaN(e.totalTime)}function Zp(e){return{providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model}}function wB(e){return`${e.providerId}::${e.model}`}function CB(e){return`${e.providerName} > ${e.model}`}function jS(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=Zp(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?yl(r/l):0,m=u>0?yl(a/u):0;return{totalTime:yl(t),aiTime:yl(t-n),toolTime:yl(n),prefillTokens:r,generationTokens:a,avgPrefillSpeed:p,avgGenerationSpeed:m,responseCount:e.length,llmCallCount:d.length,dataPoints:c,callDataPoints:d}}function kB(e){const t=e.filter(a=>a.stats!==void 0&&a.stats!==null&&SB(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=wB(Zp(a.stats)),u=n.get(l)??[];n.set(l,[...u,a])}const r=Array.from(n.entries()).map(([a,l])=>{const u=Zp(l[0].stats),c=jS(l);return{...u,key:a,label:CB(u),...c}});return{...jS(t),modelGroups:r}}function jB(e){return E.useMemo(()=>kB(e),[e])}function Yg(){var a;const e=Le(l=>l.gitStatus),t=Le(l=>l.currentSession),[n,r]=E.useState(!0);return E.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 oo(e){return e.toLocaleString("en-US").replace(/,/g," ")}function ES(e){return Number.isFinite(e)?e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1):"0"}function Yr(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 NS=Object.assign(Object.create(null),{criteria:"Acceptance Criteria",review_findings:"Review Findings",todos:"Tasks"}),TS=Object.assign(Object.create(null),{criteria:"criteria",review_findings:"review findings",todos:"tasks"});function so(e){return Object.hasOwn(NS,e)?NS[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function EB(e){return Object.hasOwn(TS,e)?TS[e]:e.replace(/_/g," ")}const AS=["▁","▂","▃","▄","▅","▆","▇","█"];function NB(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 TB(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 AB(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}=TB(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]=AS[NB(w,c,d)]??AS[0]}return{blocks:p.join(""),minX:r,maxX:a,minY:h,maxY:d}}function LS(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function DS({data:e,width:t=60,height:n=78,label:r,xLabel:a,yLabel:l,showAxes:u=!0,formatY:c=LS,formatX:d=LS}){const h=E.useMemo(()=>{const p=AB(e,t),m=Math.max(t*6,240),x=10,y=8,C=[...e].sort((b,j)=>b.x-j.x).map(b=>{const j=p.maxX===p.minX?m/2:x+(b.x-p.minX)/(p.maxX-p.minX)*(m-x*2),N=p.maxY===p.minY?n/2:y+(p.maxY-b.y)/(p.maxY-p.minY)*(n-y*2);return{...b,cx:j,cy:N,leftPercent:j/m*100,topPercent:N/n*100}}),_=C.map((b,j)=>`${j===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 LB({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(DS,{data:l,width:a,label:t,xLabel:r}),i.jsx(DS,{data:u,width:a,label:n,xLabel:r})]})}function DB(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 RB(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 OB(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 IB(e){return e.callDataPoints.length>0?OB(e):RB(e)}function Yi(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function Cl(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function MB(e){if(e.length===0)return"0 ctx";const t=Math.min(...e),n=Math.max(...e);return t===n?`${Yi(t)} ctx`:`${Yi(t)}-${Yi(n)} ctx`}function gd(e){return`${Cl(e)} t/s`}function zk(e){try{return new Date(e).toLocaleTimeString("en-US",{hour12:!1})}catch{return e}}function PB(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 BB({isOpen:e,onClose:t,stats:n}){const r=E.useRef(null),[a,l]=E.useState({}),[u,c]=E.useState(()=>{var w;return((w=n.modelGroups[0])==null?void 0:w.key)??""});E.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=E.useMemo(()=>n.modelGroups.find(w=>w.key===u)??n.modelGroups[0],[u,n.modelGroups]),h=E.useMemo(()=>d?DB(d):[],[d]),p=E.useMemo(()=>d?IB(d):{mode:"responses",xLabel:"response",prefillLabel:"",generationLabel:"",points:[]},[d]),m=E.useCallback(w=>{l(C=>({...C,[w]:!C[w]}))},[]),x=E.useCallback(()=>{if(!d)return;const w=PB(d);navigator.clipboard.writeText(JSON.stringify(w,null,2)).catch(C=>console.error("Failed to copy:",C))},[d]),y=E.useCallback(async()=>{if(r.current)try{const w=(await ee(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(jt,{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:Yr(d.aiTime)}),i.jsx(ys,{label:"Total Time",value:Yr(d.totalTime)}),i.jsx(ys,{label:"Tool Time",value:Yr(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:Yi(d.prefillTokens),subValue:`@ ${Cl(d.avgPrefillSpeed)} tok/s`}),i.jsx(ys,{label:"Gen Tokens",value:Yi(d.generationTokens),subValue:`@ ${Cl(d.avgGenerationSpeed)} tok/s`}),i.jsx(ys,{label:"Avg PP Speed",value:`${Cl(d.avgPrefillSpeed)}`,subValue:"tok/s"}),i.jsx(ys,{label:"Avg TG Speed",value:`${Cl(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(LB,{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(E.Fragment,{children:[i.jsx($B,{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(zB,{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 $B({row:e,index:t,isExpanded:n,onToggle:r}){const a=e.calls.length>0?MB(e.calls.map(l=>l.promptTokens)):`${Yi(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:zk(e.timestamp)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:Yr(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:gd(e.prefillSpeed)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:gd(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 zB({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:zk(e.timestamp)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:Yr(e.totalTime)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Yi(e.promptTokens)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:gd(e.prefillSpeed)}),i.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:gd(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 HB={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"}},Hk=["open","in_progress","pending","completed","resolved","dismissed","passed","failed"];function UB(e){return HB[e]??{icon:"○",color:"text-text-muted"}}function Xg(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}const xo=E.memo(function({status:t,className:n="text-xs leading-tight flex-shrink-0"}){const{icon:r,color:a}=UB(t);return i.jsx("span",{className:`${a} ${n}`,children:r})});function xd({entries:e,title:t}){const n=E.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:Hk.map(r=>{const a=n[r];return a?i.jsxs("span",{className:"flex items-center gap-0.5",children:[i.jsx(xo,{status:r}),i.jsx("span",{children:a})]},r):null})})]})}const Uk=E.memo(function({entries:t,title:n,onClearAll:r}){const[a,l]=E.useState(!1),u=E.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(xo,{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,"]"]})," ",Xg(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(ea,{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"})]})]})})]})]})}),FB={criteria:["pending","completed","passed","failed"],todos:["pending","in_progress","completed"],review_findings:["open","resolved","dismissed"]},VB=["pending","completed","failed","dismissed"];function GB(e){return FB[e]??VB}function WB(e,t){const n=t.indexOf(e);return n===-1?t[0]??"pending":t[(n+1)%t.length]??"pending"}function Fk({entries:e,sessionId:t,metadataKey:n,title:r,isOpen:a,onClose:l}){const[u,c]=E.useState(e),[d,h]=E.useState(null),[p,m]=E.useState(""),[x,y]=E.useState(!1),[w,C]=E.useState(""),_=E.useRef(null),S=E.useRef(null),v=E.useCallback(()=>{const U=S.current;U&&(U.style.height="auto",U.style.height=U.scrollHeight+"px")},[]);E.useEffect(()=>{c(e)},[e]),E.useEffect(()=>{var U;d&&(v(),(U=S.current)==null||U.focus())},[d,v]),E.useEffect(()=>{var U;x&&((U=_.current)==null||U.focus())},[x]);const b=E.useCallback(U=>{c(U),ve(`/api/sessions/${t}/metadata/${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:U})}).catch(R=>console.error(`Failed to sync ${n}:`,R))},[t,n]),j=E.useCallback(U=>{const R=GB(n),H=u.map(G=>G.id===U?{...G,status:WB(G.status,R)}:G);b(H)},[u,n,b]),N=E.useCallback((U,R)=>{h(U),m(R)},[]),T=E.useCallback((U,R,H)=>{var Z;const G=(R.trim()||((Z=H.find(X=>X.id===U))==null?void 0:Z.description))??"",V=H.map(X=>X.id===U?{...X,description:G}:X);b(V)},[b]),D=E.useCallback(()=>{d&&(T(d,p,u),h(null))},[d,p,u,T]),L=E.useCallback(U=>{U.key==="Enter"&&D(),U.key==="Escape"&&(U.stopPropagation(),h(null))},[D]),O=E.useCallback(U=>{b(u.filter(R=>R.id!==U))},[u,b]),M=E.useCallback(()=>{const U=w.trim();if(!U)return;const R=u.map(G=>Number(G.id)).filter(G=>Number.isInteger(G)&&G>=0),H=String(Math.max(-1,...R)+1);b([...u,{id:H,description:U,status:"pending"}]),C("")},[w,u,b]),W=E.useCallback(U=>{U.key==="Enter"&&(U.preventDefault(),M()),U.key==="Escape"&&(y(!1),C(""))},[M]);return i.jsxs(jt,{isOpen:a,onClose:l,title:r,size:"full",showCloseButton:!0,closeOnEscape:!0,children:[i.jsxs("ul",{className:"space-y-1",children:[u.map((U,R)=>{const H=d===U.id,G=i.jsxs("button",{onClick:()=>N(U.id,U.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:["[",U.id,"]"]})," ",i.jsx("span",{children:Xg(U.description)})]}),V=H?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}):G;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:()=>j(U.id),className:"flex-shrink-0 cursor-pointer hover:opacity-70 transition-opacity mt-0.5",title:"Click to cycle status",children:i.jsx(xo,{status:U.status})}),i.jsx("div",{className:"flex-1 min-w-0",children:V}),i.jsx("button",{onClick:()=>O(U.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"})})})]},U.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:U=>C(U.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:M,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(Xr,{className:"w-4 h-4"}),"Add"]})]})})]})}const vt=In((e,t)=>({defaults:[],userItems:[],projectItems:[],activeWorkflowId:"default",loading:!1,templateVariables:[],fetchTemplateVariables:async()=>{try{const r=await(await ve("/api/workflows/template-variables")).json();e({templateVariables:r.variables??[]})}catch{}},fetchWorkflows:async()=>{e({loading:!0});try{const r=await(await ve("/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 ve(`/api/workflows/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/workflows/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createWorkflow:async(n,r)=>{const a=await fi("POST","/api/workflows",{...n,destination:r});return a.success&&await t().fetchWorkflows(),a},updateWorkflow:async(n,r)=>{const a=await fi("PUT",`/api/workflows/${n}`,r);return a.success&&await t().fetchWorkflows(),a},deleteWorkflow:async n=>{try{const r=await ve(`/api/workflows/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n),projectItems:l.projectItems.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)=>Cd(`/api/workflows/${n}/duplicate`,()=>t().fetchWorkflows(),r)})),qB={pending:"completed",completed:"passed",passed:"failed",failed:"pending"};async function KB(e,t){await ve(`/api/sessions/${e}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:t})})}function Ou({id:e,agents:t}){const n=Vl(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 YB({id:e}){const t=vt(u=>u.defaults),n=vt(u=>u.userItems),a=E.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 Vk({entries:e,sessionId:t}){const[n,r]=E.useState(e),[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(""),[p,m]=E.useState(""),[x,y]=E.useState(!1),[w,C]=E.useState(!1),_=xt(X=>X.defaults),S=xt(X=>X.userItems),v=xt(X=>X.projectItems),b=E.useMemo(()=>[..._,...S,...v],[_,S,v]),j=E.useRef(null),N=E.useRef(null);E.useEffect(()=>{r(e)},[e]),E.useEffect(()=>{var X;a&&((X=j.current)==null||X.focus())},[a]),E.useEffect(()=>{var X;u&&((X=N.current)==null||X.focus())},[u]);const T=E.useCallback(X=>{r(X),KB(t,X)},[t]),D=E.useCallback(X=>{var z;const $=X.map(ne=>ne.trim()).filter(Boolean);if($.length===0)return;const I=n.map(ne=>Number(ne.id)).filter(ne=>Number.isInteger(ne)&&ne>=0),B=Math.max(-1,...I)+1,q=$.map((ne,re)=>({id:String(B+re),description:ne,status:"pending"}));T([...n,...q]),h(""),(z=j.current)==null||z.focus()},[n,T]),L=E.useCallback(()=>{D([d])},[D,d]),O=E.useCallback(X=>{const $=X.clipboardData.getData("text/plain").split(/\r\n|\r|\n/);$.length<2||(X.preventDefault(),D($))},[D]),M=E.useCallback(()=>{l(!1),h("")},[]),W=E.useCallback((X,$)=>{c(X),m($)},[]),U=E.useCallback(()=>{if(!u)return;const X=p.trim(),$=n.map(I=>I.id===u?{...I,description:X||I.description}:I);T($),c(null)},[u,p,n,T]),R=E.useCallback(X=>{const $=n.map(I=>I.id===X?{...I,status:qB[I.status]??"pending"}:I);T($)},[n,T]),H=E.useCallback(X=>{T(n.filter($=>$.id!==X))},[n,T]),G=E.useCallback(()=>{T([]),y(!1)},[T]),V=E.useCallback(X=>{X.key==="Enter"&&(X.preventDefault(),L()),X.key==="Escape"&&M()},[L,M]),Z=E.useCallback(X=>{X.key==="Enter"&&U(),X.key==="Escape"&&c(null)},[U]);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 I=X.status,B=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(xo,{status:I})}),i.jsx("div",{className:"flex-1 min-w-0",children:B?i.jsx("input",{ref:N,value:p,onChange:q=>m(q.target.value),onBlur:U,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,"] ",Xg(X.description)]})}),i.jsx("button",{onClick:()=>H(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:j,value:d,onChange:X=>h(X.target.value),onKeyDown:V,onPaste:O,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(Xr,{className:"w-3 h-3"}),"Add"]}),i.jsx("button",{onClick:M,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(Xr,{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(ea,{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(ag,{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:G,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(jt,{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(Ou,{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(YB,{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(Ou,{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(Ou,{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(Ou,{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 Gk({isOpen:e,onClose:t}){const n=Dn(C=>C.config),r=Dn(C=>C.saveConfig),[a,l]=E.useState(""),[u,c]=E.useState(""),[d,h]=E.useState(!1),[p,m]=E.useState(!1),[x,y]=E.useState(!1);E.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(jt,{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 RS={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"},XB={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"},OS={1:"font-bold",2:"opacity-75",4:"underline",7:"bg-bg-secondary"},QB="text-text-primary";function JB(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=RS[h];p&&d.push(p)}else if(h>=40&&h<=47){const p=XB[h];p&&d.push(p)}else if(h>=90&&h<=97){const p=RS[h];p&&d.push(p)}else if(h in OS){const p=OS[h];p&&d.push(p)}else h===39?d.push(QB):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:ZB(e),className:"text-text-primary"}]}}function ZB(e){return e.replace(new RegExp("\x1B\\[([0-9;]+)m","g"),"")}function yd(e){const t=JB(e),n=[];return t.forEach((r,a)=>{const l=r.text.split(`
284
- `);l.forEach((u,c)=>{n.push(ai.createElement("span",{key:`${a}-${c}`,className:r.className,style:{display:"inline-block",whiteSpace:"pre-wrap"}},u)),c<l.length-1&&n.push(ai.createElement("br",{key:`${a}-${c}-br`}))})}),n.length===1?n[0]:n}function Wk({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)=>r.type==="marker"?i.jsx(E.Fragment,{children:i.jsx("hr",{className:"border-t border-border my-1"})},a):i.jsx("span",{className:r.stream==="stderr"?"text-accent-warning":"",children:yd(r.content)},a))})}function Qg({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(hn,{className:"w-3 h-3"}),e?"live":"scroll to bottom"]})}const Qd=(e,t)=>{const n=E.useRef(!0),r=E.useRef(null),[a,l]=E.useState(!0),u=()=>{const c=e.current;c&&(c.scrollTop=c.scrollHeight)};return E.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()}}},Jg=E.memo(function({title:t,logs:n,onClose:r,onClear:a,onInsertMarker:l,preClassName:u}){const c=E.useRef(null),{isAutoScrollActive:d,setAutoScroll:h}=Qd(c,null);return i.jsx(jt,{isOpen:!0,onClose:r,title:t,size:"full",scrollable:!1,headerRight:i.jsx(Qg,{isActive:d,onToggle:h,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"}),footer:i.jsxs("div",{className:"flex items-center gap-2",children:[l&&i.jsxs("button",{onClick:l,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-2 py-1 rounded hover:bg-bg-tertiary transition-colors",title:"Insert marker",children:[i.jsx(Xr,{className:"w-3.5 h-3.5"}),"Marker"]}),a&&i.jsxs("button",{onClick:a,className:"text-xs text-text-muted hover:text-accent-error flex items-center gap-1 px-2 py-1 rounded hover:bg-bg-tertiary transition-colors",title:"Clear logs",children:[i.jsx(ea,{className:"w-3.5 h-3.5"}),"Clear"]})]}),children:i.jsx("div",{ref:c,className:"flex-1 overflow-y-auto scrollbar-stable -m-4 p-4",children:i.jsx(Wk,{logs:n,preClassName:u})})})}),e8=E.memo(function({logs:t,anchorRef:n,isHiding:r,isAutoScrollActive:a,onSetAutoScroll:l}){const[u,c]=E.useState(null),d=E.useRef(null),h=E.useRef(l);return h.current=l,E.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]),E.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)},[]),E.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:yd(p.content)},m))})})}),qk=E.memo(function({workdir:t,compact:n,onExpand:r,onConfigure:a}){const l=Dn(X=>X.setWorkdir),u=Dn(X=>X.status),c=Dn(X=>X.config),d=Dn(X=>X.logs),h=Dn(X=>X.start),p=Dn(X=>X.stop),m=Dn(X=>X.fetchLogs),x=Dn(X=>X.clearLogs),y=Dn(X=>X.insertMarker),w=()=>{window.confirm("Clear all dev server logs?")&&x()},[C,_]=E.useState(!1),[S,v]=E.useState(!1),[b,j]=E.useState(!1),[N,T]=E.useState(!1),D=E.useRef(null),{isAutoScrollActive:L,setAutoScroll:O}=Qd(D,null),M=E.useRef(null),W=E.useRef(null),U=E.useRef(null),R=()=>{const X=u==null?void 0:u.inspectProxyPort;if(!X){u!=null&&u.url&&window.open(u.url,"_blank");return}const $=`${window.location.protocol}//${window.location.hostname}:${X}`;window.open($,"_blank")},H=(u==null?void 0:u.state)??"off",G=c!==null,V=H==="running"||H==="warning";E.useEffect(()=>{l(t??null)},[t,l]),E.useEffect(()=>{V&&m()},[V,m]);const Z=()=>{V?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 ${H==="running"?"bg-accent-success":H==="warning"?"bg-accent-warning":H==="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():_(!0)},className:"p-1.5 rounded hover:bg-bg-tertiary transition-colors text-text-muted",title:"Configure dev server",children:i.jsx(lT,{})})]}),G?i.jsx(i.Fragment,{children:H==="running"||H==="warning"?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:Z,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(og,{}),"Stop"]}),(u==null?void 0:u.url)&&i.jsxs("button",{onClick:()=>R(),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(T1,{}),"Open"]})]}):i.jsx("button",{onClick:Z,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():_(!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:U,className:`relative ${G&&V?"":"hidden"}`,onMouseEnter:()=>{!G||!V||n||(W.current&&clearTimeout(W.current),M.current=setTimeout(()=>{j(!0),T(!1)},500))},onMouseLeave:()=>{M.current&&clearTimeout(M.current),T(!0),W.current=setTimeout(()=>j(!1),150)},children:[i.jsx(Wk,{logs:d,preRef:D,preClassName:"text-sm bg-bg-primary p-2 rounded overflow-auto max-h-[200px] border border-border"}),G&&V&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"absolute bottom-1 right-1 z-50 flex items-center gap-1",children:[!n&&(b||N)&&i.jsx(Qg,{isActive:L,onToggle:O,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():v(!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&&(b||N)&&U.current&&mi.createPortal(i.jsx(e8,{logs:d,anchorRef:U,isHiding:N,isAutoScrollActive:L,onSetAutoScroll:O}),document.body)]})]}),!a&&i.jsx(Gk,{isOpen:C,onClose:()=>_(!1)}),S&&i.jsx(Jg,{title:"Dev Server Logs",logs:d,onClose:()=>v(!1),onClear:w,onInsertMarker:y})]})}),t8=E.memo(function({sessionId:t}){var y;const n=kl(w=>w.processes),r=kl(w=>w.stopProcess),[a,l]=E.useState(null),[u,c]=E.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=kl.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(Jg,{title:((y=d.find(w=>w.id===a))==null?void 0:y.name)??"",logs:u,onClose:()=>{l(null),c([])}})]})});function Kk(){return Xt.getState().platform??null}function Yk(e){const t=e.replace(/\\/g,"/");return encodeURI(t).replace(/#/g,"%23").replace(/\?/g,"%3F")}function Xk(e,t,n){const r=Kk(),a=e.startsWith("/")||e.match(/^[a-zA-Z]:[/\\]/)?e:n?`${n.replace(/\\/g,"/").replace(/\/$/,"")}/${e}`:e,l=Yk(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 n8(e){const t=Kk(),n=Yk(e.replace(/\\/g,"/"));return t!=null&&t.isWSL&&t.wslDistro?`vscode://vscode-remote/wsl+${t.wslDistro}${n}`:`vscode://file/${n}`}function r8({file:e,showEditorLink:t,workdir:n}){const r=H1(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?Xk(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 s8(){const{diff:e}=Yg(),t=Ft(a=>a.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",n=Le(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(r8,{file:a,showEditorLink:t,workdir:r},l))})})}function Qk(e){const[t,n]=E.useState(!1),[r,a]=E.useState(null),[l,u]=E.useState(!1),[c,d]=E.useState(""),h=E.useCallback(()=>{t||e()},[t,e]),p=c.trim().length>0&&!t,m=E.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 Jk({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(jt,{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(pi,{})}):l})}function Zk({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 e2({isOpen:e,onClose:t,projectId:n,sessionId:r,currentWorkspace:a,currentBranch:l}){const u=Le(R=>R.loadSession),{busy:c,setBusy:d,error:h,setError:p,loading:m,setLoading:x,newName:y,setNewName:w,handleClose:C,canCreate:_,resetState:S}=Qk(t),[v,b]=E.useState([]),[j,N]=E.useState(null),[T,D]=E.useState(null),[L,O]=E.useState(!1);E.useEffect(()=>{e&&(S(),N(null),D(null),O(!1),ve(`/api/projects/${n}/workspaces`).then(R=>R.json()).then(R=>{b(R.workspaces),x(!1)}).catch(()=>{b([]),x(!1)}))},[e,n,S,x]);const M=E.useCallback(async R=>{p(null),d(!0);try{const H=await ve(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R})});if(!H.ok){const G=await H.json().catch(()=>({error:"Failed to switch workspace"}));p(G.error),d(!1);return}await u(r),t()}catch(H){p(H instanceof Error?H.message:"Failed to switch workspace"),d(!1)}},[r,u,t,p,d]),W=E.useCallback(async(R,H)=>{p(null),D(null),O((H==null?void 0:H.force)===!0),d(!0);try{const G=await ve(`/api/sessions/${r}/delete-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R,force:(H==null?void 0:H.force)===!0})});if(!G.ok){const X=await G.json().catch(()=>({error:"Failed to delete workspace"}));p(X.error),X.conflictingSessionIds&&D(X.conflictingSessionIds),O(!1),d(!1);return}N(null),O(!1),await u(r);const Z=await(await ve(`/api/projects/${n}/workspaces`)).json();b(Z.workspaces),d(!1),x(!1)}catch(G){p(G instanceof Error?G.message:"Failed to delete workspace"),O(!1),d(!1)}},[r,n,u,p,d]),U=E.useCallback(async()=>{p(null),d(!0);try{const R=await ve(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:y.trim()})});if(!R.ok){const H=await R.json().catch(()=>({error:"Failed to create workspace"}));p(H.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(Jk,{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:()=>M("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(Rr,{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,H)=>R.name===a?-1:H.name===a?1:R.name.localeCompare(H.name)).map(R=>i.jsx("div",{className:"group relative",children:j===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:()=>N(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&&M(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(Rr,{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:H=>{H.stopPropagation(),p(null),D(null),N(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(Zk,{icon:i.jsx(Rr,{}),title:"Create new workspace",placeholder:"workspace name",buttonLabel:"Create Workspace",value:y,onChange:w,onCreate:U,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(Xn,{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(j??"",{force:!0}),disabled:c||!j,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 t2({isOpen:e,onClose:t,sessionId:n}){const r=Le(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}=Qk(t),[C,_]=E.useState([]),[S,v]=E.useState(""),[b,j]=E.useState("");E.useEffect(()=>{e&&(w(),v(""),_([]),j(""),ve(`/api/sessions/${n}/branches`).then(D=>D.json()).then(D=>{_(D.branches),j(D.defaultBranch??""),h(!1)}).catch(()=>{_([]),h(!1)}))},[e,n,w,h]);const N=E.useCallback(async D=>{c(null),l(!0);try{const L=await ve(`/api/sessions/${n}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:D})});if(!L.ok){const O=await L.json().catch(()=>({error:"Failed to switch branch"}));c(O.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=E.useCallback(async()=>{c(null),l(!0);try{const D={name:p.trim()};S&&(D.sourceBranch=S);const L=await ve(`/api/sessions/${n}/checkout-new`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!L.ok){const O=await L.json().catch(()=>({error:"Failed to create branch"}));c(O.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(Jk,{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||N(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(Ki,{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(Zk,{icon:i.jsx(Ki,{}),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(Ki,{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 n2({workspaceName:e,branch:t,workdir:n,showEditorLink:r,sessionId:a,projectId:l,onEditWorkspace:u,onEditBranch:c}){const[d,h]=E.useState(!1),[p,m]=E.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:n8(n),className:"flex items-center gap-2 min-w-0 flex-1 no-underline group",title:"Open workspace in VSCode",children:[i.jsx(Rr,{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(Rr,{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(Ki,{}),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(s8,{}),!u&&i.jsx(e2,{isOpen:d,onClose:()=>h(!1),projectId:l,sessionId:a,currentWorkspace:e,currentBranch:t}),!c&&i.jsx(t2,{isOpen:p,onClose:()=>m(!1),sessionId:a})]})}function i8(e,t){return t||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function a8(e,t){return t||e>85?"bg-accent-error":e>60?"bg-accent-warning":"bg-accent-success"}function Zg({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 ${a8(e,t)}`,style:{width:`${Math.min(e,100)}%`}})})}function o8({dangerZone:e,size:t="md"}){return e?i.jsx("span",{className:"text-accent-error animate-pulse text-[10px] font-medium",children:"Low!"}):null}function l8({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 lo=E.memo(function({code:t,language:n,variant:r,showLineNumbers:a=!1,startLine:l=1}){const{showSyntaxHighlighting:u}=Zi(),[c,d]=E.useState(null),h=Sk(),p=E.useRef(t);if(E.useEffect(()=>{u&&(p.current=t,_k(t,n,h).then(x=>{p.current===t&&d(x)}))},[t,n,h,u]),!u||!c)return i.jsx(l8,{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 r2({src:e,alt:t,isOpen:n,onClose:r}){return n?i.jsx(jt,{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 bd=E.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})})})}),c8=E.memo(function({oldString:t,newString:n,filePath:r}){const a=E.useMemo(()=>Yd(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(bd,{type:"removed",children:i.jsx(lo,{code:t,language:a,variant:"block",showLineNumbers:!0})}),u&&i.jsx(bd,{type:"added",children:i.jsx(lo,{code:n,language:a,variant:"block",showLineNumbers:!0})})]})}),u8=E.memo(function({content:t,filePath:n}){const r=E.useMemo(()=>Yd(n),[n]);return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto",children:i.jsx(bd,{type:"added",children:i.jsx(lo,{code:t,language:r,variant:"block",showLineNumbers:!0})})})}),d8=E.memo(function({regions:t,filePath:n}){const r=E.useMemo(()=>Yd(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(f8,{region:a,language:r},l))})});function h8(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(ai.createElement("span",{key:`${a}-${c}`,className:r.className,style:{display:"inline-block",whiteSpace:"pre-wrap"}},u)),c<l.length-1&&n.push(ai.createElement("br",{key:`${a}-${c}-br`}))})}),n.length===1?n[0]:n}function Wk({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)=>r.type==="marker"?i.jsx(E.Fragment,{children:i.jsx("hr",{className:"border-t border-border my-1"})},a):i.jsx("span",{className:r.stream==="stderr"?"text-accent-warning":"",children:yd(r.content)},a))})}function Qg({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(hn,{className:"w-3 h-3"}),e?"live":"scroll to bottom"]})}const Qd=(e,t)=>{const n=E.useRef(!0),r=E.useRef(null),[a,l]=E.useState(!0),u=()=>{const c=e.current;c&&(c.scrollTop=c.scrollHeight)};return E.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()}}},Jg=E.memo(function({title:t,logs:n,onClose:r,onClear:a,onInsertMarker:l,preClassName:u}){const c=E.useRef(null),{isAutoScrollActive:d,setAutoScroll:h}=Qd(c,null);return i.jsx(jt,{isOpen:!0,onClose:r,title:t,size:"full",scrollable:!1,headerRight:i.jsx(Qg,{isActive:d,onToggle:h,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"}),footer:i.jsxs("div",{className:"flex items-center gap-2",children:[l&&i.jsxs("button",{onClick:l,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-2 py-1 rounded hover:bg-bg-tertiary transition-colors",title:"Insert marker",children:[i.jsx(Xr,{className:"w-3.5 h-3.5"}),"Marker"]}),a&&i.jsxs("button",{onClick:a,className:"text-xs text-text-muted hover:text-accent-error flex items-center gap-1 px-2 py-1 rounded hover:bg-bg-tertiary transition-colors",title:"Clear logs",children:[i.jsx(ea,{className:"w-3.5 h-3.5"}),"Clear"]})]}),children:i.jsx("div",{ref:c,className:"flex-1 overflow-y-auto scrollbar-stable -m-4 p-4",children:i.jsx(Wk,{logs:n,preClassName:u})})})}),e8=E.memo(function({logs:t,anchorRef:n,isHiding:r,isAutoScrollActive:a,onSetAutoScroll:l}){const[u,c]=E.useState(null),d=E.useRef(null),h=E.useRef(l);return h.current=l,E.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]),E.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)},[]),E.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:yd(p.content)},m))})})}),qk=E.memo(function({workdir:t,compact:n,onExpand:r,onConfigure:a}){const l=Dn(X=>X.setWorkdir),u=Dn(X=>X.status),c=Dn(X=>X.config),d=Dn(X=>X.logs),h=Dn(X=>X.start),p=Dn(X=>X.stop),m=Dn(X=>X.fetchLogs),x=Dn(X=>X.clearLogs),y=Dn(X=>X.insertMarker),w=()=>{window.confirm("Clear all dev server logs?")&&x()},[C,_]=E.useState(!1),[S,v]=E.useState(!1),[b,j]=E.useState(!1),[N,T]=E.useState(!1),D=E.useRef(null),{isAutoScrollActive:L,setAutoScroll:O}=Qd(D,null),M=E.useRef(null),W=E.useRef(null),U=E.useRef(null),R=()=>{const X=u==null?void 0:u.inspectProxyPort;if(!X){u!=null&&u.url&&window.open(u.url,"_blank");return}const $=`${window.location.protocol}//${window.location.hostname}:${X}`;window.open($,"_blank")},H=(u==null?void 0:u.state)??"off",G=c!==null,V=H==="running"||H==="warning";E.useEffect(()=>{l(t??null)},[t,l]),E.useEffect(()=>{V&&m()},[V,m]);const Z=()=>{V?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 ${H==="running"?"bg-accent-success":H==="warning"?"bg-accent-warning":H==="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():_(!0)},className:"p-1.5 rounded hover:bg-bg-tertiary transition-colors text-text-muted",title:"Configure dev server",children:i.jsx(lT,{})})]}),G?i.jsx(i.Fragment,{children:H==="running"||H==="warning"?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:Z,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(og,{}),"Stop"]}),(u==null?void 0:u.url)&&i.jsxs("button",{onClick:()=>R(),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(T1,{}),"Open"]})]}):i.jsx("button",{onClick:Z,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():_(!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:U,className:`relative ${G&&V?"":"hidden"}`,onMouseEnter:()=>{!G||!V||n||(W.current&&clearTimeout(W.current),M.current=setTimeout(()=>{j(!0),T(!1)},500))},onMouseLeave:()=>{M.current&&clearTimeout(M.current),T(!0),W.current=setTimeout(()=>j(!1),150)},children:[i.jsx(Wk,{logs:d,preRef:D,preClassName:"text-sm bg-bg-primary p-2 rounded overflow-auto max-h-[200px] border border-border"}),G&&V&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"absolute bottom-1 right-1 z-50 flex items-center gap-1",children:[!n&&(b||N)&&i.jsx(Qg,{isActive:L,onToggle:O,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():v(!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&&(b||N)&&U.current&&mi.createPortal(i.jsx(e8,{logs:d,anchorRef:U,isHiding:N,isAutoScrollActive:L,onSetAutoScroll:O}),document.body)]})]}),!a&&i.jsx(Gk,{isOpen:C,onClose:()=>_(!1)}),S&&i.jsx(Jg,{title:"Dev Server Logs",logs:d,onClose:()=>v(!1),onClear:w,onInsertMarker:y})]})}),t8=E.memo(function({sessionId:t}){var y;const n=kl(w=>w.processes),r=kl(w=>w.stopProcess),[a,l]=E.useState(null),[u,c]=E.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=kl.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(Jg,{title:((y=d.find(w=>w.id===a))==null?void 0:y.name)??"",logs:u,onClose:()=>{l(null),c([])}})]})});function Kk(){return Xt.getState().platform??null}function Yk(e){const t=e.replace(/\\/g,"/");return encodeURI(t).replace(/#/g,"%23").replace(/\?/g,"%3F")}function Xk(e,t,n){const r=Kk(),a=e.startsWith("/")||e.match(/^[a-zA-Z]:[/\\]/)?e:n?`${n.replace(/\\/g,"/").replace(/\/$/,"")}/${e}`:e,l=Yk(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 n8(e){const t=Kk(),n=Yk(e.replace(/\\/g,"/"));return t!=null&&t.isWSL&&t.wslDistro?`vscode://vscode-remote/wsl+${t.wslDistro}${n}`:`vscode://file/${n}`}function r8({file:e,showEditorLink:t,workdir:n}){const r=H1(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?Xk(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 s8(){const{diff:e}=Yg(),t=Ft(a=>a.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",n=Le(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(r8,{file:a,showEditorLink:t,workdir:r},l))})})}function Qk(e){const[t,n]=E.useState(!1),[r,a]=E.useState(null),[l,u]=E.useState(!1),[c,d]=E.useState(""),h=E.useCallback(()=>{t||e()},[t,e]),p=c.trim().length>0&&!t,m=E.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 Jk({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(jt,{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(pi,{})}):l})}function Zk({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 ej({isOpen:e,onClose:t,projectId:n,sessionId:r,currentWorkspace:a,currentBranch:l}){const u=Le(R=>R.loadSession),{busy:c,setBusy:d,error:h,setError:p,loading:m,setLoading:x,newName:y,setNewName:w,handleClose:C,canCreate:_,resetState:S}=Qk(t),[v,b]=E.useState([]),[j,N]=E.useState(null),[T,D]=E.useState(null),[L,O]=E.useState(!1);E.useEffect(()=>{e&&(S(),N(null),D(null),O(!1),ve(`/api/projects/${n}/workspaces`).then(R=>R.json()).then(R=>{b(R.workspaces),x(!1)}).catch(()=>{b([]),x(!1)}))},[e,n,S,x]);const M=E.useCallback(async R=>{p(null),d(!0);try{const H=await ve(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R})});if(!H.ok){const G=await H.json().catch(()=>({error:"Failed to switch workspace"}));p(G.error),d(!1);return}await u(r),t()}catch(H){p(H instanceof Error?H.message:"Failed to switch workspace"),d(!1)}},[r,u,t,p,d]),W=E.useCallback(async(R,H)=>{p(null),D(null),O((H==null?void 0:H.force)===!0),d(!0);try{const G=await ve(`/api/sessions/${r}/delete-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:R,force:(H==null?void 0:H.force)===!0})});if(!G.ok){const X=await G.json().catch(()=>({error:"Failed to delete workspace"}));p(X.error),X.conflictingSessionIds&&D(X.conflictingSessionIds),O(!1),d(!1);return}N(null),O(!1),await u(r);const Z=await(await ve(`/api/projects/${n}/workspaces`)).json();b(Z.workspaces),d(!1),x(!1)}catch(G){p(G instanceof Error?G.message:"Failed to delete workspace"),O(!1),d(!1)}},[r,n,u,p,d]),U=E.useCallback(async()=>{p(null),d(!0);try{const R=await ve(`/api/sessions/${r}/switch-workspace`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:y.trim()})});if(!R.ok){const H=await R.json().catch(()=>({error:"Failed to create workspace"}));p(H.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(Jk,{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:()=>M("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(Rr,{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,H)=>R.name===a?-1:H.name===a?1:R.name.localeCompare(H.name)).map(R=>i.jsx("div",{className:"group relative",children:j===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:()=>N(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&&M(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(Rr,{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:H=>{H.stopPropagation(),p(null),D(null),N(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(Zk,{icon:i.jsx(Rr,{}),title:"Create new workspace",placeholder:"workspace name",buttonLabel:"Create Workspace",value:y,onChange:w,onCreate:U,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(Xn,{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(j??"",{force:!0}),disabled:c||!j,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 tj({isOpen:e,onClose:t,sessionId:n}){const r=Le(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}=Qk(t),[C,_]=E.useState([]),[S,v]=E.useState(""),[b,j]=E.useState("");E.useEffect(()=>{e&&(w(),v(""),_([]),j(""),ve(`/api/sessions/${n}/branches`).then(D=>D.json()).then(D=>{_(D.branches),j(D.defaultBranch??""),h(!1)}).catch(()=>{_([]),h(!1)}))},[e,n,w,h]);const N=E.useCallback(async D=>{c(null),l(!0);try{const L=await ve(`/api/sessions/${n}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:D})});if(!L.ok){const O=await L.json().catch(()=>({error:"Failed to switch branch"}));c(O.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=E.useCallback(async()=>{c(null),l(!0);try{const D={name:p.trim()};S&&(D.sourceBranch=S);const L=await ve(`/api/sessions/${n}/checkout-new`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!L.ok){const O=await L.json().catch(()=>({error:"Failed to create branch"}));c(O.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(Jk,{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||N(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(Ki,{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(Zk,{icon:i.jsx(Ki,{}),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(Ki,{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 nj({workspaceName:e,branch:t,workdir:n,showEditorLink:r,sessionId:a,projectId:l,onEditWorkspace:u,onEditBranch:c}){const[d,h]=E.useState(!1),[p,m]=E.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:n8(n),className:"flex items-center gap-2 min-w-0 flex-1 no-underline group",title:"Open workspace in VSCode",children:[i.jsx(Rr,{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(Rr,{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(Ki,{}),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(s8,{}),!u&&i.jsx(ej,{isOpen:d,onClose:()=>h(!1),projectId:l,sessionId:a,currentWorkspace:e,currentBranch:t}),!c&&i.jsx(tj,{isOpen:p,onClose:()=>m(!1),sessionId:a})]})}function i8(e,t){return t||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function a8(e,t){return t||e>85?"bg-accent-error":e>60?"bg-accent-warning":"bg-accent-success"}function Zg({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 ${a8(e,t)}`,style:{width:`${Math.min(e,100)}%`}})})}function o8({dangerZone:e,size:t="md"}){return e?i.jsx("span",{className:"text-accent-error animate-pulse text-[10px] font-medium",children:"Low!"}):null}function l8({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 lo=E.memo(function({code:t,language:n,variant:r,showLineNumbers:a=!1,startLine:l=1}){const{showSyntaxHighlighting:u}=Zi(),[c,d]=E.useState(null),h=Sk(),p=E.useRef(t);if(E.useEffect(()=>{u&&(p.current=t,_k(t,n,h).then(x=>{p.current===t&&d(x)}))},[t,n,h,u]),!u||!c)return i.jsx(l8,{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 rj({src:e,alt:t,isOpen:n,onClose:r}){return n?i.jsx(jt,{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 bd=E.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})})})}),c8=E.memo(function({oldString:t,newString:n,filePath:r}){const a=E.useMemo(()=>Yd(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(bd,{type:"removed",children:i.jsx(lo,{code:t,language:a,variant:"block",showLineNumbers:!0})}),u&&i.jsx(bd,{type:"added",children:i.jsx(lo,{code:n,language:a,variant:"block",showLineNumbers:!0})})]})}),u8=E.memo(function({content:t,filePath:n}){const r=E.useMemo(()=>Yd(n),[n]);return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto",children:i.jsx(bd,{type:"added",children:i.jsx(lo,{code:t,language:r,variant:"block",showLineNumbers:!0})})})}),d8=E.memo(function({regions:t,filePath:n}){const r=E.useMemo(()=>Yd(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(f8,{region:a,language:r},l))})});function h8(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 f8=E.memo(function({region:t,language:n}){const r=h8(t);return i.jsx("div",{className:"rounded overflow-hidden border border-border font-mono text-sm",children:r.map((a,l)=>i.jsx(m8,{section:a,language:n},l))})}),m8=E.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(lo,{code:r,language:n,variant:"block",showLineNumbers:!0,startLine:t.startLine})})})}):i.jsx(bd,{type:t.type,children:i.jsx(lo,{code:r,language:n,variant:"block",showLineNumbers:!0,startLine:t.startLine})})});function IS(e){return e.split(`
288
288
  `).filter(t=>!t.startsWith(`
289
289
  [`)&&!t.startsWith("[")).map(t=>t.replace(/^\d+\|/,"")).join(`
290
- `)}const p8=E.memo(function({result:t,metadata:n,filePath:r}){const[a,l]=E.useState(!1),u=E.useMemo(()=>Yd(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(r2,{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=IS(h);return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto p-2",children:i.jsx(zn,{content:w})})}const p=IS(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(lo,{code:p,language:u,variant:"block",showLineNumbers:!0,startLine:y})})});function g8({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 x8({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(g8,{type:r.type,content:r.content},a))})]})}function ex({isOpen:e,onClose:t,isRunning:n,onApply:r}){const[a,l]=E.useState(null),[u,c]=E.useState(!1),d=E.useRef(null),h=E.useCallback(()=>{c(!0);const p=Bt.send("context.applyDynamic.preview",{});d.current=p;const m=Bt.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 E.useEffect(()=>{e&&(l(null),c(!0),h())},[e,h]),i.jsxs(jt,{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(x8,{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 s2({variant:e="popover",onUpdateSystemPrompt:t}){const n=Le(D=>D.contextState),r=Le(D=>D.currentSession),a=Le(D=>D.compactContext),l=Le(D=>D.queueUpdate),[u,c]=E.useState(!1),[d,h]=E.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():Bt.send("context.applyDynamic",{}),c(!1)},v=e==="sidebar",b=i.jsxs("span",{className:i8(C,y),children:[oo(p)," / ",oo(m)," (",C,"%)"]}),j=i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Zg,{percent:C,dangerZone:y,className:"flex-1"}),i.jsx(o8,{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"]})]}),N=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(N1,{})}),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(ex,{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}),j]}),i.jsx("div",{className:"shrink-0 pt-0.5",children:N})]}),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}),j]}),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 MS({messages:e,workdir:t}){var v,b,j;const[n,r]=E.useState(!1),[a,l]=E.useState(!1),[u,c]=E.useState(null),d=jB(e),{branch:h}=Yg(),p=Xt(N=>N.version),m=Le(N=>N.currentSession),x=m!=null&&m.workspace?m.workspace.split("/").pop()??null:null,y=Ft(N=>N.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",w=Cs(N=>N.status),C=Cs(N=>N.check),[_,S]=E.useState(!1);return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsx(s2,{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:Yr(d.aiTime)}),i.jsx("span",{className:"w-px h-3 bg-border"}),i.jsx("span",{className:"text-text-secondary",children:ES(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:ES(d.avgGenerationSpeed)}),i.jsx("span",{children:"tg"})]})}),i.jsx(BB,{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(xd,{entries:((v=m==null?void 0:m.metadataEntries)==null?void 0:v.criteria)??[],title:"Acceptance Criteria"})}),m&&i.jsx(Vk,{entries:((b=m==null?void 0:m.metadataEntries)==null?void 0:b.criteria)??[],sessionId:m.id}),m&&(()=>{const N=["review_findings","todos"],T=m.metadataEntries??{},D=N.filter(O=>O in T),L=Object.keys(T).filter(O=>O!=="criteria"&&!N.includes(O)).sort();return[...D,...L].filter(O=>{var M;return(((M=T[O])==null?void 0:M.length)??0)>0}).map(O=>i.jsxs("div",{className:"mt-6",children:[i.jsx("button",{onClick:()=>c(O),className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(xd,{entries:T[O],title:so(O)})}),i.jsx(Uk,{entries:T[O],onClearAll:async()=>{try{await ve(`/api/sessions/${m.id}/metadata/${O}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:[]})})}catch(M){console.error(`Failed to clear ${O}:`,M)}}})]},O))})()]})}),i.jsx(n2,{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(qk,{workdir:t}),i.jsx(t8,{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(jd,{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(G1,{isOpen:a,onClose:()=>l(!1),versionInfo:null}),i.jsx(Fk,{isOpen:u!==null,onClose:()=>c(null),entries:((j=m==null?void 0:m.metadataEntries)==null?void 0:j[u??""])??[],sessionId:(m==null?void 0:m.id)??"",metadataKey:u??"",title:so(u??"")})]})}function y8({children:e,criteriaSidebarOpen:t=!0,onCriteriaSidebarToggle:n,messages:r}){const a=Le(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(MS,{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:`
290
+ `)}const p8=E.memo(function({result:t,metadata:n,filePath:r}){const[a,l]=E.useState(!1),u=E.useMemo(()=>Yd(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(rj,{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=IS(h);return i.jsx("div",{className:"rounded overflow-hidden border border-border max-h-[45vh] overflow-y-auto p-2",children:i.jsx(zn,{content:w})})}const p=IS(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(lo,{code:p,language:u,variant:"block",showLineNumbers:!0,startLine:y})})});function g8({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 x8({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(g8,{type:r.type,content:r.content},a))})]})}function ex({isOpen:e,onClose:t,isRunning:n,onApply:r}){const[a,l]=E.useState(null),[u,c]=E.useState(!1),d=E.useRef(null),h=E.useCallback(()=>{c(!0);const p=Dt.send("context.applyDynamic.preview",{});d.current=p;const m=Dt.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 E.useEffect(()=>{e&&(l(null),c(!0),h())},[e,h]),i.jsxs(jt,{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(x8,{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 sj({variant:e="popover",onUpdateSystemPrompt:t}){const n=Le(D=>D.contextState),r=Le(D=>D.currentSession),a=Le(D=>D.compactContext),l=Le(D=>D.queueUpdate),[u,c]=E.useState(!1),[d,h]=E.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():Dt.send("context.applyDynamic",{}),c(!1)},v=e==="sidebar",b=i.jsxs("span",{className:i8(C,y),children:[oo(p)," / ",oo(m)," (",C,"%)"]}),j=i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Zg,{percent:C,dangerZone:y,className:"flex-1"}),i.jsx(o8,{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"]})]}),N=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(N1,{})}),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(ex,{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}),j]}),i.jsx("div",{className:"shrink-0 pt-0.5",children:N})]}),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}),j]}),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 MS({messages:e,workdir:t}){var v,b,j;const[n,r]=E.useState(!1),[a,l]=E.useState(!1),[u,c]=E.useState(null),d=jB(e),{branch:h}=Yg(),p=Xt(N=>N.version),m=Le(N=>N.currentSession),x=m!=null&&m.workspace?m.workspace.split("/").pop()??null:null,y=Ft(N=>N.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",w=Cs(N=>N.status),C=Cs(N=>N.check),[_,S]=E.useState(!1);return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsx(sj,{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:Yr(d.aiTime)}),i.jsx("span",{className:"w-px h-3 bg-border"}),i.jsx("span",{className:"text-text-secondary",children:ES(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:ES(d.avgGenerationSpeed)}),i.jsx("span",{children:"tg"})]})}),i.jsx(BB,{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(xd,{entries:((v=m==null?void 0:m.metadataEntries)==null?void 0:v.criteria)??[],title:"Acceptance Criteria"})}),m&&i.jsx(Vk,{entries:((b=m==null?void 0:m.metadataEntries)==null?void 0:b.criteria)??[],sessionId:m.id}),m&&(()=>{const N=["review_findings","todos"],T=m.metadataEntries??{},D=N.filter(O=>O in T),L=Object.keys(T).filter(O=>O!=="criteria"&&!N.includes(O)).sort();return[...D,...L].filter(O=>{var M;return(((M=T[O])==null?void 0:M.length)??0)>0}).map(O=>i.jsxs("div",{className:"mt-6",children:[i.jsx("button",{onClick:()=>c(O),className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(xd,{entries:T[O],title:so(O)})}),i.jsx(Uk,{entries:T[O],onClearAll:async()=>{try{await ve(`/api/sessions/${m.id}/metadata/${O}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:[]})})}catch(M){console.error(`Failed to clear ${O}:`,M)}}})]},O))})()]})}),i.jsx(nj,{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(qk,{workdir:t}),i.jsx(t8,{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(jd,{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(G1,{isOpen:a,onClose:()=>l(!1),versionInfo:null}),i.jsx(Fk,{isOpen:u!==null,onClose:()=>c(null),entries:((j=m==null?void 0:m.metadataEntries)==null?void 0:j[u??""])??[],sessionId:(m==null?void 0:m.id)??"",metadataKey:u??"",title:so(u??"")})]})}function y8({children:e,criteriaSidebarOpen:t=!0,onCriteriaSidebarToggle:n,messages:r}){const a=Le(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(MS,{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
295
295
  fixed right-0 top-[32px] h-[calc(100vh-32px)] z-50
296
296
  ${t?"w-[320px] translate-x-0 border-l border-border":"w-[320px] translate-x-full"}
297
- `,children:i.jsx(MS,{messages:r,workdir:(a==null?void 0:a.workspace)??(a==null?void 0:a.workdir)})})]})]})}function b8(){const e=Le(w=>w.contextState),t=Le(w=>w.currentSession),n=Le(w=>w.pendingUpdate),r=Le(w=>w.triggerPendingUpdate),a=Le(w=>w.queueUpdate),[l,u]=E.useState(!1),[c,d]=E.useState(!1),h=E.useRef(!1),p=E.useRef(!1);if(E.useEffect(()=>{e!=null&&e.dynamicContextChanged&&!h.current&&u(!1),h.current=(e==null?void 0:e.dynamicContextChanged)??!1},[e==null?void 0:e.dynamicContextChanged]),E.useEffect(()=>{const w=(t==null?void 0:t.isRunning)??!1;p.current&&!w&&n&&r(),p.current=w},[t==null?void 0:t.isRunning,n,r]),!e||!t)return null;const{dynamicContextChanged:m}=e,x=t.isRunning,y=()=>{x?a():Bt.send("context.applyDynamic",{}),u(!0),d(!1)};return i.jsxs(i.Fragment,{children:[m&&!l&&i.jsx("div",{className:"flex-shrink-0 px-4 py-2 bg-accent-warning/10 border-b border-accent-warning/30",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1 flex items-center justify-center gap-1 text-sm text-text-secondary",children:[i.jsx("span",{children:"System prompt has changed —"}),i.jsx("button",{onClick:()=>d(!0),className:"underline hover:text-text-primary transition-colors",children:"click here to update it"})]}),i.jsx("button",{onClick:()=>u(!0),className:"flex-shrink-0 p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Dismiss",children:i.jsx(js,{})})]})}),i.jsx(ex,{isOpen:c,onClose:()=>d(!1),isRunning:x,onApply:y})]})}function v8({stats:e,onClose:t}){var c;const n=xt(d=>d.defaults),r=xt(d=>d.userItems),l=[...n,...r].find(d=>d.id===e.mode),u=(l==null?void 0:l.name)??e.mode;return i.jsx(jt,{isOpen:!0,onClose:t,title:"Turn Stats",size:"md",children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"flex items-center gap-3",children:i.jsxs("p",{className:"text-xs text-text-muted",children:[e.model," · ",u]})}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[i.jsx(Iu,{label:"Total Time",value:Yr(e.totalTime)}),i.jsx(Iu,{label:"Prefill",value:e.prefillTokens>=1e3?`${(e.prefillTokens/1e3).toFixed(1)}k`:String(e.prefillTokens)}),i.jsx(Iu,{label:"Generated",value:e.generationTokens>=1e3?`${(e.generationTokens/1e3).toFixed(1)}k`:String(e.generationTokens)}),i.jsx(Iu,{label:"LLM Calls",value:String(((c=e.llmCalls)==null?void 0:c.length)??1)})]}),e.llmCalls&&e.llmCalls.length>0&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-2",children:"LLM Calls"}),e.llmCalls.map((d,h)=>i.jsxs("div",{className:"bg-bg-tertiary/30 rounded p-3 mb-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("span",{className:"text-xs text-text-muted",children:["Call ",h+1]}),i.jsxs("span",{className:"text-xs text-text-muted",children:[d.ttft.toFixed(2),"s TTFT · ",d.completionTime.toFixed(2),"s gen"]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-text-muted",children:"Tokens:"})," ",i.jsxs("span",{className:"text-text-primary",children:[d.promptTokens," → ",d.completionTokens]})]}),i.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1",children:[d.temperature!==void 0&&i.jsx(Mu,{label:"temp",value:d.temperature.toFixed(2)}),d.topP!==void 0&&i.jsx(Mu,{label:"topP",value:d.topP.toFixed(2)}),d.topK!==void 0&&i.jsx(Mu,{label:"topK",value:String(d.topK)}),d.maxTokens!==void 0&&i.jsx(Mu,{label:"maxTok",value:String(d.maxTokens)})]})]})]},h))]})]})})}function Iu({label:e,value:t}){return i.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[i.jsx("div",{className:"text-xs text-text-muted",children:e}),i.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t})]})}function Mu({label:e,value:t}){return i.jsxs("span",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-text-primary",children:[i.jsxs("span",{className:"text-text-muted",children:[e,":"]})," ",t]})}const _8=E.memo(function({content:t,variant:n="default"}){return n==="labeled"?i.jsxs("div",{className:"text-text-muted text-sm italic feed-item",children:[i.jsx("span",{className:"text-text-thinking",children:"thinking:"}),i.jsx("div",{className:"ml-1.5 mt-0.5 overflow-x-auto",children:i.jsx(zn,{content:t})})]}):i.jsx("div",{className:"text-text-muted text-sm italic bg-secondary rounded p-1.5 feed-item overflow-x-auto",children:i.jsx(zn,{content:t,muted:!0})})});function i2({tool:e,className:t="w-4 h-4 text-text-muted flex-shrink-0"}){return e==="glob"||e==="grep"?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:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}):e==="run_command"||e==="bash"?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:"M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"})}):e==="workspace"?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:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"})}):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:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}const S8={error:{icon:"✗",color:"text-accent-error",bg:"bg-red-500/10",border:"border-red-500/30"},warning:{icon:"⚠",color:"text-accent-warning",bg:"bg-yellow-500/10",border:"border-yellow-500/30"},info:{icon:"ℹ",color:"text-accent-info",bg:"bg-blue-500/10",border:"border-blue-500/30"},hint:{icon:"💡",color:"text-text-muted",bg:"bg-gray-500/10",border:"border-gray-500/30"}},PS=E.memo(function({diagnostics:t}){if(t.length===0)return null;const n=t.filter(l=>l.severity==="error"),r=t.filter(l=>l.severity==="warning"),a=t.filter(l=>l.severity==="info"||l.severity==="hint");return i.jsxs("div",{className:"rounded border border-border overflow-hidden mt-2",children:[i.jsxs("div",{className:"flex items-center gap-3 px-2 py-1.5 bg-bg-tertiary border-b border-border",children:[i.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"LSP Diagnostics"}),n.length>0&&i.jsxs("span",{className:"text-xs text-accent-error font-medium",children:[n.length," error",n.length!==1?"s":""]}),r.length>0&&i.jsxs("span",{className:"text-xs text-accent-warning font-medium",children:[r.length," warning",r.length!==1?"s":""]}),a.length>0&&i.jsxs("span",{className:"text-xs text-text-muted",children:[a.length," info"]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto",children:t.map((l,u)=>{const c=S8[l.severity];return i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${c.bg} border-b border-border last:border-b-0`,children:[i.jsx("span",{className:`${c.color} text-xs flex-shrink-0 w-4 text-center`,children:c.icon}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:["Ln ",l.range.start.line+1,":",l.range.start.character+1]}),l.code&&i.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:["[",l.code,"]"]})]}),i.jsx("div",{className:"text-xs text-text-primary break-words",children:l.message})]})]},u)})})]})}),w8=E.memo(function({command:t,timeout:n,startedAt:r,streamingOutput:a,status:l,result:u,error:c,durationMs:d}){const h=E.useRef(null),[p,m]=E.useState(0);E.useEffect(()=>{h.current&&l==="pending"&&(h.current.scrollTop=h.current.scrollHeight)},[a,l]),E.useEffect(()=>{if(l!=="pending"||!r)return;const C=setInterval(()=>{m(Date.now()-r)},100);return()=>clearInterval(C)},[l,r]);const x=n/1e3,y=l==="pending"?p/1e3:(d??0)/1e3,w=l==="pending"?(a==null?void 0:a.map(C=>C.content).join(""))??"":u??"";return i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs flex-1 min-w-0",children:[i.jsx("span",{className:"text-text-muted flex-shrink-0",children:"$"}),i.jsx("code",{className:"text-text-primary break-all",children:t})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted flex-shrink-0",children:[l==="pending"&&i.jsx("span",{className:"animate-pulse text-accent-warning",children:"running"}),l==="interrupted"&&i.jsx("span",{className:"text-red-400",children:"interrupted"}),i.jsxs("span",{className:l==="pending"?"text-text-secondary":"text-text-muted",children:[y.toFixed(1),"s / ",x,"s"]})]})]}),l==="pending"&&i.jsx("div",{className:"h-1 bg-bg-tertiary rounded overflow-hidden",children:i.jsx("div",{className:"h-full bg-accent-warning transition-all duration-100",style:{width:`${Math.min(100,p/n*100)}%`}})}),(w||l==="pending")&&i.jsx("pre",{ref:h,className:`text-xs bg-bg-primary p-2 rounded max-h-64 overflow-y-auto ${l==="pending"?"border border-accent-warning/30":""}`,style:{overflowX:"hidden",whiteSpace:"normal"},children:l==="pending"&&a?a.map((C,_)=>i.jsx("span",{className:C.stream==="stderr"?"text-accent-warning":"",children:yd(C.content)},_)):yd(w)}),l==="error"&&c&&i.jsx("div",{className:"text-xs text-accent-error bg-accent-error/10 p-2 rounded",children:c}),l!=="pending"&&d!==void 0&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Completed in ",(d/1e3).toFixed(2),"s"]})]})}),bl=E.memo(function({className:t=""}){return i.jsx("div",{className:`text-[10px] text-accent-warning ${t}`,children:"Output truncated"})}),C8=E.memo(function({result:t,action:n}){let r;try{r=JSON.parse(t)}catch{return console.warn("DevServerView: failed to parse result JSON",t.slice(0,200)),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}return n==="logs"?k8(r):j8(r)});function k8(e){if(!e.logs)return i.jsx("div",{className:"text-xs text-text-muted italic",children:"No log output"});const t=e.logs.split(`
298
- `);return i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-mono whitespace-pre-wrap bg-bg-primary p-2 rounded max-h-[60vh] overflow-y-auto break-words",children:t.map((n,r)=>{const a=n.startsWith("[stderr] ");return i.jsx("div",{className:a?"text-accent-warning":"",children:a?n.slice(9):n},r)})}),e.hasMore&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Showing ",e.limit," of ",e.total," lines"]})]})}function j8(e){const t=String(e.state??""),n=String(e.url??""),r=e.error?String(e.error):void 0,a=t==="running"?"text-accent-success":t==="stopped"?"text-text-muted":t==="error"?"text-accent-error":"text-text-muted";return i.jsxs("div",{className:"space-y-2 text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"State:"}),i.jsx("span",{className:`font-medium ${a}`,children:t})]}),n&&n!=="undefined"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"URL:"}),i.jsx("a",{href:n,className:"text-accent-primary hover:underline",target:"_blank",rel:"noopener noreferrer",children:n})]}),r&&i.jsx("div",{className:"text-accent-error bg-accent-error/10 p-2 rounded",children:r})]})}const E8=E.memo(function({result:t,action:n}){let r;try{r=JSON.parse(t)}catch{return console.warn("BackgroundProcessView: failed to parse result JSON",t.slice(0,200)),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}return n==="logs"?N8(r):n==="list"?T8(r):n==="status"?A8(r):n==="start"||n==="stop"?L8(r):i.jsxs("div",{className:"space-y-2 text-xs",children:[i.jsxs("div",{className:"text-accent-warning",children:["Unknown action: ",n]}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})]})});function N8(e){const t=e.lines,n=e.hasMore,r=e.totalLines;return!t||t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic",children:"No log output"}):i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-mono whitespace-pre-wrap bg-bg-primary p-2 rounded max-h-[60vh] overflow-y-auto break-words",children:t.map((a,l)=>i.jsx("div",{className:a.stream==="stderr"?"text-accent-warning":"",children:a.content},l))}),n&&r!=null&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Showing ",t.length," of ",r," lines"]})]})}function T8(e){const t=e.processes,n=e.currentCount,r=e.maxPerSession;return!t||t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic",children:"No background processes"}):i.jsxs("div",{className:"space-y-2",children:[t.map(a=>i.jsx(a2,{process:a},a.id)),n!=null&&r!=null&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:[n," of ",r," slots used"]})]})}function A8(e){const t=e.process,n=e.uptime;return t?i.jsxs("div",{className:"space-y-2",children:[i.jsx(a2,{process:t}),n!=null&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Uptime: ",D8(n)]})]}):i.jsx("div",{className:"text-xs text-text-muted italic",children:"Process not found"})}function L8(e){const t=e.processId,n=e.name,r=e.pid,a=e.status,l=a==="running"?"text-accent-success":"text-text-muted";return i.jsxs("div",{className:"space-y-2 text-xs",children:[n&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"Name:"}),i.jsx("span",{className:"font-medium",children:n})]}),t&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"ID:"}),i.jsx("span",{className:"font-mono",children:t})]}),r!=null&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"PID:"}),i.jsx("span",{className:"font-mono",children:r})]}),a&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"Status:"}),i.jsx("span",{className:`font-medium ${l}`,children:a})]})]})}function a2({process:e}){const t=e.status==="running"?"text-accent-success":(e.status==="exited","text-text-muted");return i.jsxs("div",{className:"border border-border rounded p-2 space-y-1 text-xs",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"font-medium",children:e.name}),i.jsx("span",{className:`${t}`,children:e.status})]}),e.pid!=null&&i.jsxs("div",{className:"text-text-muted",children:["PID: ",i.jsx("span",{className:"font-mono",children:e.pid})]}),e.command&&i.jsx("div",{className:"text-text-muted font-mono truncate",children:e.command})]})}function D8(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}const R8=E.memo(function({result:t,action:n}){let r;try{r=JSON.parse(t)}catch{return i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}switch(n){case"list":return O8(r);case"switch":case"delete":return I8(r);default:return i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}});function O8(e){const t=e.workspaces??[];return t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic",children:"No workspaces found"}):i.jsxs("div",{className:"space-y-1 text-xs",children:[i.jsx("div",{className:"text-text-muted mb-1",children:"Workspaces:"}),t.map(n=>i.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[i.jsx("span",{className:n.active?"text-accent-success":"text-text-muted",children:n.active?"●":"○"}),i.jsx("span",{className:n.active?"text-text-primary font-medium":"text-text-secondary",children:n.name}),n.branch&&i.jsxs("span",{className:"text-text-muted",children:["· ",n.branch]}),n.active&&i.jsx("span",{className:"text-[10px] text-accent-primary",children:"(current)"})]},n.name))]})}function lp({label:e,value:t,mono:n}){return i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-text-muted",children:[e,":"]}),i.jsx("span",{className:n?"font-mono text-accent-primary":"text-text-primary",children:t})]})}function I8(e){return i.jsxs("div",{className:"space-y-2 text-xs",children:[e.message&&i.jsx("div",{className:"text-text-primary",children:e.message}),e.workspace&&i.jsx(lp,{label:"Name",value:e.workspace,mono:!0}),e.path&&i.jsx(lp,{label:"Path",value:e.path,mono:!0}),e.branch&&i.jsx(lp,{label:"Branch",value:e.branch,mono:!0})]})}function M8(e){switch(e){case"sensitive_file":return{title:"Sensitive File Access",description:"Accessing files that may contain secrets"};case"both":return{title:"Sensitive File Access",description:"Accessing sensitive files outside project"};case"dangerous_command":return{title:"Dangerous Command",description:"Running potentially dangerous command"};case"git_no_verify":return{title:"Git --no-verify",description:"Bypassing git hooks/pre-commit checks"};case"outside_workdir":default:return{title:"Path Access Request",description:"Accessing paths outside project directory"}}}function P8({confirmation:e}){const t=Le(m=>m.confirmPath),n=Le(m=>m.currentSession),r=Le(m=>m.switchDangerLevel),{title:a,description:l}=M8(e.reason),u=e.reason==="sensitive_file"||e.reason==="both",c=u?"border-red-500/50":"border-amber-500/50",d=u?"bg-red-500/10":"bg-amber-500/10",h=e.reason==="git_no_verify",p=()=>{n!=null&&n.id&&r("dangerous"),t(e.callId,!0,!1)};return i.jsxs("div",{className:`border ${c} ${d} rounded p-3 my-2`,children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(yp,{}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:`text-sm font-medium ${u?"text-red-400":"text-amber-400"}`,children:a}),i.jsx("div",{className:"text-xs text-text-muted",children:l})]})]}),i.jsxs("div",{className:"text-xs text-text-muted mb-2",children:[i.jsx("span",{className:"font-medium",children:e.tool})," wants to access:"]}),i.jsx("div",{className:"bg-bg-primary rounded p-2 mb-3 max-h-24 overflow-y-auto",children:i.jsx("ul",{className:"space-y-0.5",children:e.paths.map((m,x)=>i.jsx("li",{className:`text-xs font-mono ${u?"text-red-300":"text-amber-300"} break-all`,children:m},x))})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>t(e.callId,!1),className:"flex-1 px-3 py-1.5 text-xs font-medium rounded bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border transition-colors",children:"Deny"}),i.jsx("button",{onClick:()=>t(e.callId,!0,!1),className:"flex-1 px-3 py-1.5 text-xs font-medium rounded bg-accent-primary hover:bg-accent-primary/80 text-text-primary transition-colors",children:"Allow"}),i.jsx("button",{onClick:p,className:`flex-1 px-3 py-1.5 text-xs font-medium rounded transition-colors ${h?"hidden":"bg-red-600 hover:bg-red-700 text-white"}`,title:"Enable dangerous mode and allow this request",children:"Allow Everything"})]})]})}function B8(e,t){if(e==="read_file"){const r=String(t.path??""),a=t.offset,l=t.limit,u=[];return a!==void 0&&a!==1&&u.push(`offset=${a}`),l!==void 0&&u.push(`limit=${l}`),u.length>0?`${r} [${u.join(", ")}]`:r}if(e==="write_file"||e==="edit_file")return String(t.path??"");if(e==="run_command"||e==="bash")return String(t.command??"");if(e==="return_value"){const r=String(t.content??"");return r.length>60?r.slice(0,60)+"...":r}if(e==="call_sub_agent")return String(t.subAgentType??"");if(e==="load_skill")return String(t.skillId??"");if(e==="web_fetch")return String(t.url??"");if(e==="web_search"){const r=String(t.query??"");return r.length>60?r.slice(0,57)+"...":r}if(e==="dev_server")return String(t.action??"");if(e==="background_process"){const r=String(t.action??""),a=t.name?String(t.name):"";return a?`${r}: ${a}`:r}if(e==="mcp_config")return String(t.action??"");const n=JSON.stringify(t);return n.length>50?n.slice(0,50)+"...":n}function BS(e,t,n){var a;const r=B8(e,t);if(e==="read_file"&&n){const l=n.format,u=n.pageCount;if(l==="pdf"&&u!=null)return`${r} (PDF, ${u}p)`;if(l==="image")return`${r} (image)`}if(e==="web_fetch"&&n){const l=n.contentType;if(l){const u=((a=l.split(";")[0])==null?void 0:a.trim())??"";if(u&&u!=="text/html")return`${r} (${u})`}}return r}function $8(e){return JSON.stringify(e,null,2)}const z8={pending:{icon:"●",color:"text-accent-warning",animate:!0},success:{icon:"✓",color:"text-accent-success",animate:!1},error:{icon:"✗",color:"text-accent-error",animate:!1},interrupted:{icon:"✗",color:"text-text-tool-error",animate:!1}},H8=E.memo(function({tool:t,args:n,status:r,variant:a="compact",forceCompact:l,result:u,error:c,durationMs:d,diagnostics:h,editContext:p,startedAt:m,streamingOutput:x,metadata:y,truncated:w,callId:C}){var L;const _=!l,[S,v]=E.useState(_),b=z8[r],j=Ft(O=>O.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",N=t==="edit_file"?(L=p==null?void 0:p.regions[0])==null?void 0:L.startLine:t==="read_file"?(()=>{const O=u==null?void 0:u.split(`
299
- `)[0],M=O==null?void 0:O.match(/^(\d+): /);return M?parseInt(M[1],10):void 0})():void 0,T=Le(O=>O.pendingPathConfirmations),D=C?T.find(O=>O.callId===C||O.callId.startsWith(C+"-"))??null:null;return t==="step_done"?i.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-secondary border border-border rounded px-2 py-1.5 my-1",children:[i.jsx("span",{className:`${b.color} ${b.animate?"animate-pulse":""}`,children:b.icon}),i.jsx("span",{className:"font-mono text-accent-primary text-sm",children:t})]}):a==="compact"?i.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-secondary rounded px-2 py-1.5",children:[i.jsx(i2,{tool:t}),i.jsx("span",{className:"text-accent-primary font-medium",children:t}),i.jsx("span",{className:"text-text-muted truncate flex-1",children:BS(t,n,y)}),i.jsx("span",{className:`${b.color} ${b.animate?"animate-pulse":""}`,children:r==="pending"?"...":"done"})]}):i.jsxs("div",{className:"border border-border rounded overflow-hidden my-1 min-w-0",children:[i.jsxs("button",{className:"w-full flex items-center gap-1.5 p-2 bg-secondary hover:bg-secondary/80 text-left",onClick:()=>v(!S),children:[i.jsx("span",{className:`${b.color} ${b.animate?"animate-pulse":""}`,children:b.icon}),i.jsx("span",{className:"font-mono text-accent-primary text-sm",children:t}),i.jsx("span",{className:"text-text-muted text-xs flex-1 truncate",children:BS(t,n,y)}),i.jsx("span",{className:"text-text-muted text-xs",children:S?"▼":"▶"})]}),S&&i.jsxs("div",{className:"p-2 bg-primary border-t border-border space-y-2 min-w-0",children:[t==="run_command"&&i.jsx(w8,{command:String(n.command??""),timeout:n.timeout??12e4,startedAt:m,streamingOutput:x,status:r,result:u,error:c,durationMs:d}),t==="edit_file"&&r==="success"&&i.jsxs(i.Fragment,{children:[p&&p.regions.length>0?i.jsx(d8,{regions:p.regions,filePath:String(n.path??"")}):i.jsx(c8,{oldString:String(n.old_string??""),newString:String(n.new_string??""),filePath:String(n.path??"")}),h&&h.length>0&&i.jsx(PS,{diagnostics:h})]}),t==="write_file"&&r==="success"&&i.jsxs(i.Fragment,{children:[i.jsx(u8,{content:String(n.content??""),filePath:String(n.path??"")}),h&&h.length>0&&i.jsx(PS,{diagnostics:h})]}),t==="read_file"&&r==="success"&&i.jsx(p8,{result:u,metadata:y,filePath:String(n.path??"")}),t==="return_value"&&(()=>{const O=(x==null?void 0:x.map(W=>W.content).join(""))??"",M=r==="pending"&&O?O:String(n.content??"");return i.jsxs("div",{children:[i.jsx("div",{className:"text-[10px] text-accent-primary font-medium mb-1 uppercase tracking-wide",children:"Sub-Agent Summary"}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none",children:i.jsx(zn,{content:M})})]})})(),t==="call_sub_agent"&&i.jsxs("div",{children:[i.jsxs("div",{className:"text-[10px] text-accent-primary font-medium mb-1 uppercase tracking-wide",children:[String(n.subAgentType??"Sub-Agent")," Prompt"]}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:String(n.prompt??"")})})]}),t==="web_search"&&r==="success"&&i.jsxs("div",{children:[i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{className:"mt-1"})]}),t==="load_skill"&&r==="success"&&i.jsxs("div",{children:[i.jsxs("div",{className:"text-[10px] text-accent-primary font-medium mb-1 uppercase tracking-wide",children:["Skill: ",String(n.skillId??"")]}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{className:"mt-1"})]}),t==="web_fetch"&&r==="success"&&i.jsxs("div",{className:"space-y-2",children:[!!(y!=null&&y.url)&&i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[i.jsx("span",{children:"Source:"}),i.jsx("a",{href:String(y.url),className:"text-accent-primary hover:underline truncate",target:"_blank",rel:"noopener noreferrer",children:String(y.url)}),!!(y!=null&&y.contentType)&&i.jsxs("span",{className:"text-text-muted flex-shrink-0",children:["(",String(y.contentType),")"]}),(y==null?void 0:y.pageCount)!=null&&i.jsxs("span",{className:"text-text-muted flex-shrink-0",children:["· ",String(y.pageCount)," pages"]})]}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{})]}),t==="dev_server"&&r==="success"&&u&&i.jsx(C8,{result:u,action:String(n.action??"")}),t==="workspace"&&r==="success"&&u&&i.jsx(R8,{result:u,action:String(n.action??"")}),t==="background_process"&&r==="success"&&u&&i.jsx(E8,{result:u,action:String(n.action??"")}),t==="mcp_config"&&r==="success"&&i.jsxs("div",{children:[i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{className:"mt-1"})]}),t==="step_done"&&null,t!=="edit_file"&&t!=="write_file"&&t!=="run_command"&&t!=="read_file"&&t!=="return_value"&&t!=="call_sub_agent"&&t!=="web_search"&&t!=="load_skill"&&t!=="web_fetch"&&t!=="dev_server"&&t!=="workspace"&&t!=="background_process"&&t!=="mcp_config"&&t!=="step_done"&&i.jsxs(i.Fragment,{children:[Object.keys(n).length>0&&i.jsxs("div",{children:[i.jsx("div",{className:"text-[10px] text-text-muted mb-0.5",children:"Arguments:"}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto break-words",children:$8(n)})]}),r==="success"&&u!==void 0&&i.jsxs("div",{children:[i.jsxs("div",{className:"text-[10px] text-text-muted mb-0.5",children:["Result",d!==void 0&&` (${d}ms)`,":"]}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:u||"No output"}),w&&i.jsx(bl,{className:"mt-1"})]})]}),r==="success"&&(t==="edit_file"||t==="write_file"||t==="read_file")&&d!==void 0&&i.jsxs("div",{className:"text-[10px] text-text-muted flex items-center gap-2",children:[i.jsxs("span",{children:["Completed in ",d,"ms"]}),j&&(t==="read_file"||t==="write_file"||t==="edit_file")&&String((y==null?void 0:y.path)??n.path??"")&&i.jsx("a",{href:Xk(String((y==null?void 0:y.path)??n.path),N),className:"text-accent-primary hover:underline ml-auto",children:"Open in VSCode"})]}),r==="error"&&c&&t!=="run_command"&&i.jsxs("div",{children:[i.jsx("div",{className:"text-[10px] text-accent-error mb-0.5",children:"Error:"}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded text-accent-error break-words",children:c})]}),D&&i.jsx(P8,{confirmation:D})]})]})}),U8={read_file:"Reading file",write_file:"Writing file",edit_file:"Editing file",run_command:"Running command",glob:"Searching files",grep:"Searching content",ask_user:"Asking user",criterion:"Managing criterion",session_metadata:"Managing",todo_write:"Updating tasks"};function F8(e,t){const n=U8[e];if(!n)return`Preparing ${e}`;if(e==="session_metadata"&&t)try{const a=JSON.parse(t).key;if(a){const l=EB(a);return`${n} ${l}`}}catch{}return n}function V8(e){try{const t=e.replace(/\s*\}\s*$/,""),n=JSON.parse(t);if(typeof n.command=="string")return n.command}catch{const t=e.match(/"command"\s*:\s*"([^"]*)/);if(t&&t[1])return t[1]}return null}const G8=E.memo(function({name:t,arguments:n}){let a=F8(t,n)+"...";if(t==="run_command"&&n){const l=V8(n);l&&(a=l)}return i.jsx("div",{className:"border border-border rounded overflow-hidden my-1 min-w-0 animate-pulse",children:i.jsxs("div",{className:"flex items-center gap-1.5 p-2 bg-bg-tertiary",children:[i.jsx("span",{className:"text-accent-warning animate-pulse",children:"..."}),i.jsx(i2,{tool:t}),i.jsx("span",{className:"font-mono text-accent-primary text-sm",children:t}),t==="run_command"&&n?i.jsx("code",{className:"text-text-muted text-xs flex-1 truncate",children:a}):i.jsx("span",{className:"text-text-muted text-xs flex-1",children:a})]})})}),W8={pending:{icon:"○",color:"text-text-muted"},in_progress:{icon:"●",color:"text-accent-warning",animate:!0},completed:{icon:"✓",color:"text-accent-success"}},q8=E.memo(function({todos:t}){return Array.isArray(t)?t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic my-1",children:"No tasks"}):i.jsxs("div",{className:"my-1 rounded border border-border bg-bg-tertiary overflow-hidden",children:[i.jsx("div",{className:"px-2 py-1.5 border-b border-border bg-bg-secondary",children:i.jsx("span",{className:"text-xs font-medium text-text-muted",children:"Tasks"})}),i.jsx("div",{children:t.map((n,r)=>{const a=W8[n.status];return i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${r>0?"border-t border-border":""}`,children:[i.jsx("span",{className:`${(a==null?void 0:a.color)??"text-text-muted"} ${a!=null&&a.animate?"animate-pulse":""} text-sm leading-tight`,children:(a==null?void 0:a.icon)??"○"}),i.jsx("span",{className:`text-sm leading-tight ${n.status==="completed"?"text-text-muted":"text-text-primary"}`,children:n.content})]},r)})})]}):i.jsx("div",{className:"text-xs text-accent-warning italic my-1",children:"⚠️ Invalid todos data"})});function K8({toolCall:e}){var j;const t=Le(N=>N.pendingQuestions),n=Le(N=>N.answerQuestion),[r,a]=E.useState(""),l=E.useRef(null),u=E.useRef(null),c=t.find(N=>N.callId===e.id),d=e.arguments.question??(c==null?void 0:c.question)??"",h=e.arguments.type??(c==null?void 0:c.type)??"text",p=e.arguments.options??(c==null?void 0:c.options)??void 0,m=e.result!==void 0,x=c!==void 0&&!m,y=((j=e.result)==null?void 0:j.output)??"",w=y==="[user skipped]";E.useEffect(()=>{x&&l.current&&l.current.focus()},[x]),E.useEffect(()=>{x&&u.current&&u.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]);const C=E.useCallback(()=>{c&&n(c.callId,r)},[c,r,n]),_=E.useCallback(()=>{c&&n(c.callId,"",!0)},[c,n]),S=E.useCallback(N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),C()),N.key==="Escape"&&!N.shiftKey&&(N.preventDefault(),_())},[C,_]),v=E.useCallback(N=>{c&&n(c.callId,N)},[c,n]),b="px-3 py-1.5 text-xs font-medium rounded transition-colors";return i.jsxs("div",{ref:u,className:"my-1",children:[i.jsx("div",{className:"text-sm text-text-primary",children:d}),x&&i.jsx("div",{className:"mt-2 border border-border rounded overflow-hidden",children:i.jsx("div",{className:"p-3 bg-primary space-y-2",children:h==="confirm"?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>v("yes"),className:`${b} flex-1 bg-accent-success/20 hover:bg-accent-success/30 text-accent-success border border-accent-success/30`,children:"Yes"}),i.jsx("button",{onClick:()=>v("no"),className:`${b} flex-1 bg-accent-error/20 hover:bg-accent-error/30 text-accent-error border border-accent-error/30`,children:"No"}),i.jsx("button",{onClick:_,className:`${b} bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border`,children:"Skip"})]}):h==="choice"&&Array.isArray(p)&&p.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(N=>i.jsx("button",{onClick:()=>v(N),className:`${b} text-left w-full bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary border border-border hover:border-accent-primary/50`,children:N},N))}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("textarea",{ref:l,value:r,onChange:N=>a(N.target.value),onKeyDown:S,placeholder:"Or type your own answer... (Enter to submit)",className:"flex-1 min-h-[36px] max-h-[80px] px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 resize-y",rows:1}),i.jsx("button",{onClick:C,disabled:!r.trim(),className:`${b} bg-accent-primary/25 hover:bg-accent-primary/40 text-text-primary disabled:opacity-50 disabled:cursor-not-allowed`,children:"Send"}),i.jsx("button",{onClick:_,className:`${b} bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border`,children:"Skip"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("textarea",{ref:l,value:r,onChange:N=>a(N.target.value),onKeyDown:S,placeholder:"Type your answer here... (Enter to submit, Shift+Enter for new line)",className:"w-full min-h-[80px] px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 resize-y",autoFocus:!0}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{onClick:_,className:`${b} bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border`,children:"Skip"}),i.jsx("button",{onClick:C,disabled:!r.trim(),className:`${b} bg-accent-primary/25 hover:bg-accent-primary/40 text-text-primary disabled:opacity-50 disabled:cursor-not-allowed`,children:"Send Answer"})]})]})})}),m&&i.jsx("div",{className:"mt-1 flex items-center gap-2",children:i.jsx("span",{className:`text-xs ${w?"text-amber-400":"text-accent-success"}`,children:w?"Skipped":`Answered: ${y}`})})]})}const $S={add:{icon:"○",color:"text-text-muted"},update:{icon:"○",color:"text-text-muted"},remove:{icon:"○",color:"text-text-muted"},complete:{icon:"◉",color:"text-purple-400"},pass:{icon:"✓",color:"text-accent-success"},fail:{icon:"✗",color:"text-accent-error"},get:{icon:"○",color:"text-text-muted"},list:{icon:"○",color:"text-text-muted"},schema:{icon:"○",color:"text-text-muted"}},Y8=E.memo(function({toolCalls:t,criteria:n}){if(t.length===0)return null;const r=new Map((n==null?void 0:n.map(c=>[c.id,c]))??[]),a=t.find(c=>{var d,h;return c.arguments.action==="get"&&((d=c.result)==null?void 0:d.success)&&((h=c.result)==null?void 0:h.output)}),l=t.some(c=>c.name==="session_metadata"),u=(()=>{if(!l)return"Acceptance Criteria";const c=new Set(t.map(d=>d.arguments.key).filter(Boolean));if(c.size===1){const d=c.values().next().value;return d?so(d):"Session Data"}return"Session Data"})();return i.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[i.jsx("div",{className:"px-2 py-1.5 border-b border-border bg-secondary",children:i.jsx("span",{className:"text-xs font-medium text-text-muted",children:u})}),i.jsx("div",{className:"bg-primary",children:a?(()=>{const c=a.result.output;if(c==="No criteria defined yet.")return i.jsxs("div",{className:"flex items-start gap-2 px-2 py-1.5",children:[i.jsx("span",{className:"text-text-muted text-sm leading-tight flex-shrink-0",children:"○"}),i.jsx("div",{className:"flex-1 min-w-0 text-text-muted text-sm",children:"No criteria defined yet."})]});try{return JSON.parse(c).map((h,p)=>i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${p>0?"border-t border-border":""}`,children:[i.jsx("span",{className:"text-text-muted text-sm leading-tight flex-shrink-0",children:"○"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx(zn,{content:`[${h.id}] ${h.description}`})})]},h.id??p))}catch{return t.map((d,h)=>i.jsx(zS,{tc:d,index:h,criteriaMap:r},d.id??h))}})():t.map((c,d)=>i.jsx(zS,{tc:c,index:d,criteriaMap:r},c.id??d))})]})});function zS({tc:e,index:t,criteriaMap:n}){const r=e.arguments.action,a=e.arguments,l=e.name==="session_metadata",u=r==="remove",c=a.id,d=a.description,h=c?n.get(c):void 0,p=d??(h==null?void 0:h.description)??(u&&c?`[${c}]`:"Criterion updated"),m=a.reason,x=r==="fail";return i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${t>0?"border-t border-border":""}`,children:[l?i.jsx(xo,{status:a.status,className:"text-sm leading-tight flex-shrink-0"}):(()=>{const y=r&&$S[r]?$S[r]:{icon:"○",color:"text-text-muted"};return i.jsx("span",{className:`${y.color} text-sm leading-tight flex-shrink-0`,children:y.icon})})(),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:u?"line-through text-text-muted":"",children:i.jsx(zn,{content:p})}),m&&i.jsxs("div",{className:`mt-1 text-sm ${x?"text-accent-error":"text-text-muted"}`,children:[i.jsx("span",{className:"text-text-muted",children:"└ "}),'"',m,'"']})]})]})}function X8(e){return e==="criterion"||e==="session_metadata"}async function o2(e){if(navigator.clipboard){await navigator.clipboard.writeText(e);return}const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}function Q8({items:e,position:t,onClose:n}){const r=E.useRef(null),[a,l]=E.useState(-1);if(E.useEffect(()=>{t&&l(-1)},[t]),E.useEffect(()=>{var p;if(!t)return;function d(m){r.current&&!r.current.contains(m.target)&&n()}function h(m){var x;switch(m.key){case"Escape":m.preventDefault(),n();break;case"ArrowDown":m.preventDefault(),l(y=>y<e.length-1?y+1:0);break;case"ArrowUp":m.preventDefault(),l(y=>y>0?y-1:e.length-1);break;case"Enter":m.preventDefault(),(x=e[a])==null||x.onClick(),n();break}}return document.addEventListener("mousedown",d),window.addEventListener("keydown",h,!0),window.addEventListener("blur",n),(p=r.current)==null||p.focus(),()=>{document.removeEventListener("mousedown",d),window.removeEventListener("keydown",h,!0),window.removeEventListener("blur",n)}},[t,e,a,n]),!t)return null;let u=Math.min(t.x,window.innerWidth-190),c=Math.min(t.y,window.innerHeight-100);return u=Math.max(8,u),c=Math.max(8,c),mi.createPortal(i.jsx("div",{ref:r,tabIndex:-1,className:"fixed bg-bg-secondary border border-border rounded shadow-lg z-50 min-w-[160px] outline-none",style:{left:u,top:c},children:i.jsx("div",{className:"max-h-[60vh] overflow-y-auto",onMouseLeave:()=>l(-1),children:e.map((d,h)=>i.jsxs("button",{onClick:()=>{d.onClick(),n()},onMouseEnter:()=>l(h),className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${h<e.length-1?"border-b border-border":""} ${d.danger?"text-accent-error hover:bg-accent-error/10":h===a?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"}`,children:[d.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0",children:d.icon}),d.label]},h))})}),document.body)}function l2(){const[e,t]=E.useState(null);return{onContextMenu:E.useCallback((a,l)=>{var u;l&&((u=window.getSelection())!=null&&u.toString()||(a.preventDefault(),t({x:a.clientX,y:a.clientY})))},[]),contextMenu:a=>i.jsx(Q8,{position:e,onClose:()=>t(null),items:a})}}function J8(e){const t=[];let n=[];const r=()=>{n.length>0&&(t.push({type:"criteria_group",toolCalls:n}),n=[])};for(const a of e)a.type==="tool_call"&&X8(a.toolCall.name)?n.push(a.toolCall):(r(),t.push(a));return r(),t}function Z8(e,t){if(e.segments&&e.segments.length>0)return e$(e.segments,e.toolCalls??[],e.preparingToolCalls??[],e.stats,t);const n=[];if(e.thinkingContent&&n.push({type:"thinking",content:e.thinkingContent}),e.content&&n.push({type:"text",content:e.content}),e.toolCalls)for(const r of e.toolCalls)n.push({type:"tool_call",toolCall:r});if(e.preparingToolCalls)for(const r of e.preparingToolCalls)n.push({type:"preparing_tool_call",preparing:r});return t&&e.stats&&n.push({type:"stats",stats:e.stats}),n}function e$(e,t,n,r,a){const l=[],u=new Map(t.map(c=>[c.id,c]));for(const c of e)switch(c.type){case"text":l.push({type:"text",content:c.content});break;case"thinking":c.content&&c.content.trim().length>0&&l.push({type:"thinking",content:c.content});break;case"tool_call":{const d=u.get(c.toolCallId);d&&l.push({type:"tool_call",toolCall:d});break}}for(const c of n)l.push({type:"preparing_tool_call",preparing:c});return a&&r&&l.push({type:"stats",stats:r}),l}const tx=E.memo(function({message:t,showStats:n=!0,showThinking:r=!0,showVerboseToolOutput:a=!0,sessionId:l}){const u=Le(T=>{var D,L;return(L=(D=T.currentSession)==null?void 0:D.metadataEntries)==null?void 0:L.criteria}),c=xt(T=>T.defaults),d=xt(T=>T.userItems),h=[...c,...d],p=Z8(t,n),m=r?p:p.filter(T=>T.type!=="thinking"),x=J8(m),[y,w]=E.useState(!1),[C,_]=E.useState(null),[,S]=Tn(),{onContextMenu:v,contextMenu:b}=l2();if(x.length===0)return null;const j=()=>{o2(t.content)},N=async()=>{if(!l||y)return;w(!0),_(null);const T=await p1(l,t.id);w(!1),T!=null&&T.session?S(`/p/${T.session.projectId}/s/${T.session.id}`):_("Failed to fork session")};return i.jsxs("div",{className:"feed-item",onContextMenu:T=>v(T,!!l),children:[i.jsxs("div",{className:"min-w-0",children:[C&&i.jsx("p",{className:"text-xs text-accent-error mb-1 ml-0.5",children:C}),x.map((T,D)=>{var L;switch(T.type){case"thinking":return i.jsx(_8,{content:T.content},D);case"text":return i.jsx("div",{className:"prose prose-sm prose-invert max-w-none",children:i.jsx(zn,{content:T.content})},D);case"preparing_tool_call":return i.jsx(G8,{name:T.preparing.name,arguments:T.preparing.arguments},`preparing-${T.preparing.index}`);case"tool_call":{const O=T.toolCall,M=O.result;if(O.name==="ask_user")return i.jsx(K8,{toolCall:O},D);if(O.name==="todo_write"){const R=O.arguments.todos,H=Array.isArray(R)?R:[];return i.jsx(q8,{todos:H},D)}const W=(L=M==null?void 0:M.output)==null?void 0:L.includes("[interrupted by user]"),U=M?W?"interrupted":M.success?"success":"error":"pending";return i.jsx(H8,{tool:O.name,args:O.arguments,status:U,variant:"expandable",forceCompact:!a,result:M==null?void 0:M.output,error:M==null?void 0:M.error,durationMs:M==null?void 0:M.durationMs,diagnostics:M==null?void 0:M.diagnostics,editContext:M==null?void 0:M.editContext,startedAt:O.startedAt,streamingOutput:O.streamingOutput,metadata:M==null?void 0:M.metadata,truncated:(M==null?void 0:M.truncated)??!1,callId:O.id},D)}case"criteria_group":return i.jsx(Y8,{toolCalls:T.toolCalls,criteria:u},D);case"stats":{const O=T.stats;if(!O||"error"in O)return null;const M=O.model.split("/").pop()??O.model,W=Vl(h,O.mode),U=h.find(V=>V.id===O.mode),R=(U==null?void 0:U.name)??O.mode,H=V=>V>=1e3?`${(V/1e3).toFixed(1)}k`:V.toString(),G=V=>V>=1e3?`${(V/1e3).toFixed(1)}k`:V.toFixed(1);return i.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[10px] text-text-muted mt-3",children:[i.jsx("span",{className:"flex-1 h-px bg-border"}),i.jsx("span",{className:"text-text-secondary",children:M}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("span",{style:{color:W},children:R}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("span",{children:Yr(O.totalTime)}),O.toolTime>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsxs("span",{children:[Yr(O.toolTime)," tools"]})]}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsxs("span",{children:[H(O.prefillTokens)," @ ",G(O.prefillSpeed)," pp"]}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsxs("span",{children:[H(O.generationTokens)," @ ",G(O.generationSpeed)," tg"]}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("button",{type:"button",className:"text-text-muted hover:text-text-secondary transition-colors",title:"View detailed stats",onClick:()=>{const V=new CustomEvent("open-turn-stats",{detail:{stats:O}});window.dispatchEvent(V)},children:i.jsx(ag,{className:"w-3 h-3"})}),i.jsx("span",{className:"flex-1 h-px bg-border"})]},D)}}}),t.partial&&i.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-accent-warning mt-1",children:[i.jsx(yp,{}),i.jsx("span",{children:"Aborted"})]}),t.completeReason==="truncated"&&i.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-text-truncated mt-1",children:[i.jsx(yp,{}),i.jsx("span",{children:"Response was truncated — the model ran out of output tokens."})]})]}),b([{label:"Copy",icon:i.jsx(Rl,{className:"w-4 h-4"}),onClick:()=>j()},{label:"Fork session from here",icon:i.jsx(Ki,{className:"w-4 h-4"}),onClick:()=>void N()}])]})});function vd(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n},${r},${a},${t})`}function t$(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}const n$=E.memo(function({data:t}){var u;const n=vt(c=>c.defaults),r=vt(c=>c.userItems),l=((u=[...n,...r].find(c=>c.id===t.workflowId))==null?void 0:u.color)??t.workflowColor??"#8b949e";return i.jsxs("div",{"data-testid":"task-completed-card",className:"feed-item rounded p-3 border",style:{borderColor:vd(l,.3),backgroundColor:vd(l,.08)},children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(fT,{color:l}),i.jsx("span",{className:"text-sm font-medium",style:{color:l},children:t.workflowName??"Task Completed"})]}),i.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-5 gap-2",children:[i.jsx(vl,{label:"Iterations",value:String(t.iterations)}),i.jsx(vl,{label:"Total time",value:Yr(t.totalTimeSeconds)}),i.jsx(vl,{label:"Tool calls",value:String(t.totalToolCalls)}),i.jsx(vl,{label:"Tokens",value:t$(t.totalTokensGenerated)}),i.jsx(vl,{label:"Speed",value:t.avgGenerationSpeed>0?`${t.avgGenerationSpeed} tok/s`:"-"})]})]})});function vl({label:e,value:t}){return i.jsxs("div",{className:"bg-bg-primary/50 rounded px-2 py-1",children:[i.jsx("div",{className:"text-sm text-text-muted",children:e}),i.jsx("div",{className:"text-sm text-text-primary font-medium",children:t})]})}const r$=E.memo(function({data:t}){var u;const n=vt(c=>c.defaults),r=vt(c=>c.userItems),l=((u=[...n,...r].find(c=>c.id===t.workflowId))==null?void 0:u.color)??t.workflowColor??"#6b7280";return i.jsxs("div",{className:"feed-item flex items-center gap-2 px-3 py-2 rounded border",style:{borderColor:vd(l,.3),backgroundColor:vd(l,.08)},children:[i.jsx(A1,{className:"w-3 h-3 shrink-0",color:l}),i.jsx("span",{className:"text-sm font-medium",style:{color:l},children:t.workflowName}),i.jsx("span",{className:"text-text-muted text-sm",children:"started"})]})}),s$=["text/"],i$=["application/json","application/xml","application/yaml","application/x-yaml","application/javascript","application/xhtml+xml","application/x-sh","image/svg+xml"];function Yu(e){return e.startsWith("image/")}function c2(e){return e.startsWith("image/")&&e!=="image/svg+xml"}function nx(e){return i$.includes(e)||s$.some(t=>e.startsWith(t))}function Za(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function u2(e){const t=e.lastIndexOf(".");return t<=0||t>=e.length-1?"FILE":e.slice(t+1).toUpperCase()}const a$={"text/plain":"txt","text/csv":"csv","text/html":"html","text/markdown":"md","text/javascript":"js","text/xml":"xml","text/x-yaml":"yaml","text/x-sh":"sh","text/tab-separated-values":"tsv","text/x-python":"py","text/x-java-source":"java","text/x-json":"json","text/x-typescript":"ts","text/css":"css","application/json":"json","application/xml":"xml","application/yaml":"yaml","application/x-yaml":"yaml","application/javascript":"js","application/xhtml+xml":"xhtml","application/x-sh":"sh","application/pdf":"pdf","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp","image/svg+xml":"svg"};function o$(e){var t;return a$[e]||((t=e.split("/")[1])==null?void 0:t.split("+")[0])||"file"}function l$(e){return Yu(e)||nx(e)||e==="application/pdf"}function c$({attachments:e,messageId:t}){const[n,r]=E.useState(null),a=Le(p=>p.visionFallbackByMessage),l=Le(p=>p.messages),u=E.useMemo(()=>{const p=l.findIndex(m=>m.id===t);if(p===-1)return null;for(let m=p+1;m<l.length;m++){const x=l[m];if(x&&x.role==="assistant")return x.id}return null},[l,t]),c=p=>{r(p)},d=()=>{r(null)},h=p=>{const m=`${t}-${p}`;if(a[m])return a[m];if(u){const x=`${u}-${p}`;return a[x]}return null};return e.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:e.map(p=>{const m=h(p.id);return c2(p.mimeType)?i.jsxs("div",{className:"relative inline-block",children:[i.jsxs("button",{onClick:()=>c(p.data),className:"group relative inline-block",title:(m==null?void 0:m.type)==="done"&&m.description||p.description||p.filename,disabled:(m==null?void 0:m.type)==="start",children:[i.jsx("img",{src:p.data,alt:(m==null?void 0:m.type)==="done"&&m.description||p.description||p.filename,className:"max-w-[256px] max-h-[256px] object-contain rounded-lg border border-border hover:border-accent-primary transition-colors cursor-pointer"}),(m==null?void 0:m.type)==="start"&&i.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center rounded-lg",children:i.jsx("span",{className:"text-xs text-text-primary animate-pulse",children:"Describing image..."})})]}),(m==null?void 0:m.type)==="done"&&m.description&&i.jsxs("div",{className:"mt-2 p-2 bg-bg-tertiary rounded text-xs text-text-secondary max-w-[256px]",children:[m.description.slice(0,200),m.description.length>200?"...":""]})]},p.id):i.jsxs("div",{className:"inline-flex items-start gap-3 p-3 bg-bg-tertiary rounded-lg border border-border max-w-[300px]",children:[i.jsx("div",{className:"w-10 h-10 flex items-center justify-center rounded-md bg-bg-secondary text-sm font-bold text-text-muted shrink-0",children:u2(p.filename)}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"text-xs text-text-primary truncate font-medium",title:p.filename,children:p.filename}),i.jsx("div",{className:"text-[10px] text-text-muted",children:Za(p.size)}),nx(p.mimeType)&&p.data&&i.jsxs("div",{className:"mt-1.5 text-[10px] text-text-muted leading-relaxed line-clamp-3 font-mono break-all",children:[p.data.slice(0,200),p.data.length>200?"...":""]})]})]},p.id)})}),n&&i.jsx(r2,{src:n,alt:"Attached image",isOpen:!0,onClose:d})]})}function u$({message:e}){const[t,n]=E.useState(!1);if(e.messageKind!=="auto-prompt")return null;const r=e.metadata,a=(r==null?void 0:r.color)??"#6b7280",l=(r==null?void 0:r.type)??"agent",u=l==="workspace"?"Workspace":(r==null?void 0:r.name)??"Agent",d={agent:(r==null?void 0:r.kind)==="reminder"?"reminder":"definition injected",workflow:"instructions",compaction:"prompt injected",subagent:"instructions",workspace:`${(r==null?void 0:r.workspaceName)??""} · ${(r==null?void 0:r.branchName)??""}`,branch:`🌿 ${(r==null?void 0:r.branchName)??""}`}[l]??"injected",h=l==="workflow"||l==="subagent";return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[10px] text-text-muted font-mono mt-3 mb-4",children:[i.jsx("span",{className:"flex-1 h-px bg-border"}),i.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${h?"":"cursor-pointer"}`,style:{backgroundColor:a},onClick:()=>!h&&n(!0)}),i.jsx("span",{className:h?"":"cursor-pointer hover:text-text-secondary transition-colors",style:{color:a},onClick:()=>!h&&n(!0),children:u}),i.jsx("span",{children:"·"}),i.jsx("span",{className:h?"":"cursor-pointer hover:text-text-secondary transition-colors",onClick:()=>!h&&n(!0),children:d}),i.jsx("span",{className:"flex-1 h-px bg-border"})]}),h&&i.jsx("div",{className:"flex justify-center feed-item mb-4",children:i.jsx("div",{className:"max-w-[75%] rounded p-3 bg-bg-tertiary/50 text-text-secondary text-sm overflow-x-auto",style:{borderLeft:`3px solid ${a}`},children:i.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs",children:e.content})})}),i.jsx(jt,{isOpen:t,onClose:()=>n(!1),title:`${u} Prompt`,size:"lg",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:a}}),i.jsx("span",{className:"text-sm text-text-primary font-medium",children:u}),i.jsxs("span",{className:"text-xs text-text-muted",children:["(",l,")"]})]}),i.jsx("div",{className:"h-full min-h-96",children:i.jsx("pre",{className:"text-sm text-text-secondary whitespace-pre-wrap break-words bg-bg-tertiary rounded p-4 h-full min-h-96 overflow-auto font-mono",children:e.content})})]})})]})}function d$({message:e,messageId:t,sessionId:n}){const r=e.messageKind==="auto-prompt",a=e.messageKind==="command",l=e.isSystemGenerated,u=Le($=>$.loadSession),[,c]=Tn(),[d,h]=E.useState(!1),[p,m]=E.useState(!1),[x,y]=E.useState(!1),[w,C]=E.useState(e.content),[_,S]=E.useState(!1),[v,b]=E.useState(!1),[j,N]=E.useState(null),[T,D]=E.useState(null),L=E.useRef(null),{onContextMenu:O,contextMenu:M}=l2(),W=E.useCallback(()=>{const $=L.current;$&&($.style.height="auto",$.style.height=`${$.scrollHeight}px`)},[]),U=async()=>{try{await o2(e.content),m(!0),window.setTimeout(()=>m(!1),1500)}catch{}},R=async()=>{if(!n||!t||v)return;b(!0),N(null);const $=await p1(n,t);if(b(!1),$!=null&&$.session){const I=$.session.projectId;c(`/p/${I}/s/${$.session.id}`)}else N("Failed to fork session")},H=async()=>{if(!n||!t||_)return;S(!0),D(null);const $=await y_(n,t);S(!1),$?u(n):D("Failed to replay")},G=async()=>{if(!n||!t||!w.trim()||_)return;S(!0),D(null);const $=await y_(n,t,w);S(!1),$?(u(n),y(!1)):D("Failed to send")},V=()=>{C(e.content),y(!1),D(null)},X=`flex items-center gap-0.5 self-end transition-[visibility,opacity] focus-within:visible focus-within:opacity-100 ${d&&!x&&!_?"visible opacity-100":"invisible opacity-0"}`;return i.jsxs("div",{className:"flex justify-end items-start gap-1.5 feed-item",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onContextMenu:$=>O($,!!n&&!!t),children:[!l&&i.jsxs("div",{className:X,children:[i.jsx("button",{onClick:()=>{U()},title:"Copy",disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",children:p?i.jsx(Mr,{className:"w-3.5 h-3.5 text-accent-success"}):i.jsx(Rl,{className:"w-3.5 h-3.5"})}),n&&t&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>{D(null),C(e.content),y(!0)},title:"Edit & resend",disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",children:i.jsx(j1,{className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>{H()},title:"Replay",disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",children:i.jsx(jd,{className:"w-3.5 h-3.5"})})]})]}),i.jsxs("div",{className:`max-w-[75%] ${x?"w-full":""} rounded p-2 ${l?"bg-bg-system border border-border-system":"bg-accent-primary/15 text-text-primary"}`,children:[l&&i.jsx("span",{className:"text-[10px] block mb-0.5 text-text-system",children:a?"Command":r?"Auto":"System"}),x?i.jsxs("div",{className:"flex flex-col gap-1.5",children:[i.jsx("textarea",{ref:$=>{L.current=$,$&&($.style.height="auto",$.style.height=`${$.scrollHeight}px`)},className:"w-full bg-bg-primary border border-border rounded p-1.5 text-sm text-text-primary resize-none focus:outline-none focus:border-accent-primary min-h-[60px] overflow-hidden disabled:opacity-50",value:w,onChange:$=>{C($.target.value),W()},onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),G()),$.key==="Escape"&&V()},disabled:_,autoFocus:!0}),T&&i.jsx("p",{className:"text-xs text-accent-error",children:T}),i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:V,disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",title:"Cancel",children:i.jsx(js,{className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>{G()},disabled:_||!w.trim(),className:"p-1 rounded hover:bg-bg-tertiary text-accent-primary hover:text-accent-primary disabled:opacity-50",title:"Confirm (Ctrl+Enter)",children:i.jsx(Mr,{className:"w-3.5 h-3.5"})})]})]}):i.jsxs(i.Fragment,{children:[(T||j)&&i.jsx("p",{className:"text-xs text-accent-error mb-1",children:T??j}),i.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${l?"text-text-system":""}`,children:e.content}),e.attachments&&e.attachments.length>0&&i.jsx(c$,{attachments:e.attachments,messageId:e.id})]})]}),M([{label:"Copy",icon:i.jsx(Rl,{className:"w-4 h-4"}),onClick:()=>void U()},{label:"Fork session from here",icon:i.jsx(Ki,{className:"w-4 h-4"}),onClick:()=>void R()}])]})}const d2=E.memo(function({message:t,isLastAssistantMessage:n=!1,messageId:r,sessionId:a}){const l=t.role==="user",u=t.role==="assistant",c=t.role==="system",d=t.role==="tool";if(u)return i.jsx(tx,{message:t,showStats:n});if(c&&t.isCompacted)return i.jsxs("div",{className:"feed-item bg-bg-tertiary/50 border border-border rounded p-2",children:[i.jsx("div",{className:"text-text-muted text-xs mb-0.5",children:"[Compacted]"}),i.jsx("div",{className:"text-text-secondary text-xs whitespace-pre-wrap",children:t.content.replace(`[COMPACTED HISTORY]
300
- `,"")})]});if(d)return i.jsxs("div",{className:"feed-item bg-bg-tertiary/30 border-l-2 border-accent-primary rounded-r p-2",children:[i.jsxs("div",{className:"text-accent-primary text-xs mb-0.5",children:["Tool: ",t.toolName]}),i.jsxs("pre",{className:"text-text-secondary text-xs whitespace-pre-wrap break-words overflow-x-auto max-h-32",children:[t.content.slice(0,500),t.content.length>500&&"..."]})]});if(t.messageKind==="workflow-started")try{const h=JSON.parse(t.content);return i.jsx(r$,{data:h})}catch{}if(t.messageKind==="task-completed")try{const h=JSON.parse(t.content);return i.jsx(n$,{data:h})}catch{}return t.messageKind==="context-reset"?i.jsxs("div",{className:"flex items-center gap-4 mb-6 text-text-muted text-xs uppercase tracking-wide",children:[i.jsx("div",{className:"flex-1 border-t border-border"}),i.jsx("span",{children:t.content}),i.jsx("div",{className:"flex-1 border-t border-border"})]}):t.messageKind==="auto-prompt"&&t.isSystemGenerated?i.jsx(u$,{message:t}):t.messageKind==="correction"&&t.isSystemGenerated?i.jsx("div",{className:"flex justify-end feed-item",children:i.jsxs("div",{className:"max-w-[75%] rounded p-2 bg-bg-system border border-border-system",children:[i.jsx("span",{className:"text-[10px] block mb-0.5 text-text-system",children:"System"}),i.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-text-system italic",children:t.content})]})}):l?i.jsx(d$,{message:t,messageId:r,sessionId:a}):i.jsx("div",{className:"flex justify-start feed-item",children:i.jsx("div",{className:"max-w-[75%] rounded p-2 bg-bg-tertiary text-text-primary",children:i.jsx(zn,{content:t.content})})})}),h$={verifier:"Verification",code_reviewer:"Code Review",test_generator:"Test Generation",debugger:"Debug"};function f$(e){return{backgroundColor:`${e}20`,color:e,borderColor:`${e}4d`}}function HS(e,t){return t||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function m$({contextState:e}){const{currentTokens:t,maxTokens:n,compactionCount:r,dangerZone:a}=e,l=Math.round(t/n*100);return i.jsxs("div",{className:"flex items-center gap-1.5 text-[10px]",children:[i.jsxs("span",{className:HS(l,a),children:[oo(t),"/",oo(n)]}),i.jsxs("span",{className:HS(l,a),children:["(",l,"%)"]}),i.jsx(Zg,{percent:l,dangerZone:a,size:"sm"}),a&&i.jsx("span",{className:"text-accent-error animate-pulse",children:"Low!"}),r>0&&i.jsxs("span",{className:"text-text-muted bg-bg-tertiary px-1 rounded",children:[r,"x"]})]})}const p$=E.memo(function({messages:t,subAgentType:n,subAgentId:r,isStreaming:a}){const l=E.useRef(null),u=E.useRef(null),[c,d]=E.useState(!1),h=xt(D=>D.defaults),p=xt(D=>D.userItems),m=[...h,...p],x=Le(D=>D.subAgentContextStates[r]),{showThinking:y,showVerboseToolOutput:w}=Zi(),{isAutoScrollActive:C,setAutoScroll:_}=Qd(u,null),S=E.useCallback(()=>{const D=!c;d(D),D&&setTimeout(()=>{var L;(L=l.current)==null||L.scrollIntoView({block:"start",behavior:"smooth"})},220)},[c]),v=m.find(D=>D.id===n),b=(v==null?void 0:v.name)??h$[n]??n,j=Vl(m,n),N=f$(j),T=t.filter(D=>D.role!=="tool");return i.jsxs("div",{ref:l,className:"feed-item border border-border rounded overflow-hidden bg-secondary",children:[i.jsxs("div",{className:"w-full flex items-center justify-between px-2 py-1 border-b relative",style:N,children:[i.jsx("span",{className:"text-xs font-medium",children:b}),i.jsx("div",{className:"absolute left-1/2 -translate-x-1/2",children:x&&i.jsx(m$,{contextState:x})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5",onClick:()=>_(!C),children:[i.jsx("span",{className:`w-1 h-1 rounded-full ${C?"bg-accent-success":"border border-text-muted"}`}),"live"]}),i.jsxs("button",{type:"button",className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-tertiary",onClick:S,children:[c?"▼":"▶"," Expand"]})]})]}),i.jsx("div",{ref:u,className:`${c?"max-h-[calc(100vh-10rem)]":"max-h-80"} overflow-y-auto p-2 transition-[max-height] duration-200`,children:T.map(D=>D.role==="assistant"?i.jsx(tx,{message:D,showStats:!0,showThinking:y,showVerboseToolOutput:w},D.id):i.jsx(d2,{message:D,isLastAssistantMessage:!1},D.id))})]})}),cp={contentVisibility:"auto",containIntrinsicSize:"auto 200px"};function Pu(e){var t;return e.type==="context-divider"?`ctx-${e.windowSequence}`:e.type==="subagent"?((t=e.messages[0])==null?void 0:t.id)??e.subAgentId:e.message.id}const h2=E.memo(function({displayItems:t,highlightedMessageId:n=null,sessionId:r,showThinking:a=!0,showVerboseToolOutput:l=!0,showStats:u=!0,showAgentDefinitions:c=!0,showWorkflowBars:d=!0}){return i.jsx(i.Fragment,{children:t.map((h,p)=>{if(h.type==="context-divider")return i.jsxs("div",{"data-item-index":p,className:"flex items-center gap-2 feed-item px-2 md:px-4",children:[i.jsx("div",{className:"flex-1 border-t border-border"}),i.jsx("span",{className:"text-[10px] text-text-muted font-medium px-2",children:"Earlier context summarized"}),i.jsx("div",{className:"flex-1 border-t border-border"})]},Pu(h));if(h.type==="subagent"){const w=h.messages.some(C=>C.isStreaming);return i.jsx("div",{"data-item-index":p,className:"px-2 md:px-4",style:cp,children:i.jsx(p$,{messages:h.messages,subAgentType:h.subAgentType,subAgentId:h.subAgentId,isStreaming:w})},Pu(h))}const m=h.message;if(m.role==="assistant")return i.jsx("div",{"data-item-index":p,className:"px-2 md:px-4",style:cp,children:i.jsx(tx,{message:m,showStats:u,showThinking:a,showVerboseToolOutput:l,sessionId:r??void 0})},Pu(h));const x=!c&&m.messageKind==="auto-prompt",y=!d&&(m.messageKind==="workflow-started"||m.messageKind==="task-completed");return x||y?null:i.jsx("div",{"data-item-index":p,className:"px-2 md:px-4",style:cp,children:i.jsx("div",{"data-message-id":m.id,className:n===m.id?"rounded animate-highlight-fade":void 0,children:i.jsx(d2,{message:m,messageId:m.id,sessionId:r??void 0,isLastAssistantMessage:!1})})},Pu(h))})})});function Jd(e,t,n=!0){E.useEffect(()=>{if(!n)return;const r=a=>{var l;(l=e.current)!=null&&l.contains(a.target)||t()};return document.addEventListener("mousedown",r),()=>document.removeEventListener("mousedown",r)},[e,t,n])}const g$=[],x$=E.memo(function({displayItems:t,scrollContainerRef:n,highlightedMessageId:r,onLaunchWorkflow:a,onScrollToTop:l,hiddenCount:u=0}){const c=Le(Q=>{var K,P;return((P=(K=Q.currentSession)==null?void 0:K.metadataEntries)==null?void 0:P.criteria)??g$}),d=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.id}),h=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.mode}),p=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.phase}),m=Le(Q=>Q.error),x=Le(Q=>Q.clearError),y=kd(),w=Le(Q=>Q.waitingWorkflow),C=Le(Q=>Q.continueWorkflow),{showThinking:_,showVerboseToolOutput:S,showStats:v,showAgentDefinitions:b,showWorkflowBars:j}=Zi(),N=vt(Q=>Q.defaults),T=vt(Q=>Q.userItems),D=[...N,...T],L=h==="planner",O=c.length>0,M=p==="done",W=t.some(Q=>Q.type==="message"&&Q.message.role==="assistant"),U=L&&O&&!y&&W&&!M,R=p==="waiting"&&w!=null&&!y,H=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.projectId}),[G,V]=E.useState(!1),[Z,X]=E.useState(!1),[$,I]=E.useState(!1);E.useLayoutEffect(()=>{const Q=n.current;Q&&X(Q.scrollHeight>Q.clientHeight+1)},[n,t]),E.useEffect(()=>{const Q=n.current;if(!Q)return;const K=()=>I(Q.scrollTop>4);return K(),Q.addEventListener("scroll",K,{passive:!0}),()=>Q.removeEventListener("scroll",K)},[n]);const B=()=>{if(!H||!d)return;V(!1),window.open(`/p/${H}/s/${d}/readonly`,"_blank")||V(!0)},[q,z]=E.useState(!1),ne=E.useCallback(()=>{q||(z(!0),C(),setTimeout(()=>z(!1),5e3))},[q,C]),re=E.useCallback(()=>{var Q;l==null||l(),(Q=n.current)==null||Q.scrollTo({top:0,behavior:"smooth"})},[n,l]);return i.jsxs("div",{className:"relative flex-1 min-w-0 group",children:[i.jsxs("div",{ref:n,"data-testid":"chat-scroll-container",className:"absolute inset-0 overflow-y-auto bg-primary scrollbar-stable",children:[i.jsxs("div",{className:"pt-4",children:[u>0&&i.jsxs("div",{className:"px-2 md:px-4 pb-2 space-y-1",children:[i.jsxs("button",{onClick:B,className:"w-full text-sm text-text-muted hover:text-text-primary bg-bg-tertiary/50 hover:bg-bg-tertiary border border-border rounded px-3 py-2 transition-colors text-center",children:[u," older item",u!==1?"s":""," hidden — View full history"]}),G&&i.jsxs("p",{className:"text-xs text-text-muted text-center",children:["Popup blocked."," ",i.jsx("a",{href:H&&d?`/p/${H}/s/${d}/readonly`:"#",target:"_blank",rel:"noopener noreferrer",className:"underline hover:text-text-primary",children:"Open manually"})]})]}),i.jsx(h2,{displayItems:t,highlightedMessageId:r,sessionId:d,showThinking:_,showVerboseToolOutput:S,showStats:v,showAgentDefinitions:b,showWorkflowBars:j})]}),i.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[m&&i.jsx("div",{className:"feed-item bg-text-tool-error/10 border border-text-tool-error/50 rounded p-2",children:i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-text-tool-error text-sm font-medium",children:m.code}),i.jsx("div",{className:"text-text-tool-error/80 text-xs mt-0.5",children:m.message})]}),i.jsx(rc,{onClick:x,className:"text-text-tool-error hover:text-text-tool-error/80 p-0.5",size:"sm"})]})}),R&&w&&i.jsx("div",{className:"flex justify-center gap-2 feed-item",children:i.jsx("button",{onClick:ne,disabled:q,className:"px-4 py-1.5 text-sm font-medium rounded bg-accent-primary/15 text-accent-primary border border-accent-primary/25 hover:bg-accent-primary/25 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:q?"⏳ Continuing...":`▶ Continue ${w.workflowName} (${w.stepName})`})}),U&&i.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:D.map(Q=>{const K=Q.color??"#3b82f6",P=parseInt(K.slice(1,3),16),J=parseInt(K.slice(3,5),16),ie=parseInt(K.slice(5,7),16),he=`rgba(${P},${J},${ie},0.12)`,ce=`rgba(${P},${J},${ie},0.22)`,De=`rgba(${P},${J},${ie},0.25)`;return i.jsx(y$,{workflowName:Q.name,color:K,bg:he,bgHover:ce,border:De,subGroups:Q.subGroups,onLaunch:Re=>a(Q.id,Re)},Q.id)})})]})]}),Z&&$&&i.jsx("div",{className:"absolute top-2 left-1/2 -translate-x-1/2 z-10 pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity duration-200",children:i.jsxs("button",{type:"button",onClick:re,className:"pointer-events-auto 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 backdrop-blur-sm bg-bg-secondary/60",children:[i.jsx(sT,{className:"w-3 h-3"}),"scroll to top"]})})]})});function y$({workflowName:e,color:t,bg:n,bgHover:r,border:a,subGroups:l,onLaunch:u}){const[c,d]=E.useState(!1),h=E.useRef(null);Jd(h,()=>d(!1),c);const p=l&&l.length>0;return i.jsxs("div",{className:"relative flex",children:[i.jsxs("button",{onClick:()=>u(),"data-testid":"workflow-run-button",className:`px-4 py-1.5 text-sm font-medium transition-colors ${p?"rounded-l":"rounded"}`,style:{backgroundColor:n,color:t,border:`1px solid ${a}`,...p?{borderRight:"none"}:{}},onMouseEnter:m=>{m.currentTarget.style.backgroundColor=r},onMouseLeave:m=>{m.currentTarget.style.backgroundColor=n},children:["▶ ",e]}),p&&i.jsxs("div",{ref:h,className:"relative",children:[i.jsx("button",{onClick:()=>d(!c),className:"px-2.5 py-1.5 rounded-r text-sm font-medium transition-colors",style:{backgroundColor:n,color:t,border:`1px solid ${a}`},onMouseEnter:m=>{m.currentTarget.style.backgroundColor=r},onMouseLeave:m=>{m.currentTarget.style.backgroundColor=n},children:"⋮"}),c&&i.jsxs("div",{className:"absolute top-full right-0 mt-1 w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[i.jsx("button",{onClick:()=>{u(),d(!1)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:"Full workflow"}),i.jsx("div",{className:"border-t border-border/50"}),l.map(m=>i.jsx("button",{onClick:()=>{u(m),d(!1)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:m},m))]})]})]})}function b$(){const e=Le(r=>r.connectionStatus),t=Le(r=>r.reconnect);if(e==="connected")return null;const n=e==="reconnecting";return i.jsxs("div",{className:`
297
+ `,children:i.jsx(MS,{messages:r,workdir:(a==null?void 0:a.workspace)??(a==null?void 0:a.workdir)})})]})]})}function b8(){const e=Le(w=>w.contextState),t=Le(w=>w.currentSession),n=Le(w=>w.pendingUpdate),r=Le(w=>w.triggerPendingUpdate),a=Le(w=>w.queueUpdate),[l,u]=E.useState(!1),[c,d]=E.useState(!1),h=E.useRef(!1),p=E.useRef(!1);if(E.useEffect(()=>{e!=null&&e.dynamicContextChanged&&!h.current&&u(!1),h.current=(e==null?void 0:e.dynamicContextChanged)??!1},[e==null?void 0:e.dynamicContextChanged]),E.useEffect(()=>{const w=(t==null?void 0:t.isRunning)??!1;p.current&&!w&&n&&r(),p.current=w},[t==null?void 0:t.isRunning,n,r]),!e||!t)return null;const{dynamicContextChanged:m}=e,x=t.isRunning,y=()=>{x?a():Dt.send("context.applyDynamic",{}),u(!0),d(!1)};return i.jsxs(i.Fragment,{children:[m&&!l&&i.jsx("div",{className:"flex-shrink-0 px-4 py-2 bg-accent-warning/10 border-b border-accent-warning/30",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1 flex items-center justify-center gap-1 text-sm text-text-secondary",children:[i.jsx("span",{children:"System prompt has changed —"}),i.jsx("button",{onClick:()=>d(!0),className:"underline hover:text-text-primary transition-colors",children:"click here to update it"})]}),i.jsx("button",{onClick:()=>u(!0),className:"flex-shrink-0 p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Dismiss",children:i.jsx(js,{})})]})}),i.jsx(ex,{isOpen:c,onClose:()=>d(!1),isRunning:x,onApply:y})]})}function v8({stats:e,onClose:t}){var c;const n=xt(d=>d.defaults),r=xt(d=>d.userItems),l=[...n,...r].find(d=>d.id===e.mode),u=(l==null?void 0:l.name)??e.mode;return i.jsx(jt,{isOpen:!0,onClose:t,title:"Turn Stats",size:"md",children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"flex items-center gap-3",children:i.jsxs("p",{className:"text-xs text-text-muted",children:[e.model," · ",u]})}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[i.jsx(Iu,{label:"Total Time",value:Yr(e.totalTime)}),i.jsx(Iu,{label:"Prefill",value:e.prefillTokens>=1e3?`${(e.prefillTokens/1e3).toFixed(1)}k`:String(e.prefillTokens)}),i.jsx(Iu,{label:"Generated",value:e.generationTokens>=1e3?`${(e.generationTokens/1e3).toFixed(1)}k`:String(e.generationTokens)}),i.jsx(Iu,{label:"LLM Calls",value:String(((c=e.llmCalls)==null?void 0:c.length)??1)})]}),e.llmCalls&&e.llmCalls.length>0&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-secondary mb-2",children:"LLM Calls"}),e.llmCalls.map((d,h)=>i.jsxs("div",{className:"bg-bg-tertiary/30 rounded p-3 mb-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("span",{className:"text-xs text-text-muted",children:["Call ",h+1]}),i.jsxs("span",{className:"text-xs text-text-muted",children:[d.ttft.toFixed(2),"s TTFT · ",d.completionTime.toFixed(2),"s gen"]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-text-muted",children:"Tokens:"})," ",i.jsxs("span",{className:"text-text-primary",children:[d.promptTokens," → ",d.completionTokens]})]}),i.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1",children:[d.temperature!==void 0&&i.jsx(Mu,{label:"temp",value:d.temperature.toFixed(2)}),d.topP!==void 0&&i.jsx(Mu,{label:"topP",value:d.topP.toFixed(2)}),d.topK!==void 0&&i.jsx(Mu,{label:"topK",value:String(d.topK)}),d.maxTokens!==void 0&&i.jsx(Mu,{label:"maxTok",value:String(d.maxTokens)})]})]})]},h))]})]})})}function Iu({label:e,value:t}){return i.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[i.jsx("div",{className:"text-xs text-text-muted",children:e}),i.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t})]})}function Mu({label:e,value:t}){return i.jsxs("span",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-text-primary",children:[i.jsxs("span",{className:"text-text-muted",children:[e,":"]})," ",t]})}const _8=E.memo(function({content:t,variant:n="default"}){return n==="labeled"?i.jsxs("div",{className:"text-text-muted text-sm italic feed-item",children:[i.jsx("span",{className:"text-text-thinking",children:"thinking:"}),i.jsx("div",{className:"ml-1.5 mt-0.5 overflow-x-auto",children:i.jsx(zn,{content:t})})]}):i.jsx("div",{className:"text-text-muted text-sm italic bg-secondary rounded p-1.5 feed-item overflow-x-auto",children:i.jsx(zn,{content:t,muted:!0})})});function ij({tool:e,className:t="w-4 h-4 text-text-muted flex-shrink-0"}){return e==="glob"||e==="grep"?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:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}):e==="run_command"||e==="bash"?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:"M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"})}):e==="workspace"?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:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"})}):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:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}const S8={error:{icon:"✗",color:"text-accent-error",bg:"bg-red-500/10",border:"border-red-500/30"},warning:{icon:"⚠",color:"text-accent-warning",bg:"bg-yellow-500/10",border:"border-yellow-500/30"},info:{icon:"ℹ",color:"text-accent-info",bg:"bg-blue-500/10",border:"border-blue-500/30"},hint:{icon:"💡",color:"text-text-muted",bg:"bg-gray-500/10",border:"border-gray-500/30"}},PS=E.memo(function({diagnostics:t}){if(t.length===0)return null;const n=t.filter(l=>l.severity==="error"),r=t.filter(l=>l.severity==="warning"),a=t.filter(l=>l.severity==="info"||l.severity==="hint");return i.jsxs("div",{className:"rounded border border-border overflow-hidden mt-2",children:[i.jsxs("div",{className:"flex items-center gap-3 px-2 py-1.5 bg-bg-tertiary border-b border-border",children:[i.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"LSP Diagnostics"}),n.length>0&&i.jsxs("span",{className:"text-xs text-accent-error font-medium",children:[n.length," error",n.length!==1?"s":""]}),r.length>0&&i.jsxs("span",{className:"text-xs text-accent-warning font-medium",children:[r.length," warning",r.length!==1?"s":""]}),a.length>0&&i.jsxs("span",{className:"text-xs text-text-muted",children:[a.length," info"]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto",children:t.map((l,u)=>{const c=S8[l.severity];return i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${c.bg} border-b border-border last:border-b-0`,children:[i.jsx("span",{className:`${c.color} text-xs flex-shrink-0 w-4 text-center`,children:c.icon}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:["Ln ",l.range.start.line+1,":",l.range.start.character+1]}),l.code&&i.jsxs("span",{className:"text-[10px] text-text-muted font-mono",children:["[",l.code,"]"]})]}),i.jsx("div",{className:"text-xs text-text-primary break-words",children:l.message})]})]},u)})})]})}),w8=E.memo(function({command:t,timeout:n,startedAt:r,streamingOutput:a,status:l,result:u,error:c,durationMs:d}){const h=E.useRef(null),[p,m]=E.useState(0);E.useEffect(()=>{h.current&&l==="pending"&&(h.current.scrollTop=h.current.scrollHeight)},[a,l]),E.useEffect(()=>{if(l!=="pending"||!r)return;const C=setInterval(()=>{m(Date.now()-r)},100);return()=>clearInterval(C)},[l,r]);const x=n/1e3,y=l==="pending"?p/1e3:(d??0)/1e3,w=l==="pending"?(a==null?void 0:a.map(C=>C.content).join(""))??"":u??"";return i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs flex-1 min-w-0",children:[i.jsx("span",{className:"text-text-muted flex-shrink-0",children:"$"}),i.jsx("code",{className:"text-text-primary break-all",children:t})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted flex-shrink-0",children:[l==="pending"&&i.jsx("span",{className:"animate-pulse text-accent-warning",children:"running"}),l==="interrupted"&&i.jsx("span",{className:"text-red-400",children:"interrupted"}),i.jsxs("span",{className:l==="pending"?"text-text-secondary":"text-text-muted",children:[y.toFixed(1),"s / ",x,"s"]})]})]}),l==="pending"&&i.jsx("div",{className:"h-1 bg-bg-tertiary rounded overflow-hidden",children:i.jsx("div",{className:"h-full bg-accent-warning transition-all duration-100",style:{width:`${Math.min(100,p/n*100)}%`}})}),(w||l==="pending")&&i.jsx("pre",{ref:h,className:`text-xs bg-bg-primary p-2 rounded max-h-64 overflow-y-auto ${l==="pending"?"border border-accent-warning/30":""}`,style:{overflowX:"hidden",whiteSpace:"normal"},children:l==="pending"&&a?a.map((C,_)=>i.jsx("span",{className:C.stream==="stderr"?"text-accent-warning":"",children:yd(C.content)},_)):yd(w)}),l==="error"&&c&&i.jsx("div",{className:"text-xs text-accent-error bg-accent-error/10 p-2 rounded",children:c}),l!=="pending"&&d!==void 0&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Completed in ",(d/1e3).toFixed(2),"s"]})]})}),bl=E.memo(function({className:t=""}){return i.jsx("div",{className:`text-[10px] text-accent-warning ${t}`,children:"Output truncated"})}),C8=E.memo(function({result:t,action:n}){let r;try{r=JSON.parse(t)}catch{return console.warn("DevServerView: failed to parse result JSON",t.slice(0,200)),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}return n==="logs"?k8(r):j8(r)});function k8(e){if(!e.logs)return i.jsx("div",{className:"text-xs text-text-muted italic",children:"No log output"});const t=e.logs.split(`
298
+ `);return i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-mono whitespace-pre-wrap bg-bg-primary p-2 rounded max-h-[60vh] overflow-y-auto break-words",children:t.map((n,r)=>{const a=n.startsWith("[stderr] ");return i.jsx("div",{className:a?"text-accent-warning":"",children:a?n.slice(9):n},r)})}),e.hasMore&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Showing ",e.limit," of ",e.total," lines"]})]})}function j8(e){const t=String(e.state??""),n=String(e.url??""),r=e.error?String(e.error):void 0,a=t==="running"?"text-accent-success":t==="stopped"?"text-text-muted":t==="error"?"text-accent-error":"text-text-muted";return i.jsxs("div",{className:"space-y-2 text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"State:"}),i.jsx("span",{className:`font-medium ${a}`,children:t})]}),n&&n!=="undefined"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"URL:"}),i.jsx("a",{href:n,className:"text-accent-primary hover:underline",target:"_blank",rel:"noopener noreferrer",children:n})]}),r&&i.jsx("div",{className:"text-accent-error bg-accent-error/10 p-2 rounded",children:r})]})}const E8=E.memo(function({result:t,action:n}){let r;try{r=JSON.parse(t)}catch{return console.warn("BackgroundProcessView: failed to parse result JSON",t.slice(0,200)),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}return n==="logs"?N8(r):n==="list"?T8(r):n==="status"?A8(r):n==="start"||n==="stop"?L8(r):i.jsxs("div",{className:"space-y-2 text-xs",children:[i.jsxs("div",{className:"text-accent-warning",children:["Unknown action: ",n]}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})]})});function N8(e){const t=e.lines,n=e.hasMore,r=e.totalLines;return!t||t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic",children:"No log output"}):i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-mono whitespace-pre-wrap bg-bg-primary p-2 rounded max-h-[60vh] overflow-y-auto break-words",children:t.map((a,l)=>i.jsx("div",{className:a.stream==="stderr"?"text-accent-warning":"",children:a.content},l))}),n&&r!=null&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Showing ",t.length," of ",r," lines"]})]})}function T8(e){const t=e.processes,n=e.currentCount,r=e.maxPerSession;return!t||t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic",children:"No background processes"}):i.jsxs("div",{className:"space-y-2",children:[t.map(a=>i.jsx(aj,{process:a},a.id)),n!=null&&r!=null&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:[n," of ",r," slots used"]})]})}function A8(e){const t=e.process,n=e.uptime;return t?i.jsxs("div",{className:"space-y-2",children:[i.jsx(aj,{process:t}),n!=null&&i.jsxs("div",{className:"text-[10px] text-text-muted",children:["Uptime: ",D8(n)]})]}):i.jsx("div",{className:"text-xs text-text-muted italic",children:"Process not found"})}function L8(e){const t=e.processId,n=e.name,r=e.pid,a=e.status,l=a==="running"?"text-accent-success":"text-text-muted";return i.jsxs("div",{className:"space-y-2 text-xs",children:[n&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"Name:"}),i.jsx("span",{className:"font-medium",children:n})]}),t&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"ID:"}),i.jsx("span",{className:"font-mono",children:t})]}),r!=null&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"PID:"}),i.jsx("span",{className:"font-mono",children:r})]}),a&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-text-muted",children:"Status:"}),i.jsx("span",{className:`font-medium ${l}`,children:a})]})]})}function aj({process:e}){const t=e.status==="running"?"text-accent-success":(e.status==="exited","text-text-muted");return i.jsxs("div",{className:"border border-border rounded p-2 space-y-1 text-xs",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"font-medium",children:e.name}),i.jsx("span",{className:`${t}`,children:e.status})]}),e.pid!=null&&i.jsxs("div",{className:"text-text-muted",children:["PID: ",i.jsx("span",{className:"font-mono",children:e.pid})]}),e.command&&i.jsx("div",{className:"text-text-muted font-mono truncate",children:e.command})]})}function D8(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}const R8=E.memo(function({result:t,action:n}){let r;try{r=JSON.parse(t)}catch{return i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}switch(n){case"list":return O8(r);case"switch":case"delete":return I8(r);default:return i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:t})}});function O8(e){const t=e.workspaces??[];return t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic",children:"No workspaces found"}):i.jsxs("div",{className:"space-y-1 text-xs",children:[i.jsx("div",{className:"text-text-muted mb-1",children:"Workspaces:"}),t.map(n=>i.jsxs("div",{className:"flex items-center gap-2 font-mono",children:[i.jsx("span",{className:n.active?"text-accent-success":"text-text-muted",children:n.active?"●":"○"}),i.jsx("span",{className:n.active?"text-text-primary font-medium":"text-text-secondary",children:n.name}),n.branch&&i.jsxs("span",{className:"text-text-muted",children:["· ",n.branch]}),n.active&&i.jsx("span",{className:"text-[10px] text-accent-primary",children:"(current)"})]},n.name))]})}function lp({label:e,value:t,mono:n}){return i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-text-muted",children:[e,":"]}),i.jsx("span",{className:n?"font-mono text-accent-primary":"text-text-primary",children:t})]})}function I8(e){return i.jsxs("div",{className:"space-y-2 text-xs",children:[e.message&&i.jsx("div",{className:"text-text-primary",children:e.message}),e.workspace&&i.jsx(lp,{label:"Name",value:e.workspace,mono:!0}),e.path&&i.jsx(lp,{label:"Path",value:e.path,mono:!0}),e.branch&&i.jsx(lp,{label:"Branch",value:e.branch,mono:!0})]})}function M8(e){switch(e){case"sensitive_file":return{title:"Sensitive File Access",description:"Accessing files that may contain secrets"};case"both":return{title:"Sensitive File Access",description:"Accessing sensitive files outside project"};case"dangerous_command":return{title:"Dangerous Command",description:"Running potentially dangerous command"};case"git_no_verify":return{title:"Git --no-verify",description:"Bypassing git hooks/pre-commit checks"};case"outside_workdir":default:return{title:"Path Access Request",description:"Accessing paths outside project directory"}}}function P8({confirmation:e}){const t=Le(m=>m.confirmPath),n=Le(m=>m.currentSession),r=Le(m=>m.switchDangerLevel),{title:a,description:l}=M8(e.reason),u=e.reason==="sensitive_file"||e.reason==="both",c=u?"border-red-500/50":"border-amber-500/50",d=u?"bg-red-500/10":"bg-amber-500/10",h=e.reason==="git_no_verify",p=()=>{n!=null&&n.id&&r("dangerous"),t(e.callId,!0,!1)};return i.jsxs("div",{className:`border ${c} ${d} rounded p-3 my-2`,children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(yp,{}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:`text-sm font-medium ${u?"text-red-400":"text-amber-400"}`,children:a}),i.jsx("div",{className:"text-xs text-text-muted",children:l})]})]}),i.jsxs("div",{className:"text-xs text-text-muted mb-2",children:[i.jsx("span",{className:"font-medium",children:e.tool})," wants to access:"]}),i.jsx("div",{className:"bg-bg-primary rounded p-2 mb-3 max-h-24 overflow-y-auto",children:i.jsx("ul",{className:"space-y-0.5",children:e.paths.map((m,x)=>i.jsx("li",{className:`text-xs font-mono ${u?"text-red-300":"text-amber-300"} break-all`,children:m},x))})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>t(e.callId,!1),className:"flex-1 px-3 py-1.5 text-xs font-medium rounded bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border transition-colors",children:"Deny"}),i.jsx("button",{onClick:()=>t(e.callId,!0,!1),className:"flex-1 px-3 py-1.5 text-xs font-medium rounded bg-accent-primary hover:bg-accent-primary/80 text-text-primary transition-colors",children:"Allow"}),i.jsx("button",{onClick:p,className:`flex-1 px-3 py-1.5 text-xs font-medium rounded transition-colors ${h?"hidden":"bg-red-600 hover:bg-red-700 text-white"}`,title:"Enable dangerous mode and allow this request",children:"Allow Everything"})]})]})}function B8(e,t){if(e==="read_file"){const r=String(t.path??""),a=t.offset,l=t.limit,u=[];return a!==void 0&&a!==1&&u.push(`offset=${a}`),l!==void 0&&u.push(`limit=${l}`),u.length>0?`${r} [${u.join(", ")}]`:r}if(e==="write_file"||e==="edit_file")return String(t.path??"");if(e==="run_command"||e==="bash")return String(t.command??"");if(e==="return_value"){const r=String(t.content??"");return r.length>60?r.slice(0,60)+"...":r}if(e==="call_sub_agent")return String(t.subAgentType??"");if(e==="load_skill")return String(t.skillId??"");if(e==="web_fetch")return String(t.url??"");if(e==="web_search"){const r=String(t.query??"");return r.length>60?r.slice(0,57)+"...":r}if(e==="dev_server")return String(t.action??"");if(e==="background_process"){const r=String(t.action??""),a=t.name?String(t.name):"";return a?`${r}: ${a}`:r}if(e==="mcp_config")return String(t.action??"");const n=JSON.stringify(t);return n.length>50?n.slice(0,50)+"...":n}function BS(e,t,n){var a;const r=B8(e,t);if(e==="read_file"&&n){const l=n.format,u=n.pageCount;if(l==="pdf"&&u!=null)return`${r} (PDF, ${u}p)`;if(l==="image")return`${r} (image)`}if(e==="web_fetch"&&n){const l=n.contentType;if(l){const u=((a=l.split(";")[0])==null?void 0:a.trim())??"";if(u&&u!=="text/html")return`${r} (${u})`}}return r}function $8(e){return JSON.stringify(e,null,2)}const z8={pending:{icon:"●",color:"text-accent-warning",animate:!0},success:{icon:"✓",color:"text-accent-success",animate:!1},error:{icon:"✗",color:"text-accent-error",animate:!1},interrupted:{icon:"✗",color:"text-text-tool-error",animate:!1}},H8=E.memo(function({tool:t,args:n,status:r,variant:a="compact",forceCompact:l,result:u,error:c,durationMs:d,diagnostics:h,editContext:p,startedAt:m,streamingOutput:x,metadata:y,truncated:w,callId:C}){var L;const _=!l,[S,v]=E.useState(_),b=z8[r],j=Ft(O=>O.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true",N=t==="edit_file"?(L=p==null?void 0:p.regions[0])==null?void 0:L.startLine:t==="read_file"?(()=>{const O=u==null?void 0:u.split(`
299
+ `)[0],M=O==null?void 0:O.match(/^(\d+): /);return M?parseInt(M[1],10):void 0})():void 0,T=Le(O=>O.pendingPathConfirmations),D=C?T.find(O=>O.callId===C||O.callId.startsWith(C+"-"))??null:null;return t==="step_done"?i.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-secondary border border-border rounded px-2 py-1.5 my-1",children:[i.jsx("span",{className:`${b.color} ${b.animate?"animate-pulse":""}`,children:b.icon}),i.jsx("span",{className:"font-mono text-accent-primary text-sm",children:t})]}):a==="compact"?i.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-secondary rounded px-2 py-1.5",children:[i.jsx(ij,{tool:t}),i.jsx("span",{className:"text-accent-primary font-medium",children:t}),i.jsx("span",{className:"text-text-muted truncate flex-1",children:BS(t,n,y)}),i.jsx("span",{className:`${b.color} ${b.animate?"animate-pulse":""}`,children:r==="pending"?"...":"done"})]}):i.jsxs("div",{className:"border border-border rounded overflow-hidden my-1 min-w-0",children:[i.jsxs("button",{className:"w-full flex items-center gap-1.5 p-2 bg-secondary hover:bg-secondary/80 text-left",onClick:()=>v(!S),children:[i.jsx("span",{className:`${b.color} ${b.animate?"animate-pulse":""}`,children:b.icon}),i.jsx("span",{className:"font-mono text-accent-primary text-sm",children:t}),i.jsx("span",{className:"text-text-muted text-xs flex-1 truncate",children:BS(t,n,y)}),i.jsx("span",{className:"text-text-muted text-xs",children:S?"▼":"▶"})]}),S&&i.jsxs("div",{className:"p-2 bg-primary border-t border-border space-y-2 min-w-0",children:[t==="run_command"&&i.jsx(w8,{command:String(n.command??""),timeout:n.timeout??12e4,startedAt:m,streamingOutput:x,status:r,result:u,error:c,durationMs:d}),t==="edit_file"&&r==="success"&&i.jsxs(i.Fragment,{children:[p&&p.regions.length>0?i.jsx(d8,{regions:p.regions,filePath:String(n.path??"")}):i.jsx(c8,{oldString:String(n.old_string??""),newString:String(n.new_string??""),filePath:String(n.path??"")}),h&&h.length>0&&i.jsx(PS,{diagnostics:h})]}),t==="write_file"&&r==="success"&&i.jsxs(i.Fragment,{children:[i.jsx(u8,{content:String(n.content??""),filePath:String(n.path??"")}),h&&h.length>0&&i.jsx(PS,{diagnostics:h})]}),t==="read_file"&&r==="success"&&i.jsx(p8,{result:u,metadata:y,filePath:String(n.path??"")}),t==="return_value"&&(()=>{const O=(x==null?void 0:x.map(W=>W.content).join(""))??"",M=r==="pending"&&O?O:String(n.content??"");return i.jsxs("div",{children:[i.jsx("div",{className:"text-[10px] text-accent-primary font-medium mb-1 uppercase tracking-wide",children:"Sub-Agent Summary"}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none",children:i.jsx(zn,{content:M})})]})})(),t==="call_sub_agent"&&i.jsxs("div",{children:[i.jsxs("div",{className:"text-[10px] text-accent-primary font-medium mb-1 uppercase tracking-wide",children:[String(n.subAgentType??"Sub-Agent")," Prompt"]}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:String(n.prompt??"")})})]}),t==="web_search"&&r==="success"&&i.jsxs("div",{children:[i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{className:"mt-1"})]}),t==="load_skill"&&r==="success"&&i.jsxs("div",{children:[i.jsxs("div",{className:"text-[10px] text-accent-primary font-medium mb-1 uppercase tracking-wide",children:["Skill: ",String(n.skillId??"")]}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{className:"mt-1"})]}),t==="web_fetch"&&r==="success"&&i.jsxs("div",{className:"space-y-2",children:[!!(y!=null&&y.url)&&i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[i.jsx("span",{children:"Source:"}),i.jsx("a",{href:String(y.url),className:"text-accent-primary hover:underline truncate",target:"_blank",rel:"noopener noreferrer",children:String(y.url)}),!!(y!=null&&y.contentType)&&i.jsxs("span",{className:"text-text-muted flex-shrink-0",children:["(",String(y.contentType),")"]}),(y==null?void 0:y.pageCount)!=null&&i.jsxs("span",{className:"text-text-muted flex-shrink-0",children:["· ",String(y.pageCount)," pages"]})]}),i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{})]}),t==="dev_server"&&r==="success"&&u&&i.jsx(C8,{result:u,action:String(n.action??"")}),t==="workspace"&&r==="success"&&u&&i.jsx(R8,{result:u,action:String(n.action??"")}),t==="background_process"&&r==="success"&&u&&i.jsx(E8,{result:u,action:String(n.action??"")}),t==="mcp_config"&&r==="success"&&i.jsxs("div",{children:[i.jsx("div",{className:"text-xs prose prose-invert prose-sm max-w-none max-h-[60vh] overflow-y-auto",children:i.jsx(zn,{content:u??""})}),w&&i.jsx(bl,{className:"mt-1"})]}),t==="step_done"&&null,t!=="edit_file"&&t!=="write_file"&&t!=="run_command"&&t!=="read_file"&&t!=="return_value"&&t!=="call_sub_agent"&&t!=="web_search"&&t!=="load_skill"&&t!=="web_fetch"&&t!=="dev_server"&&t!=="workspace"&&t!=="background_process"&&t!=="mcp_config"&&t!=="step_done"&&i.jsxs(i.Fragment,{children:[Object.keys(n).length>0&&i.jsxs("div",{children:[i.jsx("div",{className:"text-[10px] text-text-muted mb-0.5",children:"Arguments:"}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto break-words",children:$8(n)})]}),r==="success"&&u!==void 0&&i.jsxs("div",{children:[i.jsxs("div",{className:"text-[10px] text-text-muted mb-0.5",children:["Result",d!==void 0&&` (${d}ms)`,":"]}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded overflow-x-auto max-h-[60vh] break-words",children:u||"No output"}),w&&i.jsx(bl,{className:"mt-1"})]})]}),r==="success"&&(t==="edit_file"||t==="write_file"||t==="read_file")&&d!==void 0&&i.jsxs("div",{className:"text-[10px] text-text-muted flex items-center gap-2",children:[i.jsxs("span",{children:["Completed in ",d,"ms"]}),j&&(t==="read_file"||t==="write_file"||t==="edit_file")&&String((y==null?void 0:y.path)??n.path??"")&&i.jsx("a",{href:Xk(String((y==null?void 0:y.path)??n.path),N),className:"text-accent-primary hover:underline ml-auto",children:"Open in VSCode"})]}),r==="error"&&c&&t!=="run_command"&&i.jsxs("div",{children:[i.jsx("div",{className:"text-[10px] text-accent-error mb-0.5",children:"Error:"}),i.jsx("pre",{className:"text-xs bg-bg-primary p-1.5 rounded text-accent-error break-words",children:c})]}),D&&i.jsx(P8,{confirmation:D})]})]})}),U8={read_file:"Reading file",write_file:"Writing file",edit_file:"Editing file",run_command:"Running command",glob:"Searching files",grep:"Searching content",ask_user:"Asking user",criterion:"Managing criterion",session_metadata:"Managing",todo_write:"Updating tasks"};function F8(e,t){const n=U8[e];if(!n)return`Preparing ${e}`;if(e==="session_metadata"&&t)try{const a=JSON.parse(t).key;if(a){const l=EB(a);return`${n} ${l}`}}catch{}return n}function V8(e){try{const t=e.replace(/\s*\}\s*$/,""),n=JSON.parse(t);if(typeof n.command=="string")return n.command}catch{const t=e.match(/"command"\s*:\s*"([^"]*)/);if(t&&t[1])return t[1]}return null}const G8=E.memo(function({name:t,arguments:n}){let a=F8(t,n)+"...";if(t==="run_command"&&n){const l=V8(n);l&&(a=l)}return i.jsx("div",{className:"border border-border rounded overflow-hidden my-1 min-w-0 animate-pulse",children:i.jsxs("div",{className:"flex items-center gap-1.5 p-2 bg-bg-tertiary",children:[i.jsx("span",{className:"text-accent-warning animate-pulse",children:"..."}),i.jsx(ij,{tool:t}),i.jsx("span",{className:"font-mono text-accent-primary text-sm",children:t}),t==="run_command"&&n?i.jsx("code",{className:"text-text-muted text-xs flex-1 truncate",children:a}):i.jsx("span",{className:"text-text-muted text-xs flex-1",children:a})]})})}),W8={pending:{icon:"○",color:"text-text-muted"},in_progress:{icon:"●",color:"text-accent-warning",animate:!0},completed:{icon:"✓",color:"text-accent-success"}},q8=E.memo(function({todos:t}){return Array.isArray(t)?t.length===0?i.jsx("div",{className:"text-xs text-text-muted italic my-1",children:"No tasks"}):i.jsxs("div",{className:"my-1 rounded border border-border bg-bg-tertiary overflow-hidden",children:[i.jsx("div",{className:"px-2 py-1.5 border-b border-border bg-bg-secondary",children:i.jsx("span",{className:"text-xs font-medium text-text-muted",children:"Tasks"})}),i.jsx("div",{children:t.map((n,r)=>{const a=W8[n.status];return i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${r>0?"border-t border-border":""}`,children:[i.jsx("span",{className:`${(a==null?void 0:a.color)??"text-text-muted"} ${a!=null&&a.animate?"animate-pulse":""} text-sm leading-tight`,children:(a==null?void 0:a.icon)??"○"}),i.jsx("span",{className:`text-sm leading-tight ${n.status==="completed"?"text-text-muted":"text-text-primary"}`,children:n.content})]},r)})})]}):i.jsx("div",{className:"text-xs text-accent-warning italic my-1",children:"⚠️ Invalid todos data"})});function K8({toolCall:e}){var j;const t=Le(N=>N.pendingQuestions),n=Le(N=>N.answerQuestion),[r,a]=E.useState(""),l=E.useRef(null),u=E.useRef(null),c=t.find(N=>N.callId===e.id),d=e.arguments.question??(c==null?void 0:c.question)??"",h=e.arguments.type??(c==null?void 0:c.type)??"text",p=e.arguments.options??(c==null?void 0:c.options)??void 0,m=e.result!==void 0,x=c!==void 0&&!m,y=((j=e.result)==null?void 0:j.output)??"",w=y==="[user skipped]";E.useEffect(()=>{x&&l.current&&l.current.focus()},[x]),E.useEffect(()=>{x&&u.current&&u.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]);const C=E.useCallback(()=>{c&&n(c.callId,r)},[c,r,n]),_=E.useCallback(()=>{c&&n(c.callId,"",!0)},[c,n]),S=E.useCallback(N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),C()),N.key==="Escape"&&!N.shiftKey&&(N.preventDefault(),_())},[C,_]),v=E.useCallback(N=>{c&&n(c.callId,N)},[c,n]),b="px-3 py-1.5 text-xs font-medium rounded transition-colors";return i.jsxs("div",{ref:u,className:"my-1",children:[i.jsx("div",{className:"text-sm text-text-primary",children:d}),x&&i.jsx("div",{className:"mt-2 border border-border rounded overflow-hidden",children:i.jsx("div",{className:"p-3 bg-primary space-y-2",children:h==="confirm"?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>v("yes"),className:`${b} flex-1 bg-accent-success/20 hover:bg-accent-success/30 text-accent-success border border-accent-success/30`,children:"Yes"}),i.jsx("button",{onClick:()=>v("no"),className:`${b} flex-1 bg-accent-error/20 hover:bg-accent-error/30 text-accent-error border border-accent-error/30`,children:"No"}),i.jsx("button",{onClick:_,className:`${b} bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border`,children:"Skip"})]}):h==="choice"&&Array.isArray(p)&&p.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(N=>i.jsx("button",{onClick:()=>v(N),className:`${b} text-left w-full bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary border border-border hover:border-accent-primary/50`,children:N},N))}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("textarea",{ref:l,value:r,onChange:N=>a(N.target.value),onKeyDown:S,placeholder:"Or type your own answer... (Enter to submit)",className:"flex-1 min-h-[36px] max-h-[80px] px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 resize-y",rows:1}),i.jsx("button",{onClick:C,disabled:!r.trim(),className:`${b} bg-accent-primary/25 hover:bg-accent-primary/40 text-text-primary disabled:opacity-50 disabled:cursor-not-allowed`,children:"Send"}),i.jsx("button",{onClick:_,className:`${b} bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border`,children:"Skip"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("textarea",{ref:l,value:r,onChange:N=>a(N.target.value),onKeyDown:S,placeholder:"Type your answer here... (Enter to submit, Shift+Enter for new line)",className:"w-full min-h-[80px] px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 resize-y",autoFocus:!0}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{onClick:_,className:`${b} bg-bg-tertiary hover:bg-bg-tertiary/80 text-text-secondary border border-border`,children:"Skip"}),i.jsx("button",{onClick:C,disabled:!r.trim(),className:`${b} bg-accent-primary/25 hover:bg-accent-primary/40 text-text-primary disabled:opacity-50 disabled:cursor-not-allowed`,children:"Send Answer"})]})]})})}),m&&i.jsx("div",{className:"mt-1 flex items-center gap-2",children:i.jsx("span",{className:`text-xs ${w?"text-amber-400":"text-accent-success"}`,children:w?"Skipped":`Answered: ${y}`})})]})}const $S={add:{icon:"○",color:"text-text-muted"},update:{icon:"○",color:"text-text-muted"},remove:{icon:"○",color:"text-text-muted"},complete:{icon:"◉",color:"text-purple-400"},pass:{icon:"✓",color:"text-accent-success"},fail:{icon:"✗",color:"text-accent-error"},get:{icon:"○",color:"text-text-muted"},list:{icon:"○",color:"text-text-muted"},schema:{icon:"○",color:"text-text-muted"}},Y8=E.memo(function({toolCalls:t,criteria:n}){if(t.length===0)return null;const r=new Map((n==null?void 0:n.map(c=>[c.id,c]))??[]),a=t.find(c=>{var d,h;return c.arguments.action==="get"&&((d=c.result)==null?void 0:d.success)&&((h=c.result)==null?void 0:h.output)}),l=t.some(c=>c.name==="session_metadata"),u=(()=>{if(!l)return"Acceptance Criteria";const c=new Set(t.map(d=>d.arguments.key).filter(Boolean));if(c.size===1){const d=c.values().next().value;return d?so(d):"Session Data"}return"Session Data"})();return i.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[i.jsx("div",{className:"px-2 py-1.5 border-b border-border bg-secondary",children:i.jsx("span",{className:"text-xs font-medium text-text-muted",children:u})}),i.jsx("div",{className:"bg-primary",children:a?(()=>{const c=a.result.output;if(c==="No criteria defined yet.")return i.jsxs("div",{className:"flex items-start gap-2 px-2 py-1.5",children:[i.jsx("span",{className:"text-text-muted text-sm leading-tight flex-shrink-0",children:"○"}),i.jsx("div",{className:"flex-1 min-w-0 text-text-muted text-sm",children:"No criteria defined yet."})]});try{return JSON.parse(c).map((h,p)=>i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${p>0?"border-t border-border":""}`,children:[i.jsx("span",{className:"text-text-muted text-sm leading-tight flex-shrink-0",children:"○"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx(zn,{content:`[${h.id}] ${h.description}`})})]},h.id??p))}catch{return t.map((d,h)=>i.jsx(zS,{tc:d,index:h,criteriaMap:r},d.id??h))}})():t.map((c,d)=>i.jsx(zS,{tc:c,index:d,criteriaMap:r},c.id??d))})]})});function zS({tc:e,index:t,criteriaMap:n}){const r=e.arguments.action,a=e.arguments,l=e.name==="session_metadata",u=r==="remove",c=a.id,d=a.description,h=c?n.get(c):void 0,p=d??(h==null?void 0:h.description)??(u&&c?`[${c}]`:"Criterion updated"),m=a.reason,x=r==="fail";return i.jsxs("div",{className:`flex items-start gap-2 px-2 py-1.5 ${t>0?"border-t border-border":""}`,children:[l?i.jsx(xo,{status:a.status,className:"text-sm leading-tight flex-shrink-0"}):(()=>{const y=r&&$S[r]?$S[r]:{icon:"○",color:"text-text-muted"};return i.jsx("span",{className:`${y.color} text-sm leading-tight flex-shrink-0`,children:y.icon})})(),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:u?"line-through text-text-muted":"",children:i.jsx(zn,{content:p})}),m&&i.jsxs("div",{className:`mt-1 text-sm ${x?"text-accent-error":"text-text-muted"}`,children:[i.jsx("span",{className:"text-text-muted",children:"└ "}),'"',m,'"']})]})]})}function X8(e){return e==="criterion"||e==="session_metadata"}async function oj(e){if(navigator.clipboard){await navigator.clipboard.writeText(e);return}const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}function Q8({items:e,position:t,onClose:n}){const r=E.useRef(null),[a,l]=E.useState(-1);if(E.useEffect(()=>{t&&l(-1)},[t]),E.useEffect(()=>{var p;if(!t)return;function d(m){r.current&&!r.current.contains(m.target)&&n()}function h(m){var x;switch(m.key){case"Escape":m.preventDefault(),n();break;case"ArrowDown":m.preventDefault(),l(y=>y<e.length-1?y+1:0);break;case"ArrowUp":m.preventDefault(),l(y=>y>0?y-1:e.length-1);break;case"Enter":m.preventDefault(),(x=e[a])==null||x.onClick(),n();break}}return document.addEventListener("mousedown",d),window.addEventListener("keydown",h,!0),window.addEventListener("blur",n),(p=r.current)==null||p.focus(),()=>{document.removeEventListener("mousedown",d),window.removeEventListener("keydown",h,!0),window.removeEventListener("blur",n)}},[t,e,a,n]),!t)return null;let u=Math.min(t.x,window.innerWidth-190),c=Math.min(t.y,window.innerHeight-100);return u=Math.max(8,u),c=Math.max(8,c),mi.createPortal(i.jsx("div",{ref:r,tabIndex:-1,className:"fixed bg-bg-secondary border border-border rounded shadow-lg z-50 min-w-[160px] outline-none",style:{left:u,top:c},children:i.jsx("div",{className:"max-h-[60vh] overflow-y-auto",onMouseLeave:()=>l(-1),children:e.map((d,h)=>i.jsxs("button",{onClick:()=>{d.onClick(),n()},onMouseEnter:()=>l(h),className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${h<e.length-1?"border-b border-border":""} ${d.danger?"text-accent-error hover:bg-accent-error/10":h===a?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"}`,children:[d.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0",children:d.icon}),d.label]},h))})}),document.body)}function lj(){const[e,t]=E.useState(null);return{onContextMenu:E.useCallback((a,l)=>{var u;l&&((u=window.getSelection())!=null&&u.toString()||(a.preventDefault(),t({x:a.clientX,y:a.clientY})))},[]),contextMenu:a=>i.jsx(Q8,{position:e,onClose:()=>t(null),items:a})}}function J8(e){const t=[];let n=[];const r=()=>{n.length>0&&(t.push({type:"criteria_group",toolCalls:n}),n=[])};for(const a of e)a.type==="tool_call"&&X8(a.toolCall.name)?n.push(a.toolCall):(r(),t.push(a));return r(),t}function Z8(e,t){if(e.segments&&e.segments.length>0)return e$(e.segments,e.toolCalls??[],e.preparingToolCalls??[],e.stats,t);const n=[];if(e.thinkingContent&&n.push({type:"thinking",content:e.thinkingContent}),e.content&&n.push({type:"text",content:e.content}),e.toolCalls)for(const r of e.toolCalls)n.push({type:"tool_call",toolCall:r});if(e.preparingToolCalls)for(const r of e.preparingToolCalls)n.push({type:"preparing_tool_call",preparing:r});return t&&e.stats&&n.push({type:"stats",stats:e.stats}),n}function e$(e,t,n,r,a){const l=[],u=new Map(t.map(c=>[c.id,c]));for(const c of e)switch(c.type){case"text":l.push({type:"text",content:c.content});break;case"thinking":c.content&&c.content.trim().length>0&&l.push({type:"thinking",content:c.content});break;case"tool_call":{const d=u.get(c.toolCallId);d&&l.push({type:"tool_call",toolCall:d});break}}for(const c of n)l.push({type:"preparing_tool_call",preparing:c});return a&&r&&l.push({type:"stats",stats:r}),l}const tx=E.memo(function({message:t,showStats:n=!0,showThinking:r=!0,showVerboseToolOutput:a=!0,sessionId:l}){const u=Le(T=>{var D,L;return(L=(D=T.currentSession)==null?void 0:D.metadataEntries)==null?void 0:L.criteria}),c=xt(T=>T.defaults),d=xt(T=>T.userItems),h=[...c,...d],p=Z8(t,n),m=r?p:p.filter(T=>T.type!=="thinking"),x=J8(m),[y,w]=E.useState(!1),[C,_]=E.useState(null),[,S]=Tn(),{onContextMenu:v,contextMenu:b}=lj();if(x.length===0)return null;const j=()=>{oj(t.content)},N=async()=>{if(!l||y)return;w(!0),_(null);const T=await p1(l,t.id);w(!1),T!=null&&T.session?S(`/p/${T.session.projectId}/s/${T.session.id}`):_("Failed to fork session")};return i.jsxs("div",{className:"feed-item",onContextMenu:T=>v(T,!!l),children:[i.jsxs("div",{className:"min-w-0",children:[C&&i.jsx("p",{className:"text-xs text-accent-error mb-1 ml-0.5",children:C}),x.map((T,D)=>{var L;switch(T.type){case"thinking":return i.jsx(_8,{content:T.content},D);case"text":return i.jsx("div",{className:"prose prose-sm prose-invert max-w-none",children:i.jsx(zn,{content:T.content})},D);case"preparing_tool_call":return i.jsx(G8,{name:T.preparing.name,arguments:T.preparing.arguments},`preparing-${T.preparing.index}`);case"tool_call":{const O=T.toolCall,M=O.result;if(O.name==="ask_user")return i.jsx(K8,{toolCall:O},D);if(O.name==="todo_write"){const R=O.arguments.todos,H=Array.isArray(R)?R:[];return i.jsx(q8,{todos:H},D)}const W=(L=M==null?void 0:M.output)==null?void 0:L.includes("[interrupted by user]"),U=M?W?"interrupted":M.success?"success":"error":"pending";return i.jsx(H8,{tool:O.name,args:O.arguments,status:U,variant:"expandable",forceCompact:!a,result:M==null?void 0:M.output,error:M==null?void 0:M.error,durationMs:M==null?void 0:M.durationMs,diagnostics:M==null?void 0:M.diagnostics,editContext:M==null?void 0:M.editContext,startedAt:O.startedAt,streamingOutput:O.streamingOutput,metadata:M==null?void 0:M.metadata,truncated:(M==null?void 0:M.truncated)??!1,callId:O.id},D)}case"criteria_group":return i.jsx(Y8,{toolCalls:T.toolCalls,criteria:u},D);case"stats":{const O=T.stats;if(!O||"error"in O)return null;const M=O.model.split("/").pop()??O.model,W=Vl(h,O.mode),U=h.find(V=>V.id===O.mode),R=(U==null?void 0:U.name)??O.mode,H=V=>V>=1e3?`${(V/1e3).toFixed(1)}k`:V.toString(),G=V=>V>=1e3?`${(V/1e3).toFixed(1)}k`:V.toFixed(1);return i.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[10px] text-text-muted mt-3",children:[i.jsx("span",{className:"flex-1 h-px bg-border"}),i.jsx("span",{className:"text-text-secondary",children:M}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("span",{style:{color:W},children:R}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("span",{children:Yr(O.totalTime)}),O.toolTime>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsxs("span",{children:[Yr(O.toolTime)," tools"]})]}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsxs("span",{children:[H(O.prefillTokens)," @ ",G(O.prefillSpeed)," pp"]}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsxs("span",{children:[H(O.generationTokens)," @ ",G(O.generationSpeed)," tg"]}),i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("button",{type:"button",className:"text-text-muted hover:text-text-secondary transition-colors",title:"View detailed stats",onClick:()=>{const V=new CustomEvent("open-turn-stats",{detail:{stats:O}});window.dispatchEvent(V)},children:i.jsx(ag,{className:"w-3 h-3"})}),i.jsx("span",{className:"flex-1 h-px bg-border"})]},D)}}}),t.partial&&i.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-accent-warning mt-1",children:[i.jsx(yp,{}),i.jsx("span",{children:"Aborted"})]}),t.completeReason==="truncated"&&i.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-text-truncated mt-1",children:[i.jsx(yp,{}),i.jsx("span",{children:"Response was truncated — the model ran out of output tokens."})]})]}),b([{label:"Copy",icon:i.jsx(Rl,{className:"w-4 h-4"}),onClick:()=>j()},{label:"Fork session from here",icon:i.jsx(Ki,{className:"w-4 h-4"}),onClick:()=>void N()}])]})});function vd(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n},${r},${a},${t})`}function t$(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}const n$=E.memo(function({data:t}){var u;const n=vt(c=>c.defaults),r=vt(c=>c.userItems),l=((u=[...n,...r].find(c=>c.id===t.workflowId))==null?void 0:u.color)??t.workflowColor??"#8b949e";return i.jsxs("div",{"data-testid":"task-completed-card",className:"feed-item rounded p-3 border",style:{borderColor:vd(l,.3),backgroundColor:vd(l,.08)},children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(fT,{color:l}),i.jsx("span",{className:"text-sm font-medium",style:{color:l},children:t.workflowName??"Task Completed"})]}),i.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-5 gap-2",children:[i.jsx(vl,{label:"Iterations",value:String(t.iterations)}),i.jsx(vl,{label:"Total time",value:Yr(t.totalTimeSeconds)}),i.jsx(vl,{label:"Tool calls",value:String(t.totalToolCalls)}),i.jsx(vl,{label:"Tokens",value:t$(t.totalTokensGenerated)}),i.jsx(vl,{label:"Speed",value:t.avgGenerationSpeed>0?`${t.avgGenerationSpeed} tok/s`:"-"})]})]})});function vl({label:e,value:t}){return i.jsxs("div",{className:"bg-bg-primary/50 rounded px-2 py-1",children:[i.jsx("div",{className:"text-sm text-text-muted",children:e}),i.jsx("div",{className:"text-sm text-text-primary font-medium",children:t})]})}const r$=E.memo(function({data:t}){var u;const n=vt(c=>c.defaults),r=vt(c=>c.userItems),l=((u=[...n,...r].find(c=>c.id===t.workflowId))==null?void 0:u.color)??t.workflowColor??"#6b7280";return i.jsxs("div",{className:"feed-item flex items-center gap-2 px-3 py-2 rounded border",style:{borderColor:vd(l,.3),backgroundColor:vd(l,.08)},children:[i.jsx(A1,{className:"w-3 h-3 shrink-0",color:l}),i.jsx("span",{className:"text-sm font-medium",style:{color:l},children:t.workflowName}),i.jsx("span",{className:"text-text-muted text-sm",children:"started"})]})}),s$=["text/"],i$=["application/json","application/xml","application/yaml","application/x-yaml","application/javascript","application/xhtml+xml","application/x-sh","image/svg+xml"];function Yu(e){return e.startsWith("image/")}function cj(e){return e.startsWith("image/")&&e!=="image/svg+xml"}function nx(e){return i$.includes(e)||s$.some(t=>e.startsWith(t))}function Za(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function uj(e){const t=e.lastIndexOf(".");return t<=0||t>=e.length-1?"FILE":e.slice(t+1).toUpperCase()}const a$={"text/plain":"txt","text/csv":"csv","text/html":"html","text/markdown":"md","text/javascript":"js","text/xml":"xml","text/x-yaml":"yaml","text/x-sh":"sh","text/tab-separated-values":"tsv","text/x-python":"py","text/x-java-source":"java","text/x-json":"json","text/x-typescript":"ts","text/css":"css","application/json":"json","application/xml":"xml","application/yaml":"yaml","application/x-yaml":"yaml","application/javascript":"js","application/xhtml+xml":"xhtml","application/x-sh":"sh","application/pdf":"pdf","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp","image/svg+xml":"svg"};function o$(e){var t;return a$[e]||((t=e.split("/")[1])==null?void 0:t.split("+")[0])||"file"}function l$(e){return Yu(e)||nx(e)||e==="application/pdf"}function c$({attachments:e,messageId:t}){const[n,r]=E.useState(null),a=Le(p=>p.visionFallbackByMessage),l=Le(p=>p.messages),u=E.useMemo(()=>{const p=l.findIndex(m=>m.id===t);if(p===-1)return null;for(let m=p+1;m<l.length;m++){const x=l[m];if(x&&x.role==="assistant")return x.id}return null},[l,t]),c=p=>{r(p)},d=()=>{r(null)},h=p=>{const m=`${t}-${p}`;if(a[m])return a[m];if(u){const x=`${u}-${p}`;return a[x]}return null};return e.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:e.map(p=>{const m=h(p.id);return cj(p.mimeType)?i.jsxs("div",{className:"relative inline-block",children:[i.jsxs("button",{onClick:()=>c(p.data),className:"group relative inline-block",title:(m==null?void 0:m.type)==="done"&&m.description||p.description||p.filename,disabled:(m==null?void 0:m.type)==="start",children:[i.jsx("img",{src:p.data,alt:(m==null?void 0:m.type)==="done"&&m.description||p.description||p.filename,className:"max-w-[256px] max-h-[256px] object-contain rounded-lg border border-border hover:border-accent-primary transition-colors cursor-pointer"}),(m==null?void 0:m.type)==="start"&&i.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center rounded-lg",children:i.jsx("span",{className:"text-xs text-text-primary animate-pulse",children:"Describing image..."})})]}),(m==null?void 0:m.type)==="done"&&m.description&&i.jsxs("div",{className:"mt-2 p-2 bg-bg-tertiary rounded text-xs text-text-secondary max-w-[256px]",children:[m.description.slice(0,200),m.description.length>200?"...":""]})]},p.id):i.jsxs("div",{className:"inline-flex items-start gap-3 p-3 bg-bg-tertiary rounded-lg border border-border max-w-[300px]",children:[i.jsx("div",{className:"w-10 h-10 flex items-center justify-center rounded-md bg-bg-secondary text-sm font-bold text-text-muted shrink-0",children:uj(p.filename)}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"text-xs text-text-primary truncate font-medium",title:p.filename,children:p.filename}),i.jsx("div",{className:"text-[10px] text-text-muted",children:Za(p.size)}),nx(p.mimeType)&&p.data&&i.jsxs("div",{className:"mt-1.5 text-[10px] text-text-muted leading-relaxed line-clamp-3 font-mono break-all",children:[p.data.slice(0,200),p.data.length>200?"...":""]})]})]},p.id)})}),n&&i.jsx(rj,{src:n,alt:"Attached image",isOpen:!0,onClose:d})]})}function u$({message:e}){const[t,n]=E.useState(!1);if(e.messageKind!=="auto-prompt")return null;const r=e.metadata,a=(r==null?void 0:r.color)??"#6b7280",l=(r==null?void 0:r.type)??"agent",u=l==="workspace"?"Workspace":(r==null?void 0:r.name)??"Agent",d={agent:(r==null?void 0:r.kind)==="reminder"?"reminder":"definition injected",workflow:"instructions",compaction:"prompt injected",subagent:"instructions",workspace:`${(r==null?void 0:r.workspaceName)??""} · ${(r==null?void 0:r.branchName)??""}`,branch:`🌿 ${(r==null?void 0:r.branchName)??""}`}[l]??"injected",h=l==="workflow"||l==="subagent";return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[10px] text-text-muted font-mono mt-3 mb-4",children:[i.jsx("span",{className:"flex-1 h-px bg-border"}),i.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${h?"":"cursor-pointer"}`,style:{backgroundColor:a},onClick:()=>!h&&n(!0)}),i.jsx("span",{className:h?"":"cursor-pointer hover:text-text-secondary transition-colors",style:{color:a},onClick:()=>!h&&n(!0),children:u}),i.jsx("span",{children:"·"}),i.jsx("span",{className:h?"":"cursor-pointer hover:text-text-secondary transition-colors",onClick:()=>!h&&n(!0),children:d}),i.jsx("span",{className:"flex-1 h-px bg-border"})]}),h&&i.jsx("div",{className:"flex justify-center feed-item mb-4",children:i.jsx("div",{className:"max-w-[75%] rounded p-3 bg-bg-tertiary/50 text-text-secondary text-sm overflow-x-auto",style:{borderLeft:`3px solid ${a}`},children:i.jsx("pre",{className:"whitespace-pre-wrap break-words font-mono text-xs",children:e.content})})}),i.jsx(jt,{isOpen:t,onClose:()=>n(!1),title:`${u} Prompt`,size:"lg",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:a}}),i.jsx("span",{className:"text-sm text-text-primary font-medium",children:u}),i.jsxs("span",{className:"text-xs text-text-muted",children:["(",l,")"]})]}),i.jsx("div",{className:"h-full min-h-96",children:i.jsx("pre",{className:"text-sm text-text-secondary whitespace-pre-wrap break-words bg-bg-tertiary rounded p-4 h-full min-h-96 overflow-auto font-mono",children:e.content})})]})})]})}function d$({message:e,messageId:t,sessionId:n}){const r=e.messageKind==="auto-prompt",a=e.messageKind==="command",l=e.isSystemGenerated,u=Le($=>$.loadSession),[,c]=Tn(),[d,h]=E.useState(!1),[p,m]=E.useState(!1),[x,y]=E.useState(!1),[w,C]=E.useState(e.content),[_,S]=E.useState(!1),[v,b]=E.useState(!1),[j,N]=E.useState(null),[T,D]=E.useState(null),L=E.useRef(null),{onContextMenu:O,contextMenu:M}=lj(),W=E.useCallback(()=>{const $=L.current;$&&($.style.height="auto",$.style.height=`${$.scrollHeight}px`)},[]),U=async()=>{try{await oj(e.content),m(!0),window.setTimeout(()=>m(!1),1500)}catch{}},R=async()=>{if(!n||!t||v)return;b(!0),N(null);const $=await p1(n,t);if(b(!1),$!=null&&$.session){const I=$.session.projectId;c(`/p/${I}/s/${$.session.id}`)}else N("Failed to fork session")},H=async()=>{if(!n||!t||_)return;S(!0),D(null);const $=await y_(n,t);S(!1),$?u(n):D("Failed to replay")},G=async()=>{if(!n||!t||!w.trim()||_)return;S(!0),D(null);const $=await y_(n,t,w);S(!1),$?(u(n),y(!1)):D("Failed to send")},V=()=>{C(e.content),y(!1),D(null)},X=`flex items-center gap-0.5 self-end transition-[visibility,opacity] focus-within:visible focus-within:opacity-100 ${d&&!x&&!_?"visible opacity-100":"invisible opacity-0"}`;return i.jsxs("div",{className:"flex justify-end items-start gap-1.5 feed-item",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onContextMenu:$=>O($,!!n&&!!t),children:[!l&&i.jsxs("div",{className:X,children:[i.jsx("button",{onClick:()=>{U()},title:"Copy",disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",children:p?i.jsx(Mr,{className:"w-3.5 h-3.5 text-accent-success"}):i.jsx(Rl,{className:"w-3.5 h-3.5"})}),n&&t&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>{D(null),C(e.content),y(!0)},title:"Edit & resend",disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",children:i.jsx(j1,{className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>{H()},title:"Replay",disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",children:i.jsx(jd,{className:"w-3.5 h-3.5"})})]})]}),i.jsxs("div",{className:`max-w-[75%] ${x?"w-full":""} rounded p-2 ${l?"bg-bg-system border border-border-system":"bg-accent-primary/15 text-text-primary"}`,children:[l&&i.jsx("span",{className:"text-[10px] block mb-0.5 text-text-system",children:a?"Command":r?"Auto":"System"}),x?i.jsxs("div",{className:"flex flex-col gap-1.5",children:[i.jsx("textarea",{ref:$=>{L.current=$,$&&($.style.height="auto",$.style.height=`${$.scrollHeight}px`)},className:"w-full bg-bg-primary border border-border rounded p-1.5 text-sm text-text-primary resize-none focus:outline-none focus:border-accent-primary min-h-[60px] overflow-hidden disabled:opacity-50",value:w,onChange:$=>{C($.target.value),W()},onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),G()),$.key==="Escape"&&V()},disabled:_,autoFocus:!0}),T&&i.jsx("p",{className:"text-xs text-accent-error",children:T}),i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:V,disabled:_,className:"p-1 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary disabled:opacity-50",title:"Cancel",children:i.jsx(js,{className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>{G()},disabled:_||!w.trim(),className:"p-1 rounded hover:bg-bg-tertiary text-accent-primary hover:text-accent-primary disabled:opacity-50",title:"Confirm (Ctrl+Enter)",children:i.jsx(Mr,{className:"w-3.5 h-3.5"})})]})]}):i.jsxs(i.Fragment,{children:[(T||j)&&i.jsx("p",{className:"text-xs text-accent-error mb-1",children:T??j}),i.jsx("div",{className:`whitespace-pre-wrap break-words text-sm ${l?"text-text-system":""}`,children:e.content}),e.attachments&&e.attachments.length>0&&i.jsx(c$,{attachments:e.attachments,messageId:e.id})]})]}),M([{label:"Copy",icon:i.jsx(Rl,{className:"w-4 h-4"}),onClick:()=>void U()},{label:"Fork session from here",icon:i.jsx(Ki,{className:"w-4 h-4"}),onClick:()=>void R()}])]})}const dj=E.memo(function({message:t,isLastAssistantMessage:n=!1,messageId:r,sessionId:a}){const l=t.role==="user",u=t.role==="assistant",c=t.role==="system",d=t.role==="tool";if(u)return i.jsx(tx,{message:t,showStats:n});if(c&&t.isCompacted)return i.jsxs("div",{className:"feed-item bg-bg-tertiary/50 border border-border rounded p-2",children:[i.jsx("div",{className:"text-text-muted text-xs mb-0.5",children:"[Compacted]"}),i.jsx("div",{className:"text-text-secondary text-xs whitespace-pre-wrap",children:t.content.replace(`[COMPACTED HISTORY]
300
+ `,"")})]});if(d)return i.jsxs("div",{className:"feed-item bg-bg-tertiary/30 border-l-2 border-accent-primary rounded-r p-2",children:[i.jsxs("div",{className:"text-accent-primary text-xs mb-0.5",children:["Tool: ",t.toolName]}),i.jsxs("pre",{className:"text-text-secondary text-xs whitespace-pre-wrap break-words overflow-x-auto max-h-32",children:[t.content.slice(0,500),t.content.length>500&&"..."]})]});if(t.messageKind==="workflow-started")try{const h=JSON.parse(t.content);return i.jsx(r$,{data:h})}catch{}if(t.messageKind==="task-completed")try{const h=JSON.parse(t.content);return i.jsx(n$,{data:h})}catch{}return t.messageKind==="context-reset"?i.jsxs("div",{className:"flex items-center gap-4 mb-6 text-text-muted text-xs uppercase tracking-wide",children:[i.jsx("div",{className:"flex-1 border-t border-border"}),i.jsx("span",{children:t.content}),i.jsx("div",{className:"flex-1 border-t border-border"})]}):t.messageKind==="auto-prompt"&&t.isSystemGenerated?i.jsx(u$,{message:t}):t.messageKind==="correction"&&t.isSystemGenerated?i.jsx("div",{className:"flex justify-end feed-item",children:i.jsxs("div",{className:"max-w-[75%] rounded p-2 bg-bg-system border border-border-system",children:[i.jsx("span",{className:"text-[10px] block mb-0.5 text-text-system",children:"System"}),i.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-text-system italic",children:t.content})]})}):l?i.jsx(d$,{message:t,messageId:r,sessionId:a}):i.jsx("div",{className:"flex justify-start feed-item",children:i.jsx("div",{className:"max-w-[75%] rounded p-2 bg-bg-tertiary text-text-primary",children:i.jsx(zn,{content:t.content})})})}),h$={verifier:"Verification",code_reviewer:"Code Review",test_generator:"Test Generation",debugger:"Debug"};function f$(e){return{backgroundColor:`${e}20`,color:e,borderColor:`${e}4d`}}function HS(e,t){return t||e>85?"text-accent-error":e>60?"text-accent-warning":"text-text-muted"}function m$({contextState:e}){const{currentTokens:t,maxTokens:n,compactionCount:r,dangerZone:a}=e,l=Math.round(t/n*100);return i.jsxs("div",{className:"flex items-center gap-1.5 text-[10px]",children:[i.jsxs("span",{className:HS(l,a),children:[oo(t),"/",oo(n)]}),i.jsxs("span",{className:HS(l,a),children:["(",l,"%)"]}),i.jsx(Zg,{percent:l,dangerZone:a,size:"sm"}),a&&i.jsx("span",{className:"text-accent-error animate-pulse",children:"Low!"}),r>0&&i.jsxs("span",{className:"text-text-muted bg-bg-tertiary px-1 rounded",children:[r,"x"]})]})}const p$=E.memo(function({messages:t,subAgentType:n,subAgentId:r,isStreaming:a}){const l=E.useRef(null),u=E.useRef(null),[c,d]=E.useState(!1),h=xt(D=>D.defaults),p=xt(D=>D.userItems),m=[...h,...p],x=Le(D=>D.subAgentContextStates[r]),{showThinking:y,showVerboseToolOutput:w}=Zi(),{isAutoScrollActive:C,setAutoScroll:_}=Qd(u,null),S=E.useCallback(()=>{const D=!c;d(D),D&&setTimeout(()=>{var L;(L=l.current)==null||L.scrollIntoView({block:"start",behavior:"smooth"})},220)},[c]),v=m.find(D=>D.id===n),b=(v==null?void 0:v.name)??h$[n]??n,j=Vl(m,n),N=f$(j),T=t.filter(D=>D.role!=="tool");return i.jsxs("div",{ref:l,className:"feed-item border border-border rounded overflow-hidden bg-secondary",children:[i.jsxs("div",{className:"w-full flex items-center justify-between px-2 py-1 border-b relative",style:N,children:[i.jsx("span",{className:"text-xs font-medium",children:b}),i.jsx("div",{className:"absolute left-1/2 -translate-x-1/2",children:x&&i.jsx(m$,{contextState:x})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5",onClick:()=>_(!C),children:[i.jsx("span",{className:`w-1 h-1 rounded-full ${C?"bg-accent-success":"border border-text-muted"}`}),"live"]}),i.jsxs("button",{type:"button",className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-tertiary",onClick:S,children:[c?"▼":"▶"," Expand"]})]})]}),i.jsx("div",{ref:u,className:`${c?"max-h-[calc(100vh-10rem)]":"max-h-80"} overflow-y-auto p-2 transition-[max-height] duration-200`,children:T.map(D=>D.role==="assistant"?i.jsx(tx,{message:D,showStats:!0,showThinking:y,showVerboseToolOutput:w},D.id):i.jsx(dj,{message:D,isLastAssistantMessage:!1},D.id))})]})}),cp={contentVisibility:"auto",containIntrinsicSize:"auto 200px"};function Pu(e){var t;return e.type==="context-divider"?`ctx-${e.windowSequence}`:e.type==="subagent"?((t=e.messages[0])==null?void 0:t.id)??e.subAgentId:e.message.id}const hj=E.memo(function({displayItems:t,highlightedMessageId:n=null,sessionId:r,showThinking:a=!0,showVerboseToolOutput:l=!0,showStats:u=!0,showAgentDefinitions:c=!0,showWorkflowBars:d=!0}){return i.jsx(i.Fragment,{children:t.map((h,p)=>{if(h.type==="context-divider")return i.jsxs("div",{"data-item-index":p,className:"flex items-center gap-2 feed-item px-2 md:px-4",children:[i.jsx("div",{className:"flex-1 border-t border-border"}),i.jsx("span",{className:"text-[10px] text-text-muted font-medium px-2",children:"Earlier context summarized"}),i.jsx("div",{className:"flex-1 border-t border-border"})]},Pu(h));if(h.type==="subagent"){const w=h.messages.some(C=>C.isStreaming);return i.jsx("div",{"data-item-index":p,className:"px-2 md:px-4",style:cp,children:i.jsx(p$,{messages:h.messages,subAgentType:h.subAgentType,subAgentId:h.subAgentId,isStreaming:w})},Pu(h))}const m=h.message;if(m.role==="assistant")return i.jsx("div",{"data-item-index":p,className:"px-2 md:px-4",style:cp,children:i.jsx(tx,{message:m,showStats:u,showThinking:a,showVerboseToolOutput:l,sessionId:r??void 0})},Pu(h));const x=!c&&m.messageKind==="auto-prompt",y=!d&&(m.messageKind==="workflow-started"||m.messageKind==="task-completed");return x||y?null:i.jsx("div",{"data-item-index":p,className:"px-2 md:px-4",style:cp,children:i.jsx("div",{"data-message-id":m.id,className:n===m.id?"rounded animate-highlight-fade":void 0,children:i.jsx(dj,{message:m,messageId:m.id,sessionId:r??void 0,isLastAssistantMessage:!1})})},Pu(h))})})});function Jd(e,t,n=!0){E.useEffect(()=>{if(!n)return;const r=a=>{var l;(l=e.current)!=null&&l.contains(a.target)||t()};return document.addEventListener("mousedown",r),()=>document.removeEventListener("mousedown",r)},[e,t,n])}const g$=[],x$=E.memo(function({displayItems:t,scrollContainerRef:n,highlightedMessageId:r,onLaunchWorkflow:a,onScrollToTop:l,hiddenCount:u=0}){const c=Le(Q=>{var K,P;return((P=(K=Q.currentSession)==null?void 0:K.metadataEntries)==null?void 0:P.criteria)??g$}),d=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.id}),h=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.mode}),p=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.phase}),m=Le(Q=>Q.error),x=Le(Q=>Q.clearError),y=kd(),w=Le(Q=>Q.activeWorkflowExecution),C=Le(Q=>Q.continueWorkflow),{showThinking:_,showVerboseToolOutput:S,showStats:v,showAgentDefinitions:b,showWorkflowBars:j}=Zi(),N=vt(Q=>Q.defaults),T=vt(Q=>Q.userItems),D=[...N,...T],L=h==="planner",O=c.length>0,M=p==="done",W=t.some(Q=>Q.type==="message"&&Q.message.role==="assistant"),U=L&&O&&!y&&W&&!M,R=(w==null?void 0:w.status)==="waiting"&&!y,H=Le(Q=>{var K;return(K=Q.currentSession)==null?void 0:K.projectId}),[G,V]=E.useState(!1),[Z,X]=E.useState(!1),[$,I]=E.useState(!1);E.useLayoutEffect(()=>{const Q=n.current;Q&&X(Q.scrollHeight>Q.clientHeight+1)},[n,t]),E.useEffect(()=>{const Q=n.current;if(!Q)return;const K=()=>I(Q.scrollTop>4);return K(),Q.addEventListener("scroll",K,{passive:!0}),()=>Q.removeEventListener("scroll",K)},[n]);const B=()=>{if(!H||!d)return;V(!1),window.open(`/p/${H}/s/${d}/readonly`,"_blank")||V(!0)},[q,z]=E.useState(!1),ne=E.useCallback(()=>{q||(z(!0),C(),setTimeout(()=>z(!1),5e3))},[q,C]),re=E.useCallback(()=>{var Q;l==null||l(),(Q=n.current)==null||Q.scrollTo({top:0,behavior:"smooth"})},[n,l]);return i.jsxs("div",{className:"relative flex-1 min-w-0 group",children:[i.jsxs("div",{ref:n,"data-testid":"chat-scroll-container",className:"absolute inset-0 overflow-y-auto bg-primary scrollbar-stable",children:[i.jsxs("div",{className:"pt-4",children:[u>0&&i.jsxs("div",{className:"px-2 md:px-4 pb-2 space-y-1",children:[i.jsxs("button",{onClick:B,className:"w-full text-sm text-text-muted hover:text-text-primary bg-bg-tertiary/50 hover:bg-bg-tertiary border border-border rounded px-3 py-2 transition-colors text-center",children:[u," older item",u!==1?"s":""," hidden — View full history"]}),G&&i.jsxs("p",{className:"text-xs text-text-muted text-center",children:["Popup blocked."," ",i.jsx("a",{href:H&&d?`/p/${H}/s/${d}/readonly`:"#",target:"_blank",rel:"noopener noreferrer",className:"underline hover:text-text-primary",children:"Open manually"})]})]}),i.jsx(hj,{displayItems:t,highlightedMessageId:r,sessionId:d,showThinking:_,showVerboseToolOutput:S,showStats:v,showAgentDefinitions:b,showWorkflowBars:j})]}),i.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[m&&i.jsx("div",{className:"feed-item bg-text-tool-error/10 border border-text-tool-error/50 rounded p-2",children:i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-text-tool-error text-sm font-medium",children:m.code}),i.jsx("div",{className:"text-text-tool-error/80 text-xs mt-0.5",children:m.message})]}),i.jsx(rc,{onClick:x,className:"text-text-tool-error hover:text-text-tool-error/80 p-0.5",size:"sm"})]})}),R&&w&&i.jsx("div",{className:"flex justify-center gap-2 feed-item",children:i.jsx("button",{onClick:ne,disabled:q,className:"px-4 py-1.5 text-sm font-medium rounded bg-accent-primary/15 text-accent-primary border border-accent-primary/25 hover:bg-accent-primary/25 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:q?"⏳ Continuing...":`▶ Continue ${w.workflowName} (${w.currentStepName??"..."})`})}),U&&i.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:D.map(Q=>{const K=Q.color??"#3b82f6",P=parseInt(K.slice(1,3),16),J=parseInt(K.slice(3,5),16),ie=parseInt(K.slice(5,7),16),he=`rgba(${P},${J},${ie},0.12)`,ce=`rgba(${P},${J},${ie},0.22)`,De=`rgba(${P},${J},${ie},0.25)`;return i.jsx(y$,{workflowName:Q.name,color:K,bg:he,bgHover:ce,border:De,subGroups:Q.subGroups,onLaunch:Re=>a(Q.id,Re)},Q.id)})})]})]}),Z&&$&&i.jsx("div",{className:"absolute top-2 left-1/2 -translate-x-1/2 z-10 pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity duration-200",children:i.jsxs("button",{type:"button",onClick:re,className:"pointer-events-auto 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 backdrop-blur-sm bg-bg-secondary/60",children:[i.jsx(sT,{className:"w-3 h-3"}),"scroll to top"]})})]})});function y$({workflowName:e,color:t,bg:n,bgHover:r,border:a,subGroups:l,onLaunch:u}){const[c,d]=E.useState(!1),h=E.useRef(null);Jd(h,()=>d(!1),c);const p=l&&l.length>0;return i.jsxs("div",{className:"relative flex",children:[i.jsxs("button",{onClick:()=>u(),"data-testid":"workflow-run-button",className:`px-4 py-1.5 text-sm font-medium transition-colors ${p?"rounded-l":"rounded"}`,style:{backgroundColor:n,color:t,border:`1px solid ${a}`,...p?{borderRight:"none"}:{}},onMouseEnter:m=>{m.currentTarget.style.backgroundColor=r},onMouseLeave:m=>{m.currentTarget.style.backgroundColor=n},children:["▶ ",e]}),p&&i.jsxs("div",{ref:h,className:"relative",children:[i.jsx("button",{onClick:()=>d(!c),className:"px-2.5 py-1.5 rounded-r text-sm font-medium transition-colors",style:{backgroundColor:n,color:t,border:`1px solid ${a}`},onMouseEnter:m=>{m.currentTarget.style.backgroundColor=r},onMouseLeave:m=>{m.currentTarget.style.backgroundColor=n},children:"⋮"}),c&&i.jsxs("div",{className:"absolute top-full right-0 mt-1 w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[i.jsx("button",{onClick:()=>{u(),d(!1)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:"Full workflow"}),i.jsx("div",{className:"border-t border-border/50"}),l.map(m=>i.jsx("button",{onClick:()=>{u(m),d(!1)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:m},m))]})]})]})}function b$(){const e=Le(r=>r.connectionStatus),t=Le(r=>r.reconnect);if(e==="connected")return null;const n=e==="reconnecting";return i.jsxs("div",{className:`
301
301
  flex items-center justify-between px-4 py-2
302
302
  text-sm font-medium
303
303
  ${n?"bg-amber-500/15 border-b border-amber-500/30 text-amber-300":"bg-red-500/15 border-b border-red-500/30 text-red-300"}
@@ -305,13 +305,13 @@ 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 Yt=In((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchCommands:async()=>{await kk("/api/commands",e,!0)},fetchCommand:async n=>{try{const r=await ve(`/api/commands/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/commands/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createCommand:async(n,r)=>{const a=await fi("POST","/api/commands",{...n,destination:r});return a.success&&await t().fetchCommands(),a},updateCommand:async(n,r)=>{const a=await fi("PUT",`/api/commands/${n}`,r);return a.success&&await t().fetchCommands(),a},deleteCommand:async n=>{try{const r=await ve(`/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)=>Cd(`/api/commands/${n}/duplicate`,()=>t().fetchCommands(),r)}));function v$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function _$({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(ig,{})})}function f2({isOpen:e,onClose:t,initialEditId:n}){const r=Yt(je=>je.defaults),a=Yt(je=>je.userItems),l=Yt(je=>je.projectItems),u=Yt(je=>je.loading),c=Yt(je=>je.fetchCommands),d=Yt(je=>je.fetchCommand),h=Yt(je=>je.fetchDefaultContent),p=Yt(je=>je.createCommand),m=Yt(je=>je.updateCommand),x=Yt(je=>je.deleteCommand),[y,w]=E.useState(null),[C,_]=E.useState(null),{view:S,editingId:v,formError:b,saving:j,formData:N,setView:T,setEditingId:D,setFormError:L,setFormData:O,setSaving:M}=$1(),{requestDelete:W,clearConfirm:U,isConfirming:R}=Yl(),H=E.useRef(!1),G=xt(je=>je.defaults),V=xt(je=>je.userItems),Z=xt(je=>je.fetchAgents),$=[...G,...V].filter(je=>!je.subagent),I=E.useRef(c),B=E.useRef(Z),q=E.useRef(d),z=E.useRef(h),ne=E.useRef(n),re=E.useRef(T),Q=E.useRef(D),K=E.useRef(L),P=E.useRef(U);E.useEffect(()=>{I.current=c,B.current=Z,q.current=d,z.current=h,ne.current=n,re.current=T,Q.current=D,K.current=L,P.current=U}),E.useEffect(()=>{if(e)if(I.current(),B.current(),H.current||(P.current(),H.current=!0),ne.current){const je=r.some(Me=>Me.id===ne.current);re.current("edit"),Q.current(ne.current),K.current(""),je?z.current(ne.current).then(Me=>{Me&&O({name:Me.metadata.name+" (copy)",id:`${ne.current}-copy-${Date.now()}`,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!0,destination:"user"})}):q.current(ne.current).then(Me=>{Me&&O({name:Me.metadata.name,id:Me.metadata.id,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else re.current("list"),Q.current(null);else H.current=!1},[e]);const J=async je=>{w(je);const Me=await h(je);_((Me==null?void 0:Me.prompt)??null)},ie=async je=>{if(r.some(lt=>lt.id===je)){const lt=await h(je);lt&&(D(null),O({name:`${lt.metadata.name} (copy)`,id:`${je}-copy-${Date.now()}`,prompt:lt.prompt,agentMode:lt.metadata.agentMode??"",isDefault:!0,destination:"user"}),L(""),T("edit"))}else{const lt=await d(je);lt&&(D(null),O({name:`${lt.metadata.name} (copy)`,id:`${je}-copy-${Date.now()}`,prompt:lt.prompt,agentMode:lt.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))}},he=()=>{O({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),D(null),T("edit")},ce=async je=>{const Me=await d(je);Me&&(D(je),O({name:Me.metadata.name,id:Me.metadata.id,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))},De=async je=>{await x(je),U()},Re=async()=>{const je=v??N.id;if(!je||!N.name||!N.prompt){L("Name and message are required.");return}M(!0),L("");const Me={metadata:{id:je,name:N.name,...N.agentMode?{agentMode:N.agentMode}:{}},prompt:N.prompt},lt=v?await m(v,Me):await p(Me,N.destination);if(M(!1),!lt.success){L(lt.error??"Failed to save command.");return}n?t():T("list")},ze=()=>{n?t():(T("list"),w(null),_(null))},Fe=je=>{O(Me=>({...Me,name:je})),(!v||N.isDefault)&&O(Me=>({...Me,id:v$(je)}))},Ee=()=>{w(null),_(null),T("list")},st=()=>{y&&(w(null),T("edit"),D(y),h(y).then(je=>{je&&O({name:`${je.metadata.name} (copy)`,id:`${y}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(y){const je=r.find(Me=>Me.id===y);return i.jsx(jt,{isOpen:e,onClose:Ee,title:`Default: ${(je==null?void 0:je.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:je==null?void 0:je.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:(je==null?void 0:je.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(rt,{variant:"secondary",onClick:Ee,children:"Close"}),i.jsx(rt,{variant:"primary",onClick:st,children:"Duplicate & Customize"})]})]})})}if(S==="edit")return i.jsx(jt,{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(eo,{message:b}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(B1,{name:N.name,id:N.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!N.isDefault,onNameChange:Fe,onIdChange:je=>O(Me=>({...Me,id:je}))}),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:N.agentMode,onChange:je=>O(Me=>({...Me,agentMode:je.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(je=>i.jsx("option",{value:je.id,children:je.name},je.id))]})]}),!v&&i.jsx(Nd,{value:N.destination,onChange:je=>O(Me=>({...Me,destination:je}))})]}),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:N.prompt,onChange:je=>O(Me=>({...Me,prompt:je.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(rt,{variant:"secondary",onClick:ze,children:"Cancel"}),i.jsx(rt,{variant:"primary",onClick:Re,disabled:j||!N.name||!N.prompt,children:j?"Saving...":"Save"})]})]})});const ot=je=>je.map(Me=>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:Me.name})})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(ci,{onClick:()=>ce(Me.id)}),i.jsx(Il,{onClick:()=>ie(Me.id)}),R(Me.id,"delete")?i.jsx(Qu,{onConfirm:()=>De(Me.id),onCancel:U}):i.jsx(Ju,{onClick:()=>W(Me.id)})]})]},Me.id));return i.jsxs(jt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[i.jsx(P1,{description:"Commands are pre-defined messages you can send with a single click.",onNew:he}),i.jsxs(ug,{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(je=>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:je.name})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(_$,{onClick:()=>J(je.id)}),i.jsx(Il,{onClick:()=>ie(je.id)})]})]},je.id))})]}),a.length>0&&i.jsx(M1,{children:ot(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:ot(l)})]})]})]})}function S$({title:e,defaultOpen:t=!1,children:n,className:r=""}){return i.jsxs("details",{className:`group ${r}`,open:t,children:[i.jsxs("summary",{className:"text-[11px] text-text-secondary uppercase tracking-wider font-medium cursor-pointer select-none hover:text-text-primary transition-colors list-none flex items-center gap-1",children:[i.jsx(hn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),e]}),i.jsx("div",{className:"mt-2 space-y-2",children:n})]})}const Bi=150,bs=54,Bu=80,Ar=30,Ga=70,US=100,$i=50,$u=50,FS=4,m2={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},p2=[{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)"}],w$=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"},{value:"user",label:"User (pause)"}];function rx(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 e.type==="user"?{name:"User",color:"#f59e0b"}:{name:"Shell",color:"#22c55e"}}function C$(e,t,n,r){const a=$u+$i+Bi+US+Bi+$i+$u,l=a/2,u=$u+$i+Bi/2,c=$u+$i+Bi+US+Bi/2,d=[],h=[],p=new Map,m=e.filter(G=>G.type==="agent"||G.type==="shell"||G.type==="user"),x=e.filter(G=>G.type==="sub_agent"),y=x.length>0,w=y?u:l,C=m.length>0?c:l,_=$i+Ar/2;d.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:_,w:Bu,h:Ar}),p.set("$start",{cx:w,cy:_,w:Bu,h:Ar});const S=G=>{d.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:G,w:Bu,h:Ar}),p.set("$done",{cx:w,cy:G,w:Bu,h:Ar})};if(e.length===0){const G=_+Ar/2+Ga*2+Ar/2;return S(G),{nodes:d,edges:h,width:a,height:G+Ar/2+$i,posMap:p}}const v=_+Ar/2+Ga,b=(G,V)=>{G.forEach((Z,X)=>{const $=v+X*(bs+Ga)+bs/2,{name:I,color:B}=rx(Z,r);d.push({id:Z.id,type:"step",label:I,color:B,cx:V,cy:$,w:Bi,h:bs}),p.set(Z.id,{cx:V,cy:$,w:Bi,h:bs})})};b(m,w),b(x,C);const j=m.length>0?v+(m.length-1)*(bs+Ga)+bs/2:_,N=y?v+(x.length-1)*(bs+Ga)+bs/2:_,T=Math.max(j,N)+bs/2+Ga+Ar/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 G of e)G.transitions.forEach((V,Z)=>{var z;if(!V.goto||!p.has(V.goto))return;const X=p.get(G.id),$=p.get(V.goto),I=V.when.type==="step_result"?`${V.when.result}`:V.when.type==="metadata_all_match"?`${V.when.key??"?"}=${V.when.value??"?"}`:V.when.type==="metadata_all_in"?`${V.when.key??"?"} in [${((z=V.when.values)==null?void 0:z.join(","))??"?"}]`:m2[V.when.type]??V.when.type,B=G.id===V.goto;let q;B?q="back":$.cy>X.cy+1?q="down":$.cy<X.cy-1?q="back":q="same",D.push({from:G.id,to:V.goto,label:I,edgeKey:`${G.id}:${Z}`,direction:q,backEdgeIndex:q==="back"?L++:0})});const O=new Map,M=new Map,W=new Map,U=new Map;for(const G of D)G.direction==="down"&&(O.set(G.from,(O.get(G.from)??0)+1),M.set(G.to,(M.get(G.to)??0)+1));const R=new Map,H=new Map;for(const G of D){if(G.direction!=="same")continue;const V=[G.from,G.to].sort().join("|");R.set(V,(R.get(V)??0)+1)}for(const G of D){if(G.direction==="back"||G.direction==="same"){let q=0;if(G.direction==="same"){const z=[G.from,G.to].sort().join("|");q=H.get(z)??0,H.set(z,q+1)}h.push({...G,fromPort:0,toPort:0,sameEdgeIndex:q});continue}const V=O.get(G.from)??1,Z=M.get(G.to)??1,X=W.get(G.from)??0,$=U.get(G.to)??0;W.set(G.from,X+1),U.set(G.to,$+1);const I=V===1?0:-.6+1.2*X/(V-1),B=Z===1?0:-.6+1.2*$/(Z-1);h.push({...G,fromPort:I,toPort:B,sameEdgeIndex:0})}return{nodes:d,edges:h,width:a,height:T+Ar/2+$i,posMap:p}}function k$({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=E.useRef(null),C=E.useRef(!1),[_,S]=E.useState(null),[v,b]=E.useState(null),[j,N]=E.useState(null),{nodes:T,edges:D,width:L,height:O,posMap:M}=E.useMemo(()=>C$(e,t,a,l),[e,t,a,l]),W=E.useCallback(re=>{var ie;const Q=w.current;if(!Q)return{x:0,y:0};const K=Q.createSVGPoint();K.x=re.clientX,K.y=re.clientY;const P=(ie=Q.getScreenCTM())==null?void 0:ie.inverse();if(!P)return{x:0,y:0};const J=K.matrixTransform(P);return{x:J.x,y:J.y}},[]),U=E.useCallback(re=>!re||!v||re==="$start"?!1:v.type==="reconnect-from"?re!=="$done":!0,[v]),R=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=W(re);b({type:"new",fromNodeId:Q,mouseX:K.x,mouseY:K.y})},[W,u]),H=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=W(re);b({type:"reconnect-to",fromNodeId:Q.from,edgeKey:Q.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),G=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=W(re);b({type:"reconnect-from",fromNodeId:Q.from,fixedTargetId:Q.to,edgeKey:Q.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),V=E.useCallback(re=>{if(!v)return;const Q=W(re);b(K=>K?{...K,mouseX:Q.x,mouseY:Q.y}:null)},[v,W]),Z=E.useCallback(()=>{v&&(C.current=!0,j&&U(j)&&(v.type==="new"?p(v.fromNodeId,j):v.type==="reconnect-to"?m(v.edgeKey,j):v.type==="reconnect-from"&&x(v.edgeKey,j)),b(null),N(null))},[v,j,U,p,m,x]),X=E.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);E.useEffect(()=>{if(u)return;const re=Q=>{Q.target instanceof HTMLInputElement||Q.target instanceof HTMLTextAreaElement||Q.target instanceof HTMLSelectElement||(Q.key==="Delete"||Q.key==="Backspace")&&r&&r!=="start"&&(Q.preventDefault(),y(r),d(null))};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[u,r,y,d]);const $=re=>{const Q=M.get(re.from),K=M.get(re.to);if(!Q||!K)return null;let P,J,ie,he="middle",ce,De;if(re.direction==="down"){const Re=Q.cx+re.fromPort*(Q.w/2-10),ze=Q.cy+Q.h/2,Fe=K.cx+re.toPort*(K.w/2-10),Ee=K.cy-K.h/2,st=Ee-ze,ot=Fe-Re;P=`M ${Re} ${ze} C ${Re} ${ze+st*.4}, ${Fe-ot*.2} ${Ee-st*.1}, ${Fe} ${Ee}`,J=Re+(Fe-Re)*.5,ie=ze+st*.6,ce={x:Re,y:ze},De={x:Fe,y:Ee}}else if(re.direction==="back"){const Re=re.from===re.to,ze=Q.cx>=L/2,Fe=re.backEdgeIndex*16,Ee=ze?L-20-Fe:20+Fe;if(Re){const st=Q.cx>=L/2,ot=30+re.backEdgeIndex*14,je=Q.cy-Q.h/2,Me=st?Q.cx+Q.w/2:Q.cx-Q.w/2,lt=st?Me+ot:Me-ot,we=Q.cx+(st?Q.w/4:-Q.w/4),Ie=je-20-re.backEdgeIndex*10;P=`M ${Me} ${Q.cy} C ${lt} ${Q.cy}, ${lt} ${Ie}, ${we} ${je}`,J=lt+10,ie=Ie+4,he="middle",ce={x:Me,y:Q.cy},De={x:we,y:je}}else{const st=ze?Q.cx+Q.w/2:Q.cx-Q.w/2,ot=K.cx+(ze?K.w/4:-K.w/4),je=Math.min(Q.cy,K.cy)-K.h/2-18-re.backEdgeIndex*14;P=`M ${st} ${Q.cy} L ${Ee} ${Q.cy} L ${Ee} ${je} L ${ot} ${je} L ${ot} ${K.cy-K.h/2}`,J=Ee,ie=(Q.cy+je)/2,he=ze?"start":"end",ce={x:st,y:Q.cy},De={x:ot,y:K.cy-K.h/2}}}else{const Re=K.cx>Q.cx,ze=re.sameEdgeIndex===0?-12:12,Fe=Re?Q.cx+Q.w/2:Q.cx-Q.w/2,Ee=Re?K.cx-K.w/2:K.cx+K.w/2,st=Q.cy+ze,ot=K.cy+ze,je=(Fe+Ee)/2;P=`M ${Fe} ${st} C ${je} ${st}, ${je} ${ot}, ${Ee} ${ot}`,J=je,ie=(st+ot)/2-6,ce={x:Fe,y:st},De={x:Ee,y:ot}}return{path:P,labelX:J,labelY:ie,labelAnchor:he,fromPt:ce,toPt:De}},I=(re,Q)=>{const K=$(re);if(!K)return null;const{path:P,labelX:J,labelY:ie,labelAnchor:he}=K,ce=r===re.edgeKey,De=re.label&&re.label!=="otherwise";return i.jsxs("g",{children:[i.jsx("path",{d:P,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Re=>{Re.stopPropagation(),u||d(ce?null:re.edgeKey)}}),i.jsx("path",{d:P,fill:"none",stroke:ce?"#58a6ff":"#484f58",strokeWidth:ce?2.2:1.2,markerEnd:ce?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),De&&i.jsx("text",{x:J+(he==="start"?5:he==="end"?-5:0),y:ie+3,textAnchor:he,className:"text-[8px]",fill:ce?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:re.label})]},Q)},B=()=>{if(!r||v)return null;const re=D.find(ie=>ie.edgeKey===r);if(!re)return null;const Q=$(re);if(!Q)return null;const{fromPt:K,toPt:P}=Q,J=6;return i.jsxs(i.Fragment,{children:[re.edgeKey!=="start"&&i.jsx("circle",{cx:K.x,cy:K.y,r:J,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>G(ie,re)}),i.jsx("circle",{cx:P.x,cy:P.y,r:J,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>H(ie,re)})]})},q=()=>{if(!v)return null;let re,Q,K,P;if(v.type==="reconnect-from"){const he=M.get(v.fixedTargetId);if(!he)return null;re=v.mouseX,Q=v.mouseY,K=he.cx,P=he.cy-he.h/2}else{const he=M.get(v.fromNodeId);if(!he)return null;re=he.cx,Q=he.cy+he.h/2,K=v.mouseX,P=v.mouseY}const J=P-Q,ie=Math.abs(J)>10?`M ${re} ${Q} C ${re} ${Q+J*.4}, ${K} ${P-J*.4}, ${K} ${P}`:`M ${re} ${Q} L ${K} ${P}`;return i.jsx("path",{d:ie,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},z=re=>{const Q=re.cy+re.h/2,K=(v==null?void 0:v.fromNodeId)===re.id;return i.jsx("circle",{cx:re.cx,cy:Q,r:FS,fill:K?"#58a6ff":"#1c2128",stroke:K?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5,className:"cursor-crosshair",onMouseDown:P=>R(P,re.id)})},ne=re=>{const Q=re.cy-re.h/2,K=v&&j===re.id&&U(re.id);return i.jsx("circle",{cx:re.cx,cy:Q,r:FS,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} ${O}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:V,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((re,Q)=>I(re,Q)),T.map(re=>{const Q=n===re.id,K=re.cx-re.w/2,P=re.cy-re.h/2,J=_===re.id,ie=v&&j===re.id&&U(re.id);if(re.type==="terminal"){const ce=re.id==="$start",De=ce?"#58a6ff":"#3fb950",Re=ce,ze=!ce;return i.jsxs("g",{onClick:Fe=>{Fe.stopPropagation(),ce&&!u&&d("start")},className:ce&&!u?"cursor-pointer":void 0,children:[ie&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:re.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ce&&r==="start"&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:re.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:P,width:re.w,height:re.h,rx:re.h/2,fill:De,fillOpacity:.08,stroke:De,strokeOpacity:.4,strokeWidth:1.5}),i.jsx("text",{x:re.cx,y:re.cy+4,textAnchor:"middle",fill:De,className:"text-[10px] font-medium",pointerEvents:"none",children:re.label}),Re&&z(re),ze&&ne(re)]},re.id)}const he=re.color??"#6b7280";return i.jsxs("g",{onClick:ce=>{ce.stopPropagation(),u||c(Q?null:re.id)},onMouseEnter:()=>S(re.id),onMouseLeave:()=>S(null),className:u?void 0:"cursor-pointer",children:[ie&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),Q&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:P,width:re.w,height:re.h,rx:10,fill:he,fillOpacity:.08,stroke:he,strokeOpacity:.6,strokeWidth:Q?2:1.5}),i.jsx("text",{x:re.cx,y:re.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:re.label}),!u&&z(re),!u&&ne(re),J&&!v&&!u&&i.jsxs("g",{onClick:ce=>{ce.stopPropagation(),h(re.id)},className:"cursor-pointer",children:[i.jsx("circle",{cx:K+re.w-2,cy:P+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),i.jsx("line",{x1:K+re.w-5,y1:P-1,x2:K+re.w+1,y2:P+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),i.jsx("line",{x1:K+re.w+1,y1:P-1,x2:K+re.w-5,y2:P+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},re.id)}),v&&T.map(re=>U(re.id)?i.jsx("rect",{x:re.cx-re.w/2-8,y:re.cy-re.h/2-8,width:re.w+16,height:re.h+16,fill:"transparent",rx:12,onMouseEnter:()=>N(re.id),onMouseLeave:()=>N(null),onMouseUp:Q=>{Q.stopPropagation(),Z()}},`drop-${re.id}`):null),q(),B()]})}const zu="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",_l="block text-[11px] text-text-secondary mb-0.5";function j$({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:_l,children:"Name"}),i.jsx("input",{value:e,onChange:p=>u(p.target.value),placeholder:"Workflow name",className:`${zu} ${l?"opacity-50":""}`,readOnly:l})]}),i.jsxs("div",{className:"min-w-[100px]",children:[i.jsx("label",{className:_l,children:"ID"}),i.jsx("input",{value:t,readOnly:!0,className:`${zu} font-mono opacity-50`})]}),i.jsxs("div",{className:"flex-1 min-w-[140px]",children:[i.jsx("label",{className:_l,children:"Description"}),i.jsx("input",{value:n,onChange:p=>!l&&c(p.target.value),readOnly:l,placeholder:"What does this workflow do?",className:`${zu} ${l?"opacity-50":""}`})]}),i.jsxs("div",{className:"w-20",children:[i.jsx("label",{className:_l,children:"Max Iter."}),i.jsx("input",{type:"number",value:r,onChange:p=>!l&&d(Number(p.target.value)),readOnly:l,className:`${zu} font-mono ${l?"opacity-50":""}`})]}),i.jsxs("div",{children:[i.jsx("label",{className:_l,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 E$({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 up({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(E$,{name:r.name,id:r.id,color:r.color??"#3b82f6",description:r.description,actions:n(r)},r.id))})]})}const Wa="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",dp="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 hp({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 N$({step:e,isEntry:t,agentTypes:n,transitionCount:r,templateVariables:a,onUpdate:l,onRemove:u,onSetEntry:c}){const{color:d,name:h}=rx(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(m==="user"?{...e,type:m,phase:x,name:"User"}:{...e,type:m,phase:x,name:"Shell"})},className:dp,children:w$.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:dp,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:dp,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:`${Wa} resize-y text-xs`,placeholder:"Injected on first entry..."}),i.jsx(hp,{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:`${Wa} resize-y text-xs`,placeholder:"Injected on re-entry..."}),i.jsx(hp,{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:`${Wa} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),i.jsx(hp,{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:`${Wa} 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:`${Wa} 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:Wa})]}),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 qa="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="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",zi="block text-[11px] text-text-secondary mb-0.5";function T$({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(hn,{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(hn,{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(C1,{}),i.jsx("span",{className:"font-medium text-text-primary",children:t})]}),i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Condition"}),i.jsx("select",{value:n.type,onChange:_=>{d(_.target.value==="step_result"?{type:"step_result",result:"success"}:{type:_.target.value})},className:VS,children:p2.map(_=>i.jsx("option",{value:_.value,children:_.label},_.value))})]}),n.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Result"}),w?i.jsx("select",{value:n.result??y.results[0],onChange:_=>{d({type:"step_result",result:_.target.value})},className:VS,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:qa})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:zi,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:qa})]}),i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Field"}),i.jsx("input",{type:"text",value:n.field??"",onChange:_=>d({...n,field:_.target.value}),placeholder:"e.g. status",className:qa})]}),n.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Value"}),i.jsx("input",{type:"text",value:n.value??"",onChange:_=>d({...n,value:_.target.value}),placeholder:"e.g. passed, resolved",className:qa})]}):i.jsxs("div",{children:[i.jsx("label",{className:zi,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:qa})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Sub-group"}),i.jsx("input",{type:"text",value:r??"",onChange:_=>h(_.target.value||void 0),placeholder:"e.g. build, verify",className:qa})]}),i.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function A$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function L$(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const Sl="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",GS="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",Ka="block text-[11px] text-text-secondary mb-0.5",WS=[];function g2({isOpen:e,onClose:t,initialEditId:n}){var Ts,As;const r=vt(Se=>Se.defaults),a=vt(Se=>Se.userItems),l=vt(Se=>Se.projectItems),u=vt(Se=>Se.loading),c=vt(Se=>Se.templateVariables),d=vt(Se=>Se.fetchWorkflows),h=vt(Se=>Se.fetchWorkflow),p=vt(Se=>Se.fetchDefaultContent),m=vt(Se=>Se.fetchTemplateVariables),x=vt(Se=>Se.createWorkflow),y=vt(Se=>Se.updateWorkflow),w=vt(Se=>Se.deleteWorkflow),{requestDelete:C,clearConfirm:_,isConfirming:S}=Yl(),[v,b]=E.useState("list"),[j,N]=E.useState(null),[T,D]=E.useState(!1),[L,O]=E.useState(null),[M,W]=E.useState(null),[U,R]=E.useState(""),[H,G]=E.useState(""),[V,Z]=E.useState(""),[X,$]=E.useState("1.0.0"),[I,B]=E.useState("#3b82f6"),[q,z]=E.useState(""),[ne,re]=E.useState(50),[Q,K]=E.useState(WS),[P,J]=E.useState({type:"always"}),[ie,he]=E.useState([]),[ce,De]=E.useState("user"),[Re,ze]=E.useState(""),[Fe,Ee]=E.useState(!1),st=xt(Se=>Se.defaults),ot=xt(Se=>Se.userItems),je=xt(Se=>Se.projectItems),Me=E.useMemo(()=>[...st,...ot,...je],[st,ot,je]),lt=xt(Se=>Se.fetchAgents),[we]=E.useState(null);E.useEffect(()=>{e&&(d(),m(),lt(),O(null),W(null),n?r.some(Ce=>Ce.id===n)?p(n).then(Ce=>{Ce&&Ie({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):h(n).then(Ce=>{Ce&&Ie(Ce,{editingId:n,isReadOnly:!1})}):(b("list"),N(null),D(!1)))},[e,d,h,p,m,n]);const Ie=(Se,Ce)=>{R(Se.metadata.name),G(Se.metadata.id),Z(Se.metadata.description),$(Se.metadata.version),B(Se.metadata.color??"#3b82f6"),z(Se.entryStep),re(Se.settings.maxIterations),K(Se.steps),J(Se.startCondition??{type:"always"}),he(Se.metadata.parameters??[]),ze(""),(Ce==null?void 0:Ce.editingId)!==void 0&&N(Ce.editingId),(Ce==null?void 0:Ce.isReadOnly)!==void 0&&D(Ce.isReadOnly),(Ce==null?void 0:Ce.selectedNodeKey)!==void 0&&O(null),(Ce==null?void 0:Ce.selectedEdgeKey)!==void 0&&W(null),b("edit")},qe=async Se=>{const Ce=await h(Se);Ce&&Ie(Ce,{editingId:Se,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},te=async()=>{var Qe;const Se=j??H;if(!Se||!U)return ze("Name is required."),!1;if(Q.length===0)return ze("Add at least one step."),!1;const Ce=ie.find(at=>!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(at.id));if(Ce)return ze(`Invalid parameter ID "${Ce.id}". Use letters, digits, and underscores only.`),!1;let Oe=q;if(!Oe||!Q.some(at=>at.id===Oe)){if(Oe=((Qe=Q.find(at=>at.id))==null?void 0:Qe.id)??"",!Oe)return ze("All steps need an ID."),!1;z(Oe)}Ee(!0),ze("");const We={metadata:{id:Se,name:U,description:V,version:X||"1.0.0",color:I,...ie.length>0?{parameters:ie}:{}},entryStep:Oe,settings:{maxIterations:ne},steps:Q,startCondition:P},Ve=j?await y(j,We):await x(We,ce);return Ee(!1),Ve.success?(j||N(Se),!0):(ze(Ve.error??"Failed to save."),!1)},ae=async()=>{await te()},se=async()=>{await te()&&(n?t():b("list"))},me=()=>{n?t():b("list")},Ue=Se=>{R(Se),j||G(A$(Se))},He=async Se=>r.some(Oe=>Oe.id===Se)?await p(Se):await h(Se),Ye=async Se=>{const Ce=await He(Se);Ce&&Ie({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${Se}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},ct=()=>{N(null),R(""),G(""),Z(""),$("1.0.0"),B("#3b82f6"),z(""),re(50),K(structuredClone(WS)),J({type:"always"}),he([]),De("user"),ze(""),O(null),W(null),D(!1),b("edit")},Je=async Se=>{await w(Se),_()},Ze=E.useCallback(Se=>{O(Se),W(null)},[]),tt=E.useCallback(Se=>{W(Se),O(null)},[]),Nt=L!==null?Number(L):-1,dt=Nt>=0?Q[Nt]??null:null,rn=E.useCallback(Se=>{K(Ce=>Ce.map((Oe,We)=>We===Nt?Se:Oe))},[Nt]),Un=P.type==="step_result"?`${P.result}`:P.type==="metadata_all_match"?`${P.key??"?"}=${P.value??"?"}`:P.type==="metadata_all_in"?`${P.key??"?"} in [${((Ts=P.values)==null?void 0:Ts.join(","))??"?"}]`:m2[P.type]??P.type,ye=()=>{const Se=Q.length,Ce=L$(Q),Oe=Me.find(We=>!We.subagent);K([...Q,{id:Ce,name:(Oe==null?void 0:Oe.name)??"Agent",type:"agent",phase:"build",agentId:(Oe==null?void 0:Oe.id)??"builder",transitions:[]}]),q||z(Ce),Ze(String(Se))},Ge=E.useCallback((Se,Ce)=>{Se==="$start"?(z(Ce),tt("start")):K(Oe=>{const We=Oe.find(Qe=>Qe.id===Se),Ve=We?We.transitions.length:0;return tt(`${Se}:${Ve}`),Oe.map(Qe=>Qe.id===Se?{...Qe,transitions:[...Qe.transitions,{when:{type:"always"},goto:Ce}]}:Qe)})},[tt]),oe=Se=>{if(Se==="start")return null;const Ce=Se.lastIndexOf(":"),Oe=Se.slice(0,Ce),We=parseInt(Se.slice(Ce+1));return{stepId:Oe,transIdx:We}},fe=E.useCallback((Se,Ce)=>{const Oe=oe(Se);Oe&&K(We=>We.map(Ve=>Ve.id===Oe.stepId?{...Ve,transitions:Ve.transitions.map((Qe,at)=>at===Oe.transIdx?Ce(Qe):Qe)}:Ve))},[]),Pe=E.useCallback((Se,Ce)=>{if(Se==="start"){z(Ce);return}fe(Se,Oe=>({...Oe,goto:Ce}))},[fe]),St=E.useCallback((Se,Ce)=>{const Oe=oe(Se);Oe&&(K(We=>{const Ve=We.find(at=>at.id===Oe.stepId);if(!Ve)return We;const Qe=Ve.transitions[Oe.transIdx];return Qe?We.map(at=>at.id===Oe.stepId?{...at,transitions:at.transitions.filter((Zt,mn)=>mn!==Oe.transIdx)}:at.id===Ce?{...at,transitions:[...at.transitions,Qe]}:at):We}),W(null))},[]),bn=E.useCallback(Se=>{if(Se==="start"){z(""),W(null);return}const Ce=oe(Se);Ce&&(K(Oe=>Oe.map(We=>We.id===Ce.stepId?{...We,transitions:We.transitions.filter((Ve,Qe)=>Qe!==Ce.transIdx)}:We)),W(null))},[]),fn=E.useCallback((Se,Ce)=>{if(Se==="start"){J(Ce);return}fe(Se,Oe=>({...Oe,when:Ce}))},[fe]),Pr=E.useCallback((Se,Ce)=>{Se!=="start"&&fe(Se,Oe=>({...Oe,subGroup:Ce||void 0}))},[fe]),Ns=Se=>rx(Se,Me).name,xi=()=>{if(!M)return null;if(M==="start"){const Zt=Q.find(mn=>mn.id===q);return{type:"start",fromLabel:"Start",toLabel:Zt?Ns(Zt):"(none)",condition:P}}const Se=M.lastIndexOf(":"),Ce=M.slice(0,Se),Oe=parseInt(M.slice(Se+1)),We=Q.find(Zt=>Zt.id===Ce);if(!We)return null;const Ve=We.transitions[Oe];if(!Ve)return null;const Qe=Q.find(Zt=>Zt.id===Ve.goto),at=Ve.goto==="$done"?"Done":Qe?Ns(Qe):Ve.goto;return{type:"step",fromLabel:Ns(We),toLabel:at,condition:Ve.when,subGroup:Ve.subGroup}};if(v==="edit"){const Se=xi();return i.jsxs(jt,{isOpen:e,onClose:me,title:T?U:j?"Edit Workflow":"New Workflow",size:"full",children:[Re&&i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:Re}),i.jsx(j$,{formName:U,formId:H,formDescription:V,formMaxIterations:ne,formColor:I,isReadOnly:T,onNameChange:Ue,onDescriptionChange:Z,onMaxIterationsChange:re,onColorChange:B}),!T&&i.jsx("div",{className:"mb-3 pb-3 border-b border-border",children:i.jsxs(S$,{title:`Parameters (${ie.length})`,children:[ie.map((Ce,Oe)=>i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{value:Ce.id,onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,id:We.target.value},he(Ve)},placeholder:"ID",className:"w-28 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"}),i.jsx("input",{value:Ce.label,onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,label:We.target.value},he(Ve)},placeholder:"Label",className:"w-36 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary"}),i.jsx("input",{value:Ce.description??"",onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,description:We.target.value||void 0},he(Ve)},placeholder:"Description",className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary"}),i.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-muted whitespace-nowrap",children:[i.jsx("input",{type:"checkbox",checked:Ce.required??!1,onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,required:We.target.checked||void 0},he(Ve)},className:"rounded border-border"}),"Req."]}),i.jsxs("div",{className:"flex gap-0.5",children:[i.jsx("button",{onClick:()=>{Oe!==0&&he(ie.map((We,Ve)=>Ve===Oe?{...ie[Oe-1],position:Ve}:Ve===Oe-1?{...ie[Oe],position:Ve}:{...We,position:Ve}))},disabled:Oe===0,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move up","aria-label":`Move ${Ce.label||Ce.id} up`,children:"▲"}),i.jsx("button",{onClick:()=>{Oe!==ie.length-1&&he(ie.map((We,Ve)=>Ve===Oe?{...ie[Oe+1],position:Ve}:Ve===Oe+1?{...ie[Oe],position:Ve}:{...We,position:Ve}))},disabled:Oe===ie.length-1,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move down","aria-label":`Move ${Ce.label||Ce.id} down`,children:"▼"})]}),i.jsx("button",{onClick:()=>he(ie.filter((We,Ve)=>Ve!==Oe)),className:"p-1 text-text-muted hover:text-accent-error transition-colors",title:"Remove parameter",children:"✕"})]},Ce.id)),i.jsx("button",{onClick:()=>{const Ce=`param_${ie.length+1}`;he([...ie,{id:Ce,label:"",description:"",required:!1}])},className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:"+ Add parameter"})]})}),!j&&!T&&i.jsx(Nd,{value:ce,onChange:De}),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"}),!T&&i.jsx("button",{onClick:ye,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(k$,{steps:Q,entryStep:q,selectedNodeId:(dt==null?void 0:dt.id)??null,selectedEdgeKey:M,startConditionLabel:Un,agentTypes:Me,isReadOnly:T,onSelectNode:Ce=>{if(Ce===null){Ze(null);return}const Oe=Q.findIndex(We=>We.id===Ce);Ze(Oe>=0?String(Oe):null)},onSelectEdge:tt,onRemoveStep:Ce=>{var We;const Oe=Q.findIndex(Ve=>Ve.id===Ce);if(K(Ve=>Ve.filter(Qe=>Qe.id!==Ce)),Nt===Oe&&Ze(null),q===Ce){const Ve=Q.filter(Qe=>Qe.id!==Ce);z(((We=Ve[0])==null?void 0:We.id)??"")}},onCreateTransition:Ge,onReconnectTo:Pe,onReconnectFrom:St,onDeleteTransition:bn}),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:ye,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:T&&(Se||dt)?i.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):Se?Se.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"})}),q&&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(C1,{}),i.jsx("span",{className:"text-text-primary font-medium",children:Se.toLabel})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Activation Condition"}),i.jsx("select",{value:P.type,onChange:Ce=>J(Ce.target.value==="step_result"?{type:"step_result",result:"success"}:Ce.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:Ce.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:Ce.target.value}),className:GS,children:p2.map(Ce=>i.jsx("option",{value:Ce.value,children:Ce.label},Ce.value))})]}),P.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Result"}),q&&(()=>{const Ce=Q.find(Qe=>Qe.id===q),Oe=Ce&&(Ce.type==="sub_agent"||Ce.type==="agent")?Me.find(Qe=>Qe.id===(Ce.type==="sub_agent"?Ce.subAgentType:Ce.agentId)):void 0,We=(Oe==null?void 0:Oe.results)&&Oe.results.length>0,Ve=(Oe==null?void 0:Oe.results)??[];return We?i.jsx("select",{value:P.result??Ve[0],onChange:Qe=>J({type:"step_result",result:Qe.target.value}),className:GS,children:Ve.map(Qe=>i.jsx("option",{value:Qe,children:Qe},Qe))}):i.jsx("input",{type:"text",value:P.result??"success",onChange:Qe=>J({type:"step_result",result:Qe.target.value}),placeholder:"e.g. success, passed, failed",className:Sl})})()]}),(P.type==="metadata_all_match"||P.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Metadata Key"}),i.jsx("input",{type:"text",value:P.key??"",onChange:Ce=>J({...P,key:Ce.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:Sl})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Field"}),i.jsx("input",{type:"text",value:P.field??"",onChange:Ce=>J({...P,field:Ce.target.value}),placeholder:"e.g. status",className:Sl})]}),P.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Value"}),i.jsx("input",{type:"text",value:P.value??"",onChange:Ce=>J({...P,value:Ce.target.value}),placeholder:"e.g. passed, resolved",className:Sl})]}):i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((As=P.values)==null?void 0:As.join(", "))??"",onChange:Ce=>J({...P,values:Ce.target.value.split(",").map(Oe=>Oe.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:Sl})]})]}),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 Ce=oe(M),Oe=Ce==null?void 0:Ce.stepId,We=(Ce==null?void 0:Ce.transIdx)??0,Ve=Oe?Q.find(at=>at.id===Oe):void 0,Qe=(Ve==null?void 0:Ve.transitions.length)??0;return i.jsx(T$,{fromLabel:Se.fromLabel,toLabel:Se.toLabel,condition:Se.condition,subGroup:"subGroup"in Se?Se.subGroup:void 0,fromStep:Se.type==="step"?Q.find(at=>at.id===Se.fromLabel):void 0,agentTypes:Me,transitionIndex:We,totalTransitions:Qe,onUpdateCondition:at=>fn(M,at),onUpdateSubGroup:at=>Pr(M,at),onDelete:()=>bn(M),onMoveUp:()=>{K(at=>{const Zt=at.find(Zn=>Zn.id===Oe);if(!Zt||We===0)return at;const mn=[...Zt.transitions];return[mn[We-1],mn[We]]=[mn[We],mn[We-1]],at.map(Zn=>Zn.id===Oe?{...Zn,transitions:mn}:Zn)}),W(`${Oe}:${We-1}`)},onMoveDown:()=>{K(at=>{const Zt=at.find(Zn=>Zn.id===Oe);if(!Zt||We===Zt.transitions.length-1)return at;const mn=[...Zt.transitions];return[mn[We],mn[We+1]]=[mn[We+1],mn[We]],at.map(Zn=>Zn.id===Oe?{...Zn,transitions:mn}:Zn)}),W(`${Oe}:${We+1}`)}})})():dt?i.jsx(N$,{step:dt,isEntry:dt.id===q,agentTypes:Me,transitionCount:dt.transitions.length,templateVariables:c,onUpdate:rn,onRemove:()=>{var Ce;if(dt&&(K(Q.filter((Oe,We)=>We!==Nt)),Ze(null),q===dt.id)){const Oe=Q.filter((We,Ve)=>Ve!==Nt);z(((Ce=Oe[0])==null?void 0:Ce.id)??"")}},onSetEntry:()=>z(dt.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(rt,{variant:"secondary",onClick:me,children:"Close"}),T?i.jsx(rt,{variant:"primary",onClick:()=>{R(U+" (copy)"),G(`${j}-copy-${Date.now()}`),N(null),D(!1)},children:"Duplicate & Customize"}):i.jsxs(i.Fragment,{children:[i.jsx(rt,{variant:"primary",onClick:ae,children:"Save"}),i.jsx(rt,{variant:"primary",onClick:se,children:"Save & Close"})]})]})]})}return i.jsx(jt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:i.jsx(I1,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:ct,loading:u,hasItems:r.length>0||a.length>0||l.length>0,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(up,{title:"Built-in",items:r,renderActions:Se=>i.jsx(i.Fragment,{children:i.jsx(ci,{onClick:()=>Ye(Se.id),children:i.jsx(ig,{})})})}),i.jsx(up,{title:"Custom",items:a,renderActions:Se=>i.jsxs(i.Fragment,{children:[i.jsx(ci,{onClick:()=>qe(Se.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Il,{onClick:()=>Ye(Se.id)}),S(Se.id,"delete")?i.jsx(Qu,{onConfirm:()=>Je(Se.id),onCancel:_}):i.jsx(Ju,{onClick:()=>C(Se.id)})]})}),l.length>0&&i.jsx(up,{title:"Project",items:l,renderActions:Se=>i.jsxs(i.Fragment,{children:[i.jsx(ci,{onClick:()=>qe(Se.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Il,{onClick:()=>Ye(Se.id)}),S(Se.id,"delete")?i.jsx(Qu,{onConfirm:()=>Je(Se.id),onCancel:_}):i.jsx(Ju,{onClick:()=>C(Se.id)})]})})]})})})}function D$(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function R$({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:r,onSelectWorkflow:a,onCloseCompleteAction:l,textareaContent:u,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:h}){const[,p]=Tn(),m=Yt(z=>z.fetchCommands),x=vt(z=>z.fetchWorkflows),y=xt(z=>z.fetchAgents),w=Yt(z=>z.defaults),C=Yt(z=>z.userItems),_=Yt(z=>z.projectItems),S=vt(z=>z.defaults),v=vt(z=>z.userItems),b=vt(z=>z.projectItems),j=xt(z=>z.defaults),N=xt(z=>z.userItems),T=xt(z=>z.projectItems),D=Le(z=>{var ne;return(ne=z.currentSession)==null?void 0:ne.mode}),L=Le(z=>{var ne;return((ne=z.currentSession)==null?void 0:ne.dangerLevel)??"normal"}),O=Le(z=>z.switchMode),M=Le(z=>z.switchDangerLevel),W=Le(z=>{var ne;return(ne=z.currentSession)==null?void 0:ne.projectId}),U=E.useRef(void 0),[R,H]=E.useState(""),[G,V]=E.useState(0),Z=E.useRef(null),X=E.useRef(!1);E.useEffect(()=>{e&&(X.current=!0)},[e]),E.useEffect(()=>{if(e){m(),x(),y(),H(""),V(0);const z=setTimeout(()=>{var ne;return(ne=Z.current)==null?void 0:ne.focus()},50);return()=>clearTimeout(z)}},[e,m,x,y]),E.useEffect(()=>{var z;!e&&X.current&&(n==null||n(),(z=U.current)==null||z.call(U),U.current=void 0)},[e,n]);const I=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const z=W??D$(window.location.pathname);z&&p(`/p/${z}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{U.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)}},...qr(qr(j,N),T).filter(z=>!z.subagent&&z.id!==D).map(z=>({id:z.id,name:z.name,prefix:"Agent > Switch to",action:()=>O(z.id)})),...qr(qr(w,C),_).map(z=>({id:z.id,name:z.name,prefix:"Command > Launch",action:()=>r(z.id,u)})),...qr(qr(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:()=>M(z)}))].filter(z=>li(`${z.prefix} ${z.name}`,R)),B=I.length-1,q=z=>{Pk(z,B,V,()=>{var ne;(ne=I[G])==null||ne.action(),t()},t)};return e?mi.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=>{H(z.target.value),V(0)},onKeyDown:q,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx(cg,{onClick:t,className:"shrink-0","aria-label":"Close"})]}),i.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:I.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"}):I.map((z,ne)=>i.jsxs("button",{type:"button",onClick:()=>{z.action(),t()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${ne===G?"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 x2="openfox-message-search-filters",O$=[{key:"user",label:"User prompts"},{key:"thinking",label:"Thinking"},{key:"response",label:"Responses"}];function I$(){try{const e=localStorage.getItem(x2);if(e){const t=JSON.parse(e);return new Set(t)}}catch{}return new Set(["user","thinking","response"])}function M$(e){localStorage.setItem(x2,JSON.stringify([...e]))}function P$(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 B$(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 $$(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 z$(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 H$(e){var n,r;if(e.type!=="message")return i.jsx(L_,{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(xT,{className:"w-3.5 h-3.5"}):i.jsx(L_,{className:"w-3.5 h-3.5"}):i.jsx(gT,{className:"w-3.5 h-3.5"})}function qS(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 U$({isOpen:e,onClose:t,displayItems:n,onNavigate:r}){const[a,l]=E.useState(""),[u,c]=E.useState(0),[d,h]=E.useState(I$),p=E.useRef(null),m=E.useRef(null),x=E.useRef(null),y=N=>{h(T=>{const D=new Set(T);return D.has(N)?D.delete(N):D.add(N),M$(D),D})},w=E.useMemo(()=>n.filter(N=>{var T,D;return!(N.type==="context-divider"||N.type==="message"&&(N.message.messageKind==="auto-prompt"||N.message.role==="assistant"&&!((T=N.message.content)!=null&&T.trim())&&!((D=N.message.thinkingContent)!=null&&D.trim())))}),[n]),C=E.useMemo(()=>w.filter(N=>{const T=P$(N);return!(T&&!d.has(T))}),[w,d]),_=E.useMemo(()=>a?w.filter(N=>{const T=qS(N);return li(T,a)}):C,[C,a]),S=_.length-1;E.useEffect(()=>{if(e){l(""),c(0);const N=setTimeout(()=>{var T;return(T=p.current)==null?void 0:T.focus()},50);return()=>clearTimeout(N)}},[e]),E.useEffect(()=>{e&&m.current&&(m.current.scrollTop=m.current.scrollHeight)},[e]),E.useEffect(()=>{x.current&&x.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[u]);const v=N=>{Pk(N,S,c,()=>{const T=_[u];if(T){const D=n.indexOf(T);D>=0&&r(D),t()}},t)},b=N=>{const T=n.indexOf(N);T>=0&&r(T),t()},j=N=>n.indexOf(N);return e?mi.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(Xi,{}),i.jsx("input",{ref:p,type:"text",value:a,onChange:N=>{l(N.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:O$.map(N=>{const T=d.has(N.key);return i.jsx("button",{type:"button",onClick:()=>y(N.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:N.label},N.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((N,T)=>{const D=j(N),L=H$(N),O=qS(N),M=z$(N),W=$$(N),U=N.type==="message"&&N.message.role==="user";return i.jsx("button",{ref:T===u?x:null,type:"button",onClick:()=>b(N),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${T===u?"bg-accent-primary/20 text-text-primary":U?"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 ${M}`,children:O})]}),W&&i.jsx("span",{className:"text-text-muted text-xs shrink-0",children:B$(W)})]})},`${D}-${N.type}`)})})]})]}),document.body):null}function y2(e){const t=new Set,n=[],r=/\{\{(\w+)\}\}/g;let a;for(;(a=r.exec(e))!==null;){const l=a[1];t.has(l)||(t.add(l),n.push(l))}return n}function F$(e,t,n){const r=e.trim();if(!r.startsWith("/"))return null;const a=r.slice(1).split(/\s+/),l=a[0];if(!l)return null;const u=a.slice(1),c={},d=t.find(h=>h.id===l);return d?(d.parameters&&d.parameters.length>0?[...d.parameters].sort((p,m)=>(p.position??0)-(m.position??0)).forEach((p,m)=>{u[m]!==void 0&&(c[p.id]=u[m])}):u.forEach((h,p)=>{c[String(p)]=h}),{workflowId:l,params:c}):n&&n.find(p=>p.id===l)?(u.forEach((p,m)=>{c[String(m)]=p}),{commandId:l,params:c}):null}function V$({attachment:e,onRemove:t}){const n=u2(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(rc,{onClick:()=>t(e.id),className:"absolute -top-2 -right-2",size:"sm",variant:"overlay","aria-label":`Remove ${e.filename}`}),c2(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:Za(e.size)})]})}function G$({history:e,selectedIndex:t,onSelect:n,onEscape:r,onNavigate:a}){const l=E.useRef(null),u=E.useRef(null);E.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 Yt=In((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchCommands:async()=>{await kk("/api/commands",e,!0)},fetchCommand:async n=>{try{const r=await ve(`/api/commands/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/commands/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createCommand:async(n,r)=>{const a=await fi("POST","/api/commands",{...n,destination:r});return a.success&&await t().fetchCommands(),a},updateCommand:async(n,r)=>{const a=await fi("PUT",`/api/commands/${n}`,r);return a.success&&await t().fetchCommands(),a},deleteCommand:async n=>{try{const r=await ve(`/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)=>Cd(`/api/commands/${n}/duplicate`,()=>t().fetchCommands(),r)}));function v$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function _$({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(ig,{})})}function fj({isOpen:e,onClose:t,initialEditId:n}){const r=Yt(je=>je.defaults),a=Yt(je=>je.userItems),l=Yt(je=>je.projectItems),u=Yt(je=>je.loading),c=Yt(je=>je.fetchCommands),d=Yt(je=>je.fetchCommand),h=Yt(je=>je.fetchDefaultContent),p=Yt(je=>je.createCommand),m=Yt(je=>je.updateCommand),x=Yt(je=>je.deleteCommand),[y,w]=E.useState(null),[C,_]=E.useState(null),{view:S,editingId:v,formError:b,saving:j,formData:N,setView:T,setEditingId:D,setFormError:L,setFormData:O,setSaving:M}=$1(),{requestDelete:W,clearConfirm:U,isConfirming:R}=Yl(),H=E.useRef(!1),G=xt(je=>je.defaults),V=xt(je=>je.userItems),Z=xt(je=>je.fetchAgents),$=[...G,...V].filter(je=>!je.subagent),I=E.useRef(c),B=E.useRef(Z),q=E.useRef(d),z=E.useRef(h),ne=E.useRef(n),re=E.useRef(T),Q=E.useRef(D),K=E.useRef(L),P=E.useRef(U);E.useEffect(()=>{I.current=c,B.current=Z,q.current=d,z.current=h,ne.current=n,re.current=T,Q.current=D,K.current=L,P.current=U}),E.useEffect(()=>{if(e)if(I.current(),B.current(),H.current||(P.current(),H.current=!0),ne.current){const je=r.some(Me=>Me.id===ne.current);re.current("edit"),Q.current(ne.current),K.current(""),je?z.current(ne.current).then(Me=>{Me&&O({name:Me.metadata.name+" (copy)",id:`${ne.current}-copy-${Date.now()}`,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!0,destination:"user"})}):q.current(ne.current).then(Me=>{Me&&O({name:Me.metadata.name,id:Me.metadata.id,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else re.current("list"),Q.current(null);else H.current=!1},[e]);const J=async je=>{w(je);const Me=await h(je);_((Me==null?void 0:Me.prompt)??null)},ie=async je=>{if(r.some(lt=>lt.id===je)){const lt=await h(je);lt&&(D(null),O({name:`${lt.metadata.name} (copy)`,id:`${je}-copy-${Date.now()}`,prompt:lt.prompt,agentMode:lt.metadata.agentMode??"",isDefault:!0,destination:"user"}),L(""),T("edit"))}else{const lt=await d(je);lt&&(D(null),O({name:`${lt.metadata.name} (copy)`,id:`${je}-copy-${Date.now()}`,prompt:lt.prompt,agentMode:lt.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))}},he=()=>{O({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),D(null),T("edit")},ce=async je=>{const Me=await d(je);Me&&(D(je),O({name:Me.metadata.name,id:Me.metadata.id,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))},De=async je=>{await x(je),U()},Re=async()=>{const je=v??N.id;if(!je||!N.name||!N.prompt){L("Name and message are required.");return}M(!0),L("");const Me={metadata:{id:je,name:N.name,...N.agentMode?{agentMode:N.agentMode}:{}},prompt:N.prompt},lt=v?await m(v,Me):await p(Me,N.destination);if(M(!1),!lt.success){L(lt.error??"Failed to save command.");return}n?t():T("list")},ze=()=>{n?t():(T("list"),w(null),_(null))},Fe=je=>{O(Me=>({...Me,name:je})),(!v||N.isDefault)&&O(Me=>({...Me,id:v$(je)}))},Ee=()=>{w(null),_(null),T("list")},st=()=>{y&&(w(null),T("edit"),D(y),h(y).then(je=>{je&&O({name:`${je.metadata.name} (copy)`,id:`${y}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(y){const je=r.find(Me=>Me.id===y);return i.jsx(jt,{isOpen:e,onClose:Ee,title:`Default: ${(je==null?void 0:je.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:je==null?void 0:je.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:(je==null?void 0:je.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(rt,{variant:"secondary",onClick:Ee,children:"Close"}),i.jsx(rt,{variant:"primary",onClick:st,children:"Duplicate & Customize"})]})]})})}if(S==="edit")return i.jsx(jt,{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(eo,{message:b}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(B1,{name:N.name,id:N.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!N.isDefault,onNameChange:Fe,onIdChange:je=>O(Me=>({...Me,id:je}))}),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:N.agentMode,onChange:je=>O(Me=>({...Me,agentMode:je.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(je=>i.jsx("option",{value:je.id,children:je.name},je.id))]})]}),!v&&i.jsx(Nd,{value:N.destination,onChange:je=>O(Me=>({...Me,destination:je}))})]}),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:N.prompt,onChange:je=>O(Me=>({...Me,prompt:je.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(rt,{variant:"secondary",onClick:ze,children:"Cancel"}),i.jsx(rt,{variant:"primary",onClick:Re,disabled:j||!N.name||!N.prompt,children:j?"Saving...":"Save"})]})]})});const ot=je=>je.map(Me=>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:Me.name})})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(ci,{onClick:()=>ce(Me.id)}),i.jsx(Il,{onClick:()=>ie(Me.id)}),R(Me.id,"delete")?i.jsx(Qu,{onConfirm:()=>De(Me.id),onCancel:U}):i.jsx(Ju,{onClick:()=>W(Me.id)})]})]},Me.id));return i.jsxs(jt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[i.jsx(P1,{description:"Commands are pre-defined messages you can send with a single click.",onNew:he}),i.jsxs(ug,{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(je=>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:je.name})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(_$,{onClick:()=>J(je.id)}),i.jsx(Il,{onClick:()=>ie(je.id)})]})]},je.id))})]}),a.length>0&&i.jsx(M1,{children:ot(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:ot(l)})]})]})]})}function S$({title:e,defaultOpen:t=!1,children:n,className:r=""}){return i.jsxs("details",{className:`group ${r}`,open:t,children:[i.jsxs("summary",{className:"text-[11px] text-text-secondary uppercase tracking-wider font-medium cursor-pointer select-none hover:text-text-primary transition-colors list-none flex items-center gap-1",children:[i.jsx(hn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),e]}),i.jsx("div",{className:"mt-2 space-y-2",children:n})]})}const Bi=150,bs=54,Bu=80,Ar=30,Ga=70,US=100,$i=50,$u=50,FS=4,mj={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},pj=[{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)"}],w$=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"},{value:"user",label:"User (pause)"}];function rx(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 e.type==="user"?{name:"User",color:"#f59e0b"}:{name:"Shell",color:"#22c55e"}}function C$(e,t,n,r){const a=$u+$i+Bi+US+Bi+$i+$u,l=a/2,u=$u+$i+Bi/2,c=$u+$i+Bi+US+Bi/2,d=[],h=[],p=new Map,m=e.filter(G=>G.type==="agent"||G.type==="shell"||G.type==="user"),x=e.filter(G=>G.type==="sub_agent"),y=x.length>0,w=y?u:l,C=m.length>0?c:l,_=$i+Ar/2;d.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:_,w:Bu,h:Ar}),p.set("$start",{cx:w,cy:_,w:Bu,h:Ar});const S=G=>{d.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:G,w:Bu,h:Ar}),p.set("$done",{cx:w,cy:G,w:Bu,h:Ar})};if(e.length===0){const G=_+Ar/2+Ga*2+Ar/2;return S(G),{nodes:d,edges:h,width:a,height:G+Ar/2+$i,posMap:p}}const v=_+Ar/2+Ga,b=(G,V)=>{G.forEach((Z,X)=>{const $=v+X*(bs+Ga)+bs/2,{name:I,color:B}=rx(Z,r);d.push({id:Z.id,type:"step",label:I,color:B,cx:V,cy:$,w:Bi,h:bs}),p.set(Z.id,{cx:V,cy:$,w:Bi,h:bs})})};b(m,w),b(x,C);const j=m.length>0?v+(m.length-1)*(bs+Ga)+bs/2:_,N=y?v+(x.length-1)*(bs+Ga)+bs/2:_,T=Math.max(j,N)+bs/2+Ga+Ar/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 G of e)G.transitions.forEach((V,Z)=>{var z;if(!V.goto||!p.has(V.goto))return;const X=p.get(G.id),$=p.get(V.goto),I=V.when.type==="step_result"?`${V.when.result}`:V.when.type==="metadata_all_match"?`${V.when.key??"?"}=${V.when.value??"?"}`:V.when.type==="metadata_all_in"?`${V.when.key??"?"} in [${((z=V.when.values)==null?void 0:z.join(","))??"?"}]`:mj[V.when.type]??V.when.type,B=G.id===V.goto;let q;B?q="back":$.cy>X.cy+1?q="down":$.cy<X.cy-1?q="back":q="same",D.push({from:G.id,to:V.goto,label:I,edgeKey:`${G.id}:${Z}`,direction:q,backEdgeIndex:q==="back"?L++:0})});const O=new Map,M=new Map,W=new Map,U=new Map;for(const G of D)G.direction==="down"&&(O.set(G.from,(O.get(G.from)??0)+1),M.set(G.to,(M.get(G.to)??0)+1));const R=new Map,H=new Map;for(const G of D){if(G.direction!=="same")continue;const V=[G.from,G.to].sort().join("|");R.set(V,(R.get(V)??0)+1)}for(const G of D){if(G.direction==="back"||G.direction==="same"){let q=0;if(G.direction==="same"){const z=[G.from,G.to].sort().join("|");q=H.get(z)??0,H.set(z,q+1)}h.push({...G,fromPort:0,toPort:0,sameEdgeIndex:q});continue}const V=O.get(G.from)??1,Z=M.get(G.to)??1,X=W.get(G.from)??0,$=U.get(G.to)??0;W.set(G.from,X+1),U.set(G.to,$+1);const I=V===1?0:-.6+1.2*X/(V-1),B=Z===1?0:-.6+1.2*$/(Z-1);h.push({...G,fromPort:I,toPort:B,sameEdgeIndex:0})}return{nodes:d,edges:h,width:a,height:T+Ar/2+$i,posMap:p}}function k$({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=E.useRef(null),C=E.useRef(!1),[_,S]=E.useState(null),[v,b]=E.useState(null),[j,N]=E.useState(null),{nodes:T,edges:D,width:L,height:O,posMap:M}=E.useMemo(()=>C$(e,t,a,l),[e,t,a,l]),W=E.useCallback(re=>{var ie;const Q=w.current;if(!Q)return{x:0,y:0};const K=Q.createSVGPoint();K.x=re.clientX,K.y=re.clientY;const P=(ie=Q.getScreenCTM())==null?void 0:ie.inverse();if(!P)return{x:0,y:0};const J=K.matrixTransform(P);return{x:J.x,y:J.y}},[]),U=E.useCallback(re=>!re||!v||re==="$start"?!1:v.type==="reconnect-from"?re!=="$done":!0,[v]),R=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=W(re);b({type:"new",fromNodeId:Q,mouseX:K.x,mouseY:K.y})},[W,u]),H=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=W(re);b({type:"reconnect-to",fromNodeId:Q.from,edgeKey:Q.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),G=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=W(re);b({type:"reconnect-from",fromNodeId:Q.from,fixedTargetId:Q.to,edgeKey:Q.edgeKey,mouseX:K.x,mouseY:K.y})},[W,u]),V=E.useCallback(re=>{if(!v)return;const Q=W(re);b(K=>K?{...K,mouseX:Q.x,mouseY:Q.y}:null)},[v,W]),Z=E.useCallback(()=>{v&&(C.current=!0,j&&U(j)&&(v.type==="new"?p(v.fromNodeId,j):v.type==="reconnect-to"?m(v.edgeKey,j):v.type==="reconnect-from"&&x(v.edgeKey,j)),b(null),N(null))},[v,j,U,p,m,x]),X=E.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);E.useEffect(()=>{if(u)return;const re=Q=>{Q.target instanceof HTMLInputElement||Q.target instanceof HTMLTextAreaElement||Q.target instanceof HTMLSelectElement||(Q.key==="Delete"||Q.key==="Backspace")&&r&&r!=="start"&&(Q.preventDefault(),y(r),d(null))};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[u,r,y,d]);const $=re=>{const Q=M.get(re.from),K=M.get(re.to);if(!Q||!K)return null;let P,J,ie,he="middle",ce,De;if(re.direction==="down"){const Re=Q.cx+re.fromPort*(Q.w/2-10),ze=Q.cy+Q.h/2,Fe=K.cx+re.toPort*(K.w/2-10),Ee=K.cy-K.h/2,st=Ee-ze,ot=Fe-Re;P=`M ${Re} ${ze} C ${Re} ${ze+st*.4}, ${Fe-ot*.2} ${Ee-st*.1}, ${Fe} ${Ee}`,J=Re+(Fe-Re)*.5,ie=ze+st*.6,ce={x:Re,y:ze},De={x:Fe,y:Ee}}else if(re.direction==="back"){const Re=re.from===re.to,ze=Q.cx>=L/2,Fe=re.backEdgeIndex*16,Ee=ze?L-20-Fe:20+Fe;if(Re){const st=Q.cx>=L/2,ot=30+re.backEdgeIndex*14,je=Q.cy-Q.h/2,Me=st?Q.cx+Q.w/2:Q.cx-Q.w/2,lt=st?Me+ot:Me-ot,we=Q.cx+(st?Q.w/4:-Q.w/4),Ie=je-20-re.backEdgeIndex*10;P=`M ${Me} ${Q.cy} C ${lt} ${Q.cy}, ${lt} ${Ie}, ${we} ${je}`,J=lt+10,ie=Ie+4,he="middle",ce={x:Me,y:Q.cy},De={x:we,y:je}}else{const st=ze?Q.cx+Q.w/2:Q.cx-Q.w/2,ot=K.cx+(ze?K.w/4:-K.w/4),je=Math.min(Q.cy,K.cy)-K.h/2-18-re.backEdgeIndex*14;P=`M ${st} ${Q.cy} L ${Ee} ${Q.cy} L ${Ee} ${je} L ${ot} ${je} L ${ot} ${K.cy-K.h/2}`,J=Ee,ie=(Q.cy+je)/2,he=ze?"start":"end",ce={x:st,y:Q.cy},De={x:ot,y:K.cy-K.h/2}}}else{const Re=K.cx>Q.cx,ze=re.sameEdgeIndex===0?-12:12,Fe=Re?Q.cx+Q.w/2:Q.cx-Q.w/2,Ee=Re?K.cx-K.w/2:K.cx+K.w/2,st=Q.cy+ze,ot=K.cy+ze,je=(Fe+Ee)/2;P=`M ${Fe} ${st} C ${je} ${st}, ${je} ${ot}, ${Ee} ${ot}`,J=je,ie=(st+ot)/2-6,ce={x:Fe,y:st},De={x:Ee,y:ot}}return{path:P,labelX:J,labelY:ie,labelAnchor:he,fromPt:ce,toPt:De}},I=(re,Q)=>{const K=$(re);if(!K)return null;const{path:P,labelX:J,labelY:ie,labelAnchor:he}=K,ce=r===re.edgeKey,De=re.label&&re.label!=="otherwise";return i.jsxs("g",{children:[i.jsx("path",{d:P,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Re=>{Re.stopPropagation(),u||d(ce?null:re.edgeKey)}}),i.jsx("path",{d:P,fill:"none",stroke:ce?"#58a6ff":"#484f58",strokeWidth:ce?2.2:1.2,markerEnd:ce?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),De&&i.jsx("text",{x:J+(he==="start"?5:he==="end"?-5:0),y:ie+3,textAnchor:he,className:"text-[8px]",fill:ce?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:re.label})]},Q)},B=()=>{if(!r||v)return null;const re=D.find(ie=>ie.edgeKey===r);if(!re)return null;const Q=$(re);if(!Q)return null;const{fromPt:K,toPt:P}=Q,J=6;return i.jsxs(i.Fragment,{children:[re.edgeKey!=="start"&&i.jsx("circle",{cx:K.x,cy:K.y,r:J,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>G(ie,re)}),i.jsx("circle",{cx:P.x,cy:P.y,r:J,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>H(ie,re)})]})},q=()=>{if(!v)return null;let re,Q,K,P;if(v.type==="reconnect-from"){const he=M.get(v.fixedTargetId);if(!he)return null;re=v.mouseX,Q=v.mouseY,K=he.cx,P=he.cy-he.h/2}else{const he=M.get(v.fromNodeId);if(!he)return null;re=he.cx,Q=he.cy+he.h/2,K=v.mouseX,P=v.mouseY}const J=P-Q,ie=Math.abs(J)>10?`M ${re} ${Q} C ${re} ${Q+J*.4}, ${K} ${P-J*.4}, ${K} ${P}`:`M ${re} ${Q} L ${K} ${P}`;return i.jsx("path",{d:ie,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},z=re=>{const Q=re.cy+re.h/2,K=(v==null?void 0:v.fromNodeId)===re.id;return i.jsx("circle",{cx:re.cx,cy:Q,r:FS,fill:K?"#58a6ff":"#1c2128",stroke:K?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5,className:"cursor-crosshair",onMouseDown:P=>R(P,re.id)})},ne=re=>{const Q=re.cy-re.h/2,K=v&&j===re.id&&U(re.id);return i.jsx("circle",{cx:re.cx,cy:Q,r:FS,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} ${O}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:V,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((re,Q)=>I(re,Q)),T.map(re=>{const Q=n===re.id,K=re.cx-re.w/2,P=re.cy-re.h/2,J=_===re.id,ie=v&&j===re.id&&U(re.id);if(re.type==="terminal"){const ce=re.id==="$start",De=ce?"#58a6ff":"#3fb950",Re=ce,ze=!ce;return i.jsxs("g",{onClick:Fe=>{Fe.stopPropagation(),ce&&!u&&d("start")},className:ce&&!u?"cursor-pointer":void 0,children:[ie&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:re.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ce&&r==="start"&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:re.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:P,width:re.w,height:re.h,rx:re.h/2,fill:De,fillOpacity:.08,stroke:De,strokeOpacity:.4,strokeWidth:1.5}),i.jsx("text",{x:re.cx,y:re.cy+4,textAnchor:"middle",fill:De,className:"text-[10px] font-medium",pointerEvents:"none",children:re.label}),Re&&z(re),ze&&ne(re)]},re.id)}const he=re.color??"#6b7280";return i.jsxs("g",{onClick:ce=>{ce.stopPropagation(),u||c(Q?null:re.id)},onMouseEnter:()=>S(re.id),onMouseLeave:()=>S(null),className:u?void 0:"cursor-pointer",children:[ie&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),Q&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:P,width:re.w,height:re.h,rx:10,fill:he,fillOpacity:.08,stroke:he,strokeOpacity:.6,strokeWidth:Q?2:1.5}),i.jsx("text",{x:re.cx,y:re.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:re.label}),!u&&z(re),!u&&ne(re),J&&!v&&!u&&i.jsxs("g",{onClick:ce=>{ce.stopPropagation(),h(re.id)},className:"cursor-pointer",children:[i.jsx("circle",{cx:K+re.w-2,cy:P+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),i.jsx("line",{x1:K+re.w-5,y1:P-1,x2:K+re.w+1,y2:P+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),i.jsx("line",{x1:K+re.w+1,y1:P-1,x2:K+re.w-5,y2:P+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},re.id)}),v&&T.map(re=>U(re.id)?i.jsx("rect",{x:re.cx-re.w/2-8,y:re.cy-re.h/2-8,width:re.w+16,height:re.h+16,fill:"transparent",rx:12,onMouseEnter:()=>N(re.id),onMouseLeave:()=>N(null),onMouseUp:Q=>{Q.stopPropagation(),Z()}},`drop-${re.id}`):null),q(),B()]})}const zu="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",_l="block text-[11px] text-text-secondary mb-0.5";function j$({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:_l,children:"Name"}),i.jsx("input",{value:e,onChange:p=>u(p.target.value),placeholder:"Workflow name",className:`${zu} ${l?"opacity-50":""}`,readOnly:l})]}),i.jsxs("div",{className:"min-w-[100px]",children:[i.jsx("label",{className:_l,children:"ID"}),i.jsx("input",{value:t,readOnly:!0,className:`${zu} font-mono opacity-50`})]}),i.jsxs("div",{className:"flex-1 min-w-[140px]",children:[i.jsx("label",{className:_l,children:"Description"}),i.jsx("input",{value:n,onChange:p=>!l&&c(p.target.value),readOnly:l,placeholder:"What does this workflow do?",className:`${zu} ${l?"opacity-50":""}`})]}),i.jsxs("div",{className:"w-20",children:[i.jsx("label",{className:_l,children:"Max Iter."}),i.jsx("input",{type:"number",value:r,onChange:p=>!l&&d(Number(p.target.value)),readOnly:l,className:`${zu} font-mono ${l?"opacity-50":""}`})]}),i.jsxs("div",{children:[i.jsx("label",{className:_l,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 E$({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 up({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(E$,{name:r.name,id:r.id,color:r.color??"#3b82f6",description:r.description,actions:n(r)},r.id))})]})}const Wa="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",dp="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 hp({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 N$({step:e,isEntry:t,agentTypes:n,transitionCount:r,templateVariables:a,onUpdate:l,onRemove:u,onSetEntry:c}){const{color:d,name:h}=rx(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(m==="user"?{...e,type:m,phase:x,name:"User"}:{...e,type:m,phase:x,name:"Shell"})},className:dp,children:w$.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:dp,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:dp,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:`${Wa} resize-y text-xs`,placeholder:"Injected on first entry..."}),i.jsx(hp,{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:`${Wa} resize-y text-xs`,placeholder:"Injected on re-entry..."}),i.jsx(hp,{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:`${Wa} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),i.jsx(hp,{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:`${Wa} 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:`${Wa} 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:Wa})]}),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 qa="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="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",zi="block text-[11px] text-text-secondary mb-0.5";function T$({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(hn,{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(hn,{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(C1,{}),i.jsx("span",{className:"font-medium text-text-primary",children:t})]}),i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Condition"}),i.jsx("select",{value:n.type,onChange:_=>{d(_.target.value==="step_result"?{type:"step_result",result:"success"}:{type:_.target.value})},className:VS,children:pj.map(_=>i.jsx("option",{value:_.value,children:_.label},_.value))})]}),n.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Result"}),w?i.jsx("select",{value:n.result??y.results[0],onChange:_=>{d({type:"step_result",result:_.target.value})},className:VS,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:qa})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:zi,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:qa})]}),i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Field"}),i.jsx("input",{type:"text",value:n.field??"",onChange:_=>d({...n,field:_.target.value}),placeholder:"e.g. status",className:qa})]}),n.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Value"}),i.jsx("input",{type:"text",value:n.value??"",onChange:_=>d({...n,value:_.target.value}),placeholder:"e.g. passed, resolved",className:qa})]}):i.jsxs("div",{children:[i.jsx("label",{className:zi,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:qa})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:zi,children:"Sub-group"}),i.jsx("input",{type:"text",value:r??"",onChange:_=>h(_.target.value||void 0),placeholder:"e.g. build, verify",className:qa})]}),i.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function A$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function L$(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const Sl="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",GS="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",Ka="block text-[11px] text-text-secondary mb-0.5",WS=[];function gj({isOpen:e,onClose:t,initialEditId:n}){var Ts,As;const r=vt(Se=>Se.defaults),a=vt(Se=>Se.userItems),l=vt(Se=>Se.projectItems),u=vt(Se=>Se.loading),c=vt(Se=>Se.templateVariables),d=vt(Se=>Se.fetchWorkflows),h=vt(Se=>Se.fetchWorkflow),p=vt(Se=>Se.fetchDefaultContent),m=vt(Se=>Se.fetchTemplateVariables),x=vt(Se=>Se.createWorkflow),y=vt(Se=>Se.updateWorkflow),w=vt(Se=>Se.deleteWorkflow),{requestDelete:C,clearConfirm:_,isConfirming:S}=Yl(),[v,b]=E.useState("list"),[j,N]=E.useState(null),[T,D]=E.useState(!1),[L,O]=E.useState(null),[M,W]=E.useState(null),[U,R]=E.useState(""),[H,G]=E.useState(""),[V,Z]=E.useState(""),[X,$]=E.useState("1.0.0"),[I,B]=E.useState("#3b82f6"),[q,z]=E.useState(""),[ne,re]=E.useState(50),[Q,K]=E.useState(WS),[P,J]=E.useState({type:"always"}),[ie,he]=E.useState([]),[ce,De]=E.useState("user"),[Re,ze]=E.useState(""),[Fe,Ee]=E.useState(!1),st=xt(Se=>Se.defaults),ot=xt(Se=>Se.userItems),je=xt(Se=>Se.projectItems),Me=E.useMemo(()=>[...st,...ot,...je],[st,ot,je]),lt=xt(Se=>Se.fetchAgents),[we]=E.useState(null);E.useEffect(()=>{e&&(d(),m(),lt(),O(null),W(null),n?r.some(Ce=>Ce.id===n)?p(n).then(Ce=>{Ce&&Ie({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):h(n).then(Ce=>{Ce&&Ie(Ce,{editingId:n,isReadOnly:!1})}):(b("list"),N(null),D(!1)))},[e,d,h,p,m,n]);const Ie=(Se,Ce)=>{R(Se.metadata.name),G(Se.metadata.id),Z(Se.metadata.description),$(Se.metadata.version),B(Se.metadata.color??"#3b82f6"),z(Se.entryStep),re(Se.settings.maxIterations),K(Se.steps),J(Se.startCondition??{type:"always"}),he(Se.metadata.parameters??[]),ze(""),(Ce==null?void 0:Ce.editingId)!==void 0&&N(Ce.editingId),(Ce==null?void 0:Ce.isReadOnly)!==void 0&&D(Ce.isReadOnly),(Ce==null?void 0:Ce.selectedNodeKey)!==void 0&&O(null),(Ce==null?void 0:Ce.selectedEdgeKey)!==void 0&&W(null),b("edit")},qe=async Se=>{const Ce=await h(Se);Ce&&Ie(Ce,{editingId:Se,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},te=async()=>{var Qe;const Se=j??H;if(!Se||!U)return ze("Name is required."),!1;if(Q.length===0)return ze("Add at least one step."),!1;const Ce=ie.find(at=>!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(at.id));if(Ce)return ze(`Invalid parameter ID "${Ce.id}". Use letters, digits, and underscores only.`),!1;let Oe=q;if(!Oe||!Q.some(at=>at.id===Oe)){if(Oe=((Qe=Q.find(at=>at.id))==null?void 0:Qe.id)??"",!Oe)return ze("All steps need an ID."),!1;z(Oe)}Ee(!0),ze("");const We={metadata:{id:Se,name:U,description:V,version:X||"1.0.0",color:I,...ie.length>0?{parameters:ie}:{}},entryStep:Oe,settings:{maxIterations:ne},steps:Q,startCondition:P},Ve=j?await y(j,We):await x(We,ce);return Ee(!1),Ve.success?(j||N(Se),!0):(ze(Ve.error??"Failed to save."),!1)},ae=async()=>{await te()},se=async()=>{await te()&&(n?t():b("list"))},me=()=>{n?t():b("list")},Ue=Se=>{R(Se),j||G(A$(Se))},He=async Se=>r.some(Oe=>Oe.id===Se)?await p(Se):await h(Se),Ye=async Se=>{const Ce=await He(Se);Ce&&Ie({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${Se}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},ct=()=>{N(null),R(""),G(""),Z(""),$("1.0.0"),B("#3b82f6"),z(""),re(50),K(structuredClone(WS)),J({type:"always"}),he([]),De("user"),ze(""),O(null),W(null),D(!1),b("edit")},Je=async Se=>{await w(Se),_()},Ze=E.useCallback(Se=>{O(Se),W(null)},[]),tt=E.useCallback(Se=>{W(Se),O(null)},[]),Nt=L!==null?Number(L):-1,dt=Nt>=0?Q[Nt]??null:null,rn=E.useCallback(Se=>{K(Ce=>Ce.map((Oe,We)=>We===Nt?Se:Oe))},[Nt]),Un=P.type==="step_result"?`${P.result}`:P.type==="metadata_all_match"?`${P.key??"?"}=${P.value??"?"}`:P.type==="metadata_all_in"?`${P.key??"?"} in [${((Ts=P.values)==null?void 0:Ts.join(","))??"?"}]`:mj[P.type]??P.type,ye=()=>{const Se=Q.length,Ce=L$(Q),Oe=Me.find(We=>!We.subagent);K([...Q,{id:Ce,name:(Oe==null?void 0:Oe.name)??"Agent",type:"agent",phase:"build",agentId:(Oe==null?void 0:Oe.id)??"builder",transitions:[]}]),q||z(Ce),Ze(String(Se))},Ge=E.useCallback((Se,Ce)=>{Se==="$start"?(z(Ce),tt("start")):K(Oe=>{const We=Oe.find(Qe=>Qe.id===Se),Ve=We?We.transitions.length:0;return tt(`${Se}:${Ve}`),Oe.map(Qe=>Qe.id===Se?{...Qe,transitions:[...Qe.transitions,{when:{type:"always"},goto:Ce}]}:Qe)})},[tt]),oe=Se=>{if(Se==="start")return null;const Ce=Se.lastIndexOf(":"),Oe=Se.slice(0,Ce),We=parseInt(Se.slice(Ce+1));return{stepId:Oe,transIdx:We}},fe=E.useCallback((Se,Ce)=>{const Oe=oe(Se);Oe&&K(We=>We.map(Ve=>Ve.id===Oe.stepId?{...Ve,transitions:Ve.transitions.map((Qe,at)=>at===Oe.transIdx?Ce(Qe):Qe)}:Ve))},[]),Pe=E.useCallback((Se,Ce)=>{if(Se==="start"){z(Ce);return}fe(Se,Oe=>({...Oe,goto:Ce}))},[fe]),St=E.useCallback((Se,Ce)=>{const Oe=oe(Se);Oe&&(K(We=>{const Ve=We.find(at=>at.id===Oe.stepId);if(!Ve)return We;const Qe=Ve.transitions[Oe.transIdx];return Qe?We.map(at=>at.id===Oe.stepId?{...at,transitions:at.transitions.filter((Zt,mn)=>mn!==Oe.transIdx)}:at.id===Ce?{...at,transitions:[...at.transitions,Qe]}:at):We}),W(null))},[]),bn=E.useCallback(Se=>{if(Se==="start"){z(""),W(null);return}const Ce=oe(Se);Ce&&(K(Oe=>Oe.map(We=>We.id===Ce.stepId?{...We,transitions:We.transitions.filter((Ve,Qe)=>Qe!==Ce.transIdx)}:We)),W(null))},[]),fn=E.useCallback((Se,Ce)=>{if(Se==="start"){J(Ce);return}fe(Se,Oe=>({...Oe,when:Ce}))},[fe]),Pr=E.useCallback((Se,Ce)=>{Se!=="start"&&fe(Se,Oe=>({...Oe,subGroup:Ce||void 0}))},[fe]),Ns=Se=>rx(Se,Me).name,xi=()=>{if(!M)return null;if(M==="start"){const Zt=Q.find(mn=>mn.id===q);return{type:"start",fromLabel:"Start",toLabel:Zt?Ns(Zt):"(none)",condition:P}}const Se=M.lastIndexOf(":"),Ce=M.slice(0,Se),Oe=parseInt(M.slice(Se+1)),We=Q.find(Zt=>Zt.id===Ce);if(!We)return null;const Ve=We.transitions[Oe];if(!Ve)return null;const Qe=Q.find(Zt=>Zt.id===Ve.goto),at=Ve.goto==="$done"?"Done":Qe?Ns(Qe):Ve.goto;return{type:"step",fromLabel:Ns(We),toLabel:at,condition:Ve.when,subGroup:Ve.subGroup}};if(v==="edit"){const Se=xi();return i.jsxs(jt,{isOpen:e,onClose:me,title:T?U:j?"Edit Workflow":"New Workflow",size:"full",children:[Re&&i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:Re}),i.jsx(j$,{formName:U,formId:H,formDescription:V,formMaxIterations:ne,formColor:I,isReadOnly:T,onNameChange:Ue,onDescriptionChange:Z,onMaxIterationsChange:re,onColorChange:B}),!T&&i.jsx("div",{className:"mb-3 pb-3 border-b border-border",children:i.jsxs(S$,{title:`Parameters (${ie.length})`,children:[ie.map((Ce,Oe)=>i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{value:Ce.id,onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,id:We.target.value},he(Ve)},placeholder:"ID",className:"w-28 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"}),i.jsx("input",{value:Ce.label,onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,label:We.target.value},he(Ve)},placeholder:"Label",className:"w-36 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary"}),i.jsx("input",{value:Ce.description??"",onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,description:We.target.value||void 0},he(Ve)},placeholder:"Description",className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary"}),i.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-muted whitespace-nowrap",children:[i.jsx("input",{type:"checkbox",checked:Ce.required??!1,onChange:We=>{const Ve=[...ie];Ve[Oe]={...Ce,required:We.target.checked||void 0},he(Ve)},className:"rounded border-border"}),"Req."]}),i.jsxs("div",{className:"flex gap-0.5",children:[i.jsx("button",{onClick:()=>{Oe!==0&&he(ie.map((We,Ve)=>Ve===Oe?{...ie[Oe-1],position:Ve}:Ve===Oe-1?{...ie[Oe],position:Ve}:{...We,position:Ve}))},disabled:Oe===0,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move up","aria-label":`Move ${Ce.label||Ce.id} up`,children:"▲"}),i.jsx("button",{onClick:()=>{Oe!==ie.length-1&&he(ie.map((We,Ve)=>Ve===Oe?{...ie[Oe+1],position:Ve}:Ve===Oe+1?{...ie[Oe],position:Ve}:{...We,position:Ve}))},disabled:Oe===ie.length-1,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move down","aria-label":`Move ${Ce.label||Ce.id} down`,children:"▼"})]}),i.jsx("button",{onClick:()=>he(ie.filter((We,Ve)=>Ve!==Oe)),className:"p-1 text-text-muted hover:text-accent-error transition-colors",title:"Remove parameter",children:"✕"})]},Ce.id)),i.jsx("button",{onClick:()=>{const Ce=`param_${ie.length+1}`;he([...ie,{id:Ce,label:"",description:"",required:!1}])},className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:"+ Add parameter"})]})}),!j&&!T&&i.jsx(Nd,{value:ce,onChange:De}),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"}),!T&&i.jsx("button",{onClick:ye,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(k$,{steps:Q,entryStep:q,selectedNodeId:(dt==null?void 0:dt.id)??null,selectedEdgeKey:M,startConditionLabel:Un,agentTypes:Me,isReadOnly:T,onSelectNode:Ce=>{if(Ce===null){Ze(null);return}const Oe=Q.findIndex(We=>We.id===Ce);Ze(Oe>=0?String(Oe):null)},onSelectEdge:tt,onRemoveStep:Ce=>{var We;const Oe=Q.findIndex(Ve=>Ve.id===Ce);if(K(Ve=>Ve.filter(Qe=>Qe.id!==Ce)),Nt===Oe&&Ze(null),q===Ce){const Ve=Q.filter(Qe=>Qe.id!==Ce);z(((We=Ve[0])==null?void 0:We.id)??"")}},onCreateTransition:Ge,onReconnectTo:Pe,onReconnectFrom:St,onDeleteTransition:bn}),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:ye,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:T&&(Se||dt)?i.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):Se?Se.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"})}),q&&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(C1,{}),i.jsx("span",{className:"text-text-primary font-medium",children:Se.toLabel})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Activation Condition"}),i.jsx("select",{value:P.type,onChange:Ce=>J(Ce.target.value==="step_result"?{type:"step_result",result:"success"}:Ce.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:Ce.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:Ce.target.value}),className:GS,children:pj.map(Ce=>i.jsx("option",{value:Ce.value,children:Ce.label},Ce.value))})]}),P.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Result"}),q&&(()=>{const Ce=Q.find(Qe=>Qe.id===q),Oe=Ce&&(Ce.type==="sub_agent"||Ce.type==="agent")?Me.find(Qe=>Qe.id===(Ce.type==="sub_agent"?Ce.subAgentType:Ce.agentId)):void 0,We=(Oe==null?void 0:Oe.results)&&Oe.results.length>0,Ve=(Oe==null?void 0:Oe.results)??[];return We?i.jsx("select",{value:P.result??Ve[0],onChange:Qe=>J({type:"step_result",result:Qe.target.value}),className:GS,children:Ve.map(Qe=>i.jsx("option",{value:Qe,children:Qe},Qe))}):i.jsx("input",{type:"text",value:P.result??"success",onChange:Qe=>J({type:"step_result",result:Qe.target.value}),placeholder:"e.g. success, passed, failed",className:Sl})})()]}),(P.type==="metadata_all_match"||P.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Metadata Key"}),i.jsx("input",{type:"text",value:P.key??"",onChange:Ce=>J({...P,key:Ce.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:Sl})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Field"}),i.jsx("input",{type:"text",value:P.field??"",onChange:Ce=>J({...P,field:Ce.target.value}),placeholder:"e.g. status",className:Sl})]}),P.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Value"}),i.jsx("input",{type:"text",value:P.value??"",onChange:Ce=>J({...P,value:Ce.target.value}),placeholder:"e.g. passed, resolved",className:Sl})]}):i.jsxs("div",{children:[i.jsx("label",{className:Ka,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((As=P.values)==null?void 0:As.join(", "))??"",onChange:Ce=>J({...P,values:Ce.target.value.split(",").map(Oe=>Oe.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:Sl})]})]}),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 Ce=oe(M),Oe=Ce==null?void 0:Ce.stepId,We=(Ce==null?void 0:Ce.transIdx)??0,Ve=Oe?Q.find(at=>at.id===Oe):void 0,Qe=(Ve==null?void 0:Ve.transitions.length)??0;return i.jsx(T$,{fromLabel:Se.fromLabel,toLabel:Se.toLabel,condition:Se.condition,subGroup:"subGroup"in Se?Se.subGroup:void 0,fromStep:Se.type==="step"?Q.find(at=>at.id===Se.fromLabel):void 0,agentTypes:Me,transitionIndex:We,totalTransitions:Qe,onUpdateCondition:at=>fn(M,at),onUpdateSubGroup:at=>Pr(M,at),onDelete:()=>bn(M),onMoveUp:()=>{K(at=>{const Zt=at.find(Zn=>Zn.id===Oe);if(!Zt||We===0)return at;const mn=[...Zt.transitions];return[mn[We-1],mn[We]]=[mn[We],mn[We-1]],at.map(Zn=>Zn.id===Oe?{...Zn,transitions:mn}:Zn)}),W(`${Oe}:${We-1}`)},onMoveDown:()=>{K(at=>{const Zt=at.find(Zn=>Zn.id===Oe);if(!Zt||We===Zt.transitions.length-1)return at;const mn=[...Zt.transitions];return[mn[We],mn[We+1]]=[mn[We+1],mn[We]],at.map(Zn=>Zn.id===Oe?{...Zn,transitions:mn}:Zn)}),W(`${Oe}:${We+1}`)}})})():dt?i.jsx(N$,{step:dt,isEntry:dt.id===q,agentTypes:Me,transitionCount:dt.transitions.length,templateVariables:c,onUpdate:rn,onRemove:()=>{var Ce;if(dt&&(K(Q.filter((Oe,We)=>We!==Nt)),Ze(null),q===dt.id)){const Oe=Q.filter((We,Ve)=>Ve!==Nt);z(((Ce=Oe[0])==null?void 0:Ce.id)??"")}},onSetEntry:()=>z(dt.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(rt,{variant:"secondary",onClick:me,children:"Close"}),T?i.jsx(rt,{variant:"primary",onClick:()=>{R(U+" (copy)"),G(`${j}-copy-${Date.now()}`),N(null),D(!1)},children:"Duplicate & Customize"}):i.jsxs(i.Fragment,{children:[i.jsx(rt,{variant:"primary",onClick:ae,children:"Save"}),i.jsx(rt,{variant:"primary",onClick:se,children:"Save & Close"})]})]})]})}return i.jsx(jt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:i.jsx(I1,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:ct,loading:u,hasItems:r.length>0||a.length>0||l.length>0,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(up,{title:"Built-in",items:r,renderActions:Se=>i.jsx(i.Fragment,{children:i.jsx(ci,{onClick:()=>Ye(Se.id),children:i.jsx(ig,{})})})}),i.jsx(up,{title:"Custom",items:a,renderActions:Se=>i.jsxs(i.Fragment,{children:[i.jsx(ci,{onClick:()=>qe(Se.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Il,{onClick:()=>Ye(Se.id)}),S(Se.id,"delete")?i.jsx(Qu,{onConfirm:()=>Je(Se.id),onCancel:_}):i.jsx(Ju,{onClick:()=>C(Se.id)})]})}),l.length>0&&i.jsx(up,{title:"Project",items:l,renderActions:Se=>i.jsxs(i.Fragment,{children:[i.jsx(ci,{onClick:()=>qe(Se.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Il,{onClick:()=>Ye(Se.id)}),S(Se.id,"delete")?i.jsx(Qu,{onConfirm:()=>Je(Se.id),onCancel:_}):i.jsx(Ju,{onClick:()=>C(Se.id)})]})})]})})})}function D$(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function R$({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:r,onSelectWorkflow:a,onCloseCompleteAction:l,textareaContent:u,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:h}){const[,p]=Tn(),m=Yt(z=>z.fetchCommands),x=vt(z=>z.fetchWorkflows),y=xt(z=>z.fetchAgents),w=Yt(z=>z.defaults),C=Yt(z=>z.userItems),_=Yt(z=>z.projectItems),S=vt(z=>z.defaults),v=vt(z=>z.userItems),b=vt(z=>z.projectItems),j=xt(z=>z.defaults),N=xt(z=>z.userItems),T=xt(z=>z.projectItems),D=Le(z=>{var ne;return(ne=z.currentSession)==null?void 0:ne.mode}),L=Le(z=>{var ne;return((ne=z.currentSession)==null?void 0:ne.dangerLevel)??"normal"}),O=Le(z=>z.switchMode),M=Le(z=>z.switchDangerLevel),W=Le(z=>{var ne;return(ne=z.currentSession)==null?void 0:ne.projectId}),U=E.useRef(void 0),[R,H]=E.useState(""),[G,V]=E.useState(0),Z=E.useRef(null),X=E.useRef(!1);E.useEffect(()=>{e&&(X.current=!0)},[e]),E.useEffect(()=>{if(e){m(),x(),y(),H(""),V(0);const z=setTimeout(()=>{var ne;return(ne=Z.current)==null?void 0:ne.focus()},50);return()=>clearTimeout(z)}},[e,m,x,y]),E.useEffect(()=>{var z;!e&&X.current&&(n==null||n(),(z=U.current)==null||z.call(U),U.current=void 0)},[e,n]);const I=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const z=W??D$(window.location.pathname);z&&p(`/p/${z}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{U.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)}},...qr(qr(j,N),T).filter(z=>!z.subagent&&z.id!==D).map(z=>({id:z.id,name:z.name,prefix:"Agent > Switch to",action:()=>O(z.id)})),...qr(qr(w,C),_).map(z=>({id:z.id,name:z.name,prefix:"Command > Launch",action:()=>r(z.id,u)})),...qr(qr(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:()=>M(z)}))].filter(z=>li(`${z.prefix} ${z.name}`,R)),B=I.length-1,q=z=>{Pk(z,B,V,()=>{var ne;(ne=I[G])==null||ne.action(),t()},t)};return e?mi.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=>{H(z.target.value),V(0)},onKeyDown:q,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx(cg,{onClick:t,className:"shrink-0","aria-label":"Close"})]}),i.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:I.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"}):I.map((z,ne)=>i.jsxs("button",{type:"button",onClick:()=>{z.action(),t()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${ne===G?"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 xj="openfox-message-search-filters",O$=[{key:"user",label:"User prompts"},{key:"thinking",label:"Thinking"},{key:"response",label:"Responses"}];function I$(){try{const e=localStorage.getItem(xj);if(e){const t=JSON.parse(e);return new Set(t)}}catch{}return new Set(["user","thinking","response"])}function M$(e){localStorage.setItem(xj,JSON.stringify([...e]))}function P$(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 B$(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 $$(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 z$(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 H$(e){var n,r;if(e.type!=="message")return i.jsx(L_,{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(xT,{className:"w-3.5 h-3.5"}):i.jsx(L_,{className:"w-3.5 h-3.5"}):i.jsx(gT,{className:"w-3.5 h-3.5"})}function qS(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 U$({isOpen:e,onClose:t,displayItems:n,onNavigate:r}){const[a,l]=E.useState(""),[u,c]=E.useState(0),[d,h]=E.useState(I$),p=E.useRef(null),m=E.useRef(null),x=E.useRef(null),y=N=>{h(T=>{const D=new Set(T);return D.has(N)?D.delete(N):D.add(N),M$(D),D})},w=E.useMemo(()=>n.filter(N=>{var T,D;return!(N.type==="context-divider"||N.type==="message"&&(N.message.messageKind==="auto-prompt"||N.message.role==="assistant"&&!((T=N.message.content)!=null&&T.trim())&&!((D=N.message.thinkingContent)!=null&&D.trim())))}),[n]),C=E.useMemo(()=>w.filter(N=>{const T=P$(N);return!(T&&!d.has(T))}),[w,d]),_=E.useMemo(()=>a?w.filter(N=>{const T=qS(N);return li(T,a)}):C,[C,a]),S=_.length-1;E.useEffect(()=>{if(e){l(""),c(0);const N=setTimeout(()=>{var T;return(T=p.current)==null?void 0:T.focus()},50);return()=>clearTimeout(N)}},[e]),E.useEffect(()=>{e&&m.current&&(m.current.scrollTop=m.current.scrollHeight)},[e]),E.useEffect(()=>{x.current&&x.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[u]);const v=N=>{Pk(N,S,c,()=>{const T=_[u];if(T){const D=n.indexOf(T);D>=0&&r(D),t()}},t)},b=N=>{const T=n.indexOf(N);T>=0&&r(T),t()},j=N=>n.indexOf(N);return e?mi.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(Xi,{}),i.jsx("input",{ref:p,type:"text",value:a,onChange:N=>{l(N.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:O$.map(N=>{const T=d.has(N.key);return i.jsx("button",{type:"button",onClick:()=>y(N.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:N.label},N.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((N,T)=>{const D=j(N),L=H$(N),O=qS(N),M=z$(N),W=$$(N),U=N.type==="message"&&N.message.role==="user";return i.jsx("button",{ref:T===u?x:null,type:"button",onClick:()=>b(N),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${T===u?"bg-accent-primary/20 text-text-primary":U?"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 ${M}`,children:O})]}),W&&i.jsx("span",{className:"text-text-muted text-xs shrink-0",children:B$(W)})]})},`${D}-${N.type}`)})})]})]}),document.body):null}function yj(e){const t=new Set,n=[],r=/\{\{(\w+)\}\}/g;let a;for(;(a=r.exec(e))!==null;){const l=a[1];t.has(l)||(t.add(l),n.push(l))}return n}function F$(e,t,n){const r=e.trim();if(!r.startsWith("/"))return null;const a=r.slice(1).split(/\s+/),l=a[0];if(!l)return null;const u=a.slice(1),c={},d=t.find(h=>h.id===l);return d?(d.parameters&&d.parameters.length>0?[...d.parameters].sort((p,m)=>(p.position??0)-(m.position??0)).forEach((p,m)=>{u[m]!==void 0&&(c[p.id]=u[m])}):u.forEach((h,p)=>{c[String(p)]=h}),{workflowId:l,params:c}):n&&n.find(p=>p.id===l)?(u.forEach((p,m)=>{c[String(m)]=p}),{commandId:l,params:c}):null}function V$({attachment:e,onRemove:t}){const n=uj(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(rc,{onClick:()=>t(e.id),className:"absolute -top-2 -right-2",size:"sm",variant:"overlay","aria-label":`Remove ${e.filename}`}),cj(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:Za(e.size)})]})}function G$({history:e,selectedIndex:t,onSelect:n,onEscape:r,onNavigate:a}){const l=E.useRef(null),u=E.useRef(null);E.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 W$(){const e=WN(),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 q$={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function K$(e,t={}){const n={...q$,...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=t7(a),u=`data:${e.type};base64,${l}`,c=await b2(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await Y$(e,n)}async function Y$(e,t){const n=await Q$(e),r=await b2(n),{width:a,height:l}=X$(r.width,r.height,t.maxWidth,t.maxHeight),u=J$();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),!(KS(h)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=KS(h);return{dataUrl:h,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function X$(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 Q$(e){return new Promise((t,n)=>{const r=e7(),a=new r;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function b2(e){return new Promise((t,n)=>{const r=Z$(),a=new r;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function J$(){var t;const e=sx();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function Z$(){const e=sx();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function e7(){const e=sx();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function sx(){return globalThis}function t7(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 KS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}const YS=50*1024*1024,XS=1024*1024,n7=["image/png","image/jpeg","image/gif"];function r7(e){return e==="application/pdf"}function s7(e){return n7.includes(e.type)}async function i7(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 QS(e,t,n){try{if(nx(e.type)){if(e.size>XS){n(`Text file too large (${Za(e.size)}). Maximum is ${Za(XS)}.`);return}const r=await e.text(),a={id:Uu(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}else if(Yu(e.type)||r7(e.type)){if(e.size>YS){const r=Yu(e.type)?"Image":"PDF";n(`${r} file too large (${Za(e.size)}). Maximum is ${Za(YS)}.`);return}if(Yu(e.type)&&s7(e)){const r=await K$(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),a={id:Uu(),filename:e.name||"unnamed-file",mimeType:r.mimeType,size:r.size,data:r.dataUrl};t(a)}else{const r=await i7(e),a={id:Uu(),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 v2(e){const t=Le(l=>l.sendMessage),n=Le(l=>l.launchWorkflow),r=E.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=E.useCallback((l,u,c,d,h)=>{e(!0),n(l,u,c,d,h)},[e,n]);return{sendMessage:r,launchWorkflow:a}}function a7({children:e}){return mi.createPortal(e,document.body)}function o7(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 l7({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,h]=E.useState(!1),[p,m]=E.useState("commands"),[x,y]=E.useState(""),[w,C]=E.useState(0),[_,S]=E.useState(null),[v,b]=E.useState(null),j=E.useRef(null),N=E.useRef(null),T=Yt(ne=>ne.defaults),D=Yt(ne=>ne.userItems),L=Yt(ne=>ne.projectItems),O=Yt(ne=>ne.fetchCommands),M=vt(ne=>ne.defaults),W=vt(ne=>ne.userItems),U=vt(ne=>ne.projectItems),R=vt(ne=>ne.fetchWorkflows),H=qr(qr(T,D),L),G=qr(qr(M,W),U);E.useEffect(()=>{d&&(p==="commands"?O():p==="workflows"&&R())},[d,p,O,R]),E.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ne;return(ne=j.current)==null?void 0:ne.focus()}))},[d,p]),E.useEffect(()=>{if(!d)return;const ne=re=>{var Q;(Q=N.current)!=null&&Q.contains(re.target)||h(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[d]);const V=ne=>{switch(ne.key){case"ArrowDown":ne.preventDefault(),C(re=>{const K=(p==="commands"?H:G).filter(P=>{const J=x.toLowerCase();return!J||P.name.toLowerCase().includes(J)});return Math.min(re+1,K.length-1)});break;case"ArrowUp":ne.preventDefault(),C(re=>Math.max(re-1,0));break;case"Enter":ne.preventDefault();break;case"Escape":ne.preventDefault(),h(!1);break}},Z=ne=>{y(ne),C(0)},X=H.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),$=G.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),I=async ne=>{const re=await Yt.getState().fetchCommand(ne);re&&e(re.prompt,re.metadata.agentMode,u,c),h(!1)},B=ne=>{t(ne),h(!1)},q=(ne,re)=>{re.stopPropagation(),h(!1),S(ne)},z=(ne,re)=>{re.stopPropagation(),h(!1),b(ne)};return i.jsxs("div",{ref:N,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(N1,{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:j,value:x,onChange:ne=>Z(ne.target.value),onKeyDown:V,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:H.length===0?"No commands yet":"No matches"}):X.map((ne,re)=>i.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsx("button",{type:"button",onClick:()=>I(ne.id),className:"flex-1 text-left",children:i.jsx("div",{className:"text-sm text-text-primary font-medium",children:ne.name})}),i.jsx(ci,{className:"opacity-0 group-hover:opacity-100",onClick:Q=>q(ne.id,Q)})]},ne.id)):p==="workflows"?$.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:G.length===0?"No workflows yet":"No matches"}):$.map((ne,re)=>{const Q=o7(ne),K=ne.color??"#3b82f6";return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsxs("button",{type:"button",onClick:()=>B(ne.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:ne.name}),Q!==null&&i.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:Q?"#22c55e":"#6b7280"},title:Q?"Entry condition met":"Entry condition not met"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[ne.subGroups&&ne.subGroups.length>0&&i.jsx(c7,{subGroups:ne.subGroups,onSelect:P=>{h(!1),n(ne.id,P)}}),i.jsx(ci,{className:"opacity-0 group-hover:opacity-100",onClick:P=>z(ne.id,P)})]})]},ne.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(nT,{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(f2,{isOpen:!!_,onClose:()=>S(null),initialEditId:_}),i.jsx(g2,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function c7({subGroups:e,onSelect:t}){const[n,r]=E.useState(!1),[a,l]=E.useState({top:0,right:0}),u=E.useRef(null),c=E.useRef(null);Jd(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(a7,{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 u7({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(rc,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function d7({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(V1,{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 JS({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(d7,{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 h7(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 fp(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function f7({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:j}){const N=h7(a),T=p.filter(O=>!(r&&O.topLevelOnly)),D=(O,M)=>{const W=new Map(N),U=W.get(O)||new Set,R=new Set(U);R.has(M)?R.delete(M):R.add(M),R.size===0?W.set(O,new Set):W.set(O,R),C(fp(W))},L=O=>{const M=new Map(N);M.has(O)?M.delete(O):M.set(O,new Set),C(fp(M))};return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3",children:[c&&i.jsx(eo,{message:c}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:h}),i.jsx(Cr,{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(Cr,{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:O=>!h&&_(O.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(O=>{const M=N.has(O.name),W=O.actions.length>0,U=N.get(O.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:O.name}),i.jsx("span",{className:"text-[10px]",children:"*"})]},O.name):i.jsx(nc,{trigger:i.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[i.jsx("span",{children:O.name}),W&&i.jsx("span",{className:`text-[10px] ${M&&U.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...O.actions.map(R=>({label:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${O.name}-${R}`,children:[i.jsx("input",{type:"checkbox",id:`${O.name}-${R}`,checked:U.has(R),onChange:()=>D(O.name,R),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),i.jsx("span",{children:R})]}),closeOnClick:!1})),{label:M?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(M)L(O.name);else{const R=new Map(N);R.set(O.name,new Set(O.actions)),C(fp(R))}}}]},O.name):i.jsx("button",{onClick:()=>!h&&L(O.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"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:O.name})},O.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:O=>!h&&S(O.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(NT,{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:j,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 m7(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function p7({isOpen:e,onClose:t,initialEditId:n}){const r=xt(ae=>ae.defaults),a=xt(ae=>ae.userItems),l=xt(ae=>ae.projectItems),u=xt(ae=>ae.loading),c=xt(ae=>ae.fetchAgents),d=xt(ae=>ae.fetchAgent),h=xt(ae=>ae.fetchDefaultContent),p=xt(ae=>ae.createAgent),m=xt(ae=>ae.updateAgent),x=xt(ae=>ae.deleteAgent),[y,w]=E.useState("list"),[C,_]=E.useState(null),[S,v]=E.useState(!1),[b,j]=E.useState(""),[N,T]=E.useState(""),[D,L]=E.useState(""),[O,M]=E.useState(!0),[W,U]=E.useState([]),[R,H]=E.useState("#6b7280"),[G,V]=E.useState(""),[Z,X]=E.useState("user"),[$,I]=E.useState(""),[B,q]=E.useState(!1),[z,ne]=E.useState([]),[re,Q]=E.useState(new Set),{requestDelete:K,clearConfirm:P,isConfirming:J}=Yl(),ie=ae=>{j(ae.metadata.name),T(ae.metadata.id),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I("")},he=(ae,se,me)=>{j(ae.metadata.name+" (copy)"),T(`${se}-copy-${Date.now()}`),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I(""),_(null),v(!1),w("edit")},ce=(ae,se)=>{ie(ae),_(se),v(!0),w("edit")};E.useEffect(()=>{e&&(c(),ve("/api/tools").then(ae=>ae.json()).then(ae=>{const se=ae.tools||[];Q(new Set(se.filter(me=>me.alwaysAllowed).map(me=>me.name))),ne(se.filter(me=>!me.alwaysAllowed))}).catch(()=>{ne([]),Q(new Set)}),n?r.some(se=>se.id===n)?h(n).then(se=>{se&&he(se,n)}):d(n).then(se=>{se&&(ie(se),_(n),v(!1),w("edit"))}):(w("list"),_(null),v(!1)))},[e,c,d,h,n]);const De=async ae=>{if(r.some(me=>me.id===ae)){const me=await h(ae);if(!me)return;ce(me,ae)}else{const me=await d(ae);if(!me)return;ce(me,ae)}},Re=async ae=>{let se=await h(ae);se||(se=await d(ae)),se&&he(se,ae)},ze=()=>{_(null),j(""),T(""),L(""),M(!0),U(["read_file"]),H("#6b7280"),V(""),X("user"),I(""),v(!1),w("edit")},Fe=async ae=>{const se=await d(ae);se&&(ie(se),_(ae),v(!1),w("edit"))},Ee=async ae=>{await x(ae)},st=async()=>{const ae=C??N;if(!ae||!b||!G){I("Name and prompt are required.");return}q(!0),I("");const se={metadata:{id:ae,name:b,description:D,subagent:O,allowedTools:W.filter(Ue=>!re.has(Ue)),color:R},prompt:G},me=C?await m(C,se):await p(se,Z);if(q(!1),!me.success){I(me.error??"Failed to save agent.");return}n?t():w("list")},ot=()=>{n?t():(w("list"),v(!1))},je=ae=>{j(ae),C||T(m7(ae))},Me=r.filter(ae=>ae.subagent),lt=r.filter(ae=>!ae.subagent),we=a.filter(ae=>ae.subagent),Ie=a.filter(ae=>!ae.subagent),qe=l.filter(ae=>ae.subagent),te=l.filter(ae=>!ae.subagent);return y==="edit"?i.jsxs(jt,{isOpen:e,onClose:ot,title:S?`${b}`:C?"Edit Agent":"New Agent",size:"xl",children:[!C&&!S&&i.jsx(Nd,{value:Z,onChange:X}),i.jsx(f7,{formName:b,formId:N,formDescription:D,formSubagent:O,formTools:W,formColor:R,formPrompt:G,formError:$,saving:B,isReadOnly:S,availableTools:z,onNameChange:je,onIdChange:T,onDescriptionChange:L,onSubagentChange:ae=>{M(ae),ae&&U(se=>se.filter(me=>{var Ue;return!((Ue=z.find(He=>He.name===me))!=null&&Ue.topLevelOnly)}))},onToolsChange:U,onColorChange:H,onPromptChange:V,onSave:st,onCancel:ot,onDuplicate:()=>{j(b+" (copy)"),T(`${C}-copy-${Date.now()}`),_(null),v(!1)}})]}):i.jsx(jt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:i.jsx(I1,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ze,loading:u,hasItems:r.length>0||a.length>0||l.length>0,children:i.jsxs("div",{className:"space-y-4",children:[r.length>0&&i.jsx(JS,{title:"Built-in",agents:lt,subagents:Me,isBuiltIn:!0,alwaysAllowedNames:re,onView:De,onDuplicate:Re}),[{title:"Custom",agents:Ie,subagents:we},{title:"Project",agents:te,subagents:qe}].map(ae=>ae.agents.length>0&&i.jsx(JS,{title:ae.title,agents:ae.agents,subagents:ae.subagents,isBuiltIn:!1,alwaysAllowedNames:re,isConfirmingDelete:se=>J(se,"delete"),onView:De,onDuplicate:Re,onEdit:Fe,onDelete:se=>{J(se,"delete")?(Ee(se),P()):K(se)},onCancelDelete:P},ae.title))]})})})}function g7(){const e=Le(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=Le(v=>v.switchMode),n=xt(v=>v.defaults),r=xt(v=>v.userItems),a=xt(v=>v.fetchAgents),l=[...n,...r],[u,c]=E.useState(!1),[d,h]=E.useState(!1),[p,m]=E.useState(null),x=E.useRef(null);E.useEffect(()=>{a()},[a]),Jd(x,()=>c(!1));const y=Kl();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=Vl(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(hn,{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 j=v.id===e,N=Vl(l,v.id),T=y.agentSwitching[b],D=T?Xu(T):null;return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${j?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[i.jsxs("button",{type:"button",onClick:()=>{j||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:N},children:v.name}),j&&i.jsx(Mr,{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(p7,{isOpen:d,onClose:()=>{h(!1),m(null)},initialEditId:p})]})}function x7(){const e=Le(r=>r.currentSession),t=Le(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 ZS({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 y7=[8080,11434,8e3,1234];function eg(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function _2(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 b7({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,j,N,T,D,L,O,M,W,U,R,H,G,V,Z,X,$,I,B,q,z,ne,re,Q,K,P,J,ie,he,ce,De,Re,ze,Fe;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:Ee=>a(e.id,{contextWindow:parseInt(Ee.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:Ee=>a(e.id,{supportsVision:Ee.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:(j=r[e.id+"-non-thinking"])==null?void 0:j.error,children:"Fail"}),((N=r[e.id+"-non-thinking"])==null?void 0:N.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(hn,{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:Ee=>a(e.id,{thinkingEnabled:Ee.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:((O=t[e.id])==null?void 0:O.thinkingLevel)??eg(e.reasoningEfforts),onChange:Ee=>a(e.id,{thinkingLevel:Ee.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(Ee=>i.jsx("option",{value:Ee,children:Ee},Ee))}):i.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((M=t[e.id])==null?void 0:M.thinkingLevel)??"",onChange:Ee=>a(e.id,{thinkingLevel:Ee.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsx(ZS,{value:(W=t[e.id])==null?void 0:W.thinkingQueryParams,onChange:Ee=>a(e.id,{thinkingQueryParams:Ee})})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((U=t[e.id])==null?void 0:U.nonThinkingEnabled)??!1,onChange:Ee=>a(e.id,{nonThinkingEnabled:Ee.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(ZS,{value:(H=t[e.id])==null?void 0:H.nonThinkingQueryParams,onChange:Ee=>a(e.id,{nonThinkingQueryParams:Ee})})})]}),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:((G=t[e.id])==null?void 0:G.temperature)??"",onChange:Ee=>a(e.id,{temperature:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((Z=(V=t[e.id])==null?void 0:V.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:((I=t[e.id])==null?void 0:I.topP)??"",onChange:Ee=>a(e.id,{topP:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((q=(B=t[e.id])==null?void 0:B.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: ",(ne=t[e.id])==null?void 0:ne.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:((re=t[e.id])==null?void 0:re.topK)??"",onChange:Ee=>a(e.id,{topK:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((K=(Q=t[e.id])==null?void 0:Q.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"}),((P=t[e.id])==null?void 0:P.defaultTopK)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(J=t[e.id])==null?void 0:J.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:((ie=t[e.id])==null?void 0:ie.maxTokens)??"",onChange:Ee=>a(e.id,{maxTokens:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((ce=(he=t[e.id])==null?void 0:he.defaultMaxTokens)==null?void 0:ce.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((De=t[e.id])==null?void 0:De.defaultMaxTokens)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Re=t[e.id])==null?void 0:Re.defaultMaxTokens]})]})]})]}),i.jsx("div",{className:"pt-3 border-t border-border",children:i.jsx(v7,{value:(ze=t[e.id])==null?void 0:ze.compactionThreshold,maxTokens:((Fe=t[e.id])==null?void 0:Fe.contextWindow)??e.contextWindow,onChange:Ee=>a(e.id,{compactionThreshold:Ee})})})]})]})}function v7({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]=E.useState(Math.round(c*100));E.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,"% · ",oo(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 ",oo(15e3)," tokens · maximum ",l,"% · default 85%"]})]})}function S2({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:a,editModelId:l}){const[u,c]=E.useState(r),[d,h]=E.useState(""),[p,m]=E.useState(""),[x,y]=E.useState("unknown"),[w,C]=E.useState(""),[_,S]=E.useState(!1),[v,b]=E.useState(),[j,N]=E.useState(),[T,D]=E.useState(!1),[L,O]=E.useState(null),[M,W]=E.useState([]),[U,R]=E.useState(null),[H,G]=E.useState(!1),[V,Z]=E.useState(""),[X,$]=E.useState({}),[I,B]=E.useState({loading:!1,progress:{}}),[q,z]=E.useState({}),[ne,re]=E.useState(null),[Q,K]=E.useState(new Set),[P,J]=E.useState(""),[ie,he]=E.useState(null),[ce,De]=E.useState("disconnected"),[Re,ze]=E.useState(!1),[Fe,Ee]=E.useState(null),[st,ot]=E.useState([]),[je,Me]=E.useState(!1),[lt,we]=E.useState(!1),Ie=E.useRef(null),qe=E.useRef(!1),te=E.useRef(null);E.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var ye;return(ye=te.current)==null?void 0:ye.focus()})},[u,e]),E.useEffect(()=>()=>{Ie.current!==null&&window.clearTimeout(Ie.current)},[]),E.useEffect(()=>{e&&ve("/api/provider-presets").then(async ye=>ye.ok?await ye.json():{presets:[]}).then(ye=>ot(ye.presets)).catch(()=>ot([]))},[e]);function ae(ye,Ge){$(oe=>({...oe,[ye]:{...oe[ye],...Ge}}))}function se(ye){K(Ge=>new Set(Ge).add(ye.id)),$(Ge=>({...Ge,[ye.id]:{contextWindow:ye.contextWindow,...Ge[ye.id]}}))}function me(ye){if(!ye.trim())return M;const Ge=ye.toLowerCase().split(/\s+/).filter(Boolean);return M.filter(oe=>Ge.every(fe=>oe.id.toLowerCase().includes(fe)))}E.useEffect(()=>{var ye,Ge;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),N(a==null?void 0:a.transportAdapter),O(null),Z((a==null?void 0:a.thinkingField)??""),z({}),re(null),he(null),De("disconnected"),Ee(null),Me(!1),we(!1),(ye=a==null?void 0:a.models)!=null&&ye.length){const oe={},fe=new Set;for(const Pe of a.models)oe[Pe.id]={contextWindow:Pe.contextWindow,supportsVision:Pe.supportsVision,thinkingEnabled:Pe.thinkingEnabled,thinkingLevel:Pe.thinkingLevel??eg(Pe.reasoningEfforts),nonThinkingEnabled:Pe.nonThinkingEnabled,thinkingQueryParams:Pe.thinkingQueryParams,nonThinkingQueryParams:Pe.nonThinkingQueryParams,defaultTemperature:Pe.defaultTemperature,defaultTopP:Pe.defaultTopP,defaultTopK:Pe.defaultTopK,defaultMaxTokens:Pe.defaultMaxTokens,temperature:Pe.temperature,topP:Pe.topP,topK:Pe.topK,maxTokens:Pe.maxTokens,compactionThreshold:Pe.compactionThreshold},Pe.selected&&fe.add(Pe.id);if(fe.size===0)for(const Pe of a.models)fe.add(Pe.id);K(fe),$(oe),W(a.models),R(l??((Ge=a.models[0])==null?void 0:Ge.id)??null)}else W([]),$({}),R(null),K(new Set)},[e,r,a==null?void 0:a.id,l]),E.useEffect(()=>{const ye=!!v;u===2&&p&&M.length===0&&!T&&!L&&(!ye||ce==="connected")&&Ze(p)},[u,ce]),E.useEffect(()=>{!e||!v||!(a!=null&&a.id)||He(a.id)},[e,j,a==null?void 0:a.id]),E.useEffect(()=>{if(!Fe)return;const ye=(a==null?void 0:a.id)??ie;if(!ye)return;let Ge=!1;const oe=async()=>{const Pe=await He(ye);Ge||Pe!=="connected"||(Ee(null),Me(!1),we(!1),await Ze(p))};oe();const fe=window.setInterval(()=>void oe(),2e3);return()=>{Ge=!0,window.clearInterval(fe)}},[Fe,ie,a==null?void 0:a.id]);async function Ue(){if(a!=null&&a.id)return a.id;if(ie)return ie;const ye=await ve("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d||"Provider",url:p,backend:x,authAdapter:v,transportAdapter:j,isLocal:!1,models:[]})});if(!ye.ok)throw new Error("Unable to create provider");const Ge=await ye.json();return he(Ge.provider.id),Ge.provider.id}async function He(ye){const Ge=await ve(`/api/provider-auth/${ye}/status`);if(!Ge.ok)return"error";const oe=await Ge.json(),fe=oe.state==="connected"?"connected":oe.state==="pending"?"pending":oe.state==="error"?"error":"disconnected";return De(fe),fe}async function Ye(){ze(!0),De("pending");try{const ye=await Ue(),Ge=await ve(`/api/provider-auth/${ye}/login`,{method:"POST"});if(!Ge.ok)throw new Error("Unable to start provider sign-in");const oe=await Ge.json();Ee(oe)}catch{De("error")}finally{ze(!1)}}async function ct(){var ye;Fe!=null&&Fe.userCode&&(await((ye=navigator.clipboard)==null?void 0:ye.writeText(Fe.userCode)),Ie.current!==null&&window.clearTimeout(Ie.current),we(!1),requestAnimationFrame(()=>we(!0)),Ie.current=window.setTimeout(()=>{we(!1),Ie.current=null},1500))}function Je(){Fe&&(window.open(Fe.directUrl??Fe.verificationUrl,"_blank","noopener,noreferrer"),Me(!0))}async function Ze(ye){var Ge,oe;D(!0),O(null),W([]);try{const fe=new URLSearchParams({url:ye});w&&fe.set("apiKey",w),x&&fe.set("backend",x);const Pe=j?await ve(`/api/providers/${await Ue()}/models`):await ve(`/api/providers/models?${fe.toString()}`);if(Pe.ok){const St=await Pe.json();if((Ge=St.models)!=null&&Ge.length){W(St.models),R(((oe=St.models[0])==null?void 0:oe.id)??null);const bn={};for(const fn of St.models)bn[fn.id]={contextWindow:fn.contextWindow,thinkingEnabled:!0,thinkingLevel:eg(fn.reasoningEfforts),defaultTemperature:fn.defaultTemperature,defaultTopP:fn.defaultTopP,defaultTopK:fn.defaultTopK,defaultMaxTokens:fn.defaultMaxTokens};$(bn),St.models.length===1&&(K(new Set([St.models[0].id])),R(St.models[0].id),tt(St.models[0].id))}}else{const St=await Pe.json();O(St.error??`Failed to fetch models from ${ye}`)}}catch(fe){O(`Failed to fetch models from ${ye}: ${fe instanceof Error?fe.message:"Unknown error"}`)}D(!1)}async function tt(ye){B(Ge=>({loading:!0,progress:{...Ge.progress,[ye]:"probing"}}));try{const Ge=await ve("/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:ye}]})});if(!Ge.ok){const fe=await Ge.json();throw new Error(fe.error??"Auto-config failed")}const oe=await Ge.json();for(const fe of oe.models){const Pe={};fe.contextSource!=="default"&&(Pe.contextWindow=fe.contextWindow,Pe.supportsVision=fe.supportsVision),fe.thinkingConfig&&(Pe.thinkingEnabled=!0,Pe.thinkingQueryParams=JSON.stringify(fe.thinkingConfig)),fe.nonThinkingConfig&&(Pe.nonThinkingEnabled=!0,Pe.nonThinkingQueryParams=JSON.stringify(fe.nonThinkingConfig)),ae(fe.id,Pe),B(St=>({...St,progress:{...St.progress,[fe.id]:"done"}}))}}catch(Ge){console.error("Auto-config error:",Ge),B(oe=>({...oe,progress:{...oe.progress,[ye]:"error"}}))}finally{B(Ge=>({...Ge,loading:!1}))}}async function Nt(ye,Ge){const oe=ye+"-"+Ge;z(fe=>({...fe,[oe]:{loading:!0}}));try{const fe=X[ye],Pe=await ve("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,providerId:(a==null?void 0:a.id)??ie??void 0,transportAdapter:j,model:ye,apiKey:w||void 0,backend:x||"unknown",thinkingField:V||void 0,mode:Ge,modelConfig:{temperature:fe==null?void 0:fe.temperature,topP:fe==null?void 0:fe.topP,topK:fe==null?void 0:fe.topK,maxTokens:fe==null?void 0:fe.maxTokens,supportsVision:fe==null?void 0:fe.supportsVision,thinkingEnabled:fe==null?void 0:fe.thinkingEnabled,thinkingLevel:fe==null?void 0:fe.thinkingLevel,nonThinkingEnabled:fe==null?void 0:fe.nonThinkingEnabled,thinkingQueryParams:fe==null?void 0:fe.thinkingQueryParams,nonThinkingQueryParams:fe==null?void 0:fe.nonThinkingQueryParams}})}),St=await Pe.json();Pe.ok?z(bn=>({...bn,[oe]:{loading:!1,result:JSON.stringify(St,null,2),message:St.message}})):z(bn=>({...bn,[oe]:{loading:!1,error:St.error??"Test failed"}}))}catch(fe){z(Pe=>({...Pe,[oe]:{loading:!1,error:fe instanceof Error?fe.message:"Request failed"}}))}}function dt(){W([]),$({}),B({loading:!1,progress:{}}),z({}),re(null),K(new Set),J("")}function rn(){ie&&!qe.current&&ve(`/api/providers/${ie}`,{method:"DELETE"}).catch(ye=>{console.warn("Failed to clean up draft provider",ye)}),t()}function Un(){const ye=d||"Provider",Ge=(a==null?void 0:a.id)??ie??`temp-${Date.now()}`;n({id:Ge,name:ye,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:_,thinkingField:V||void 0,authAdapter:v,transportAdapter:j,models:M.map(oe=>{var fe,Pe,St,bn,fn,Pr,Ns,xi,Ts,As,Se,Ce,Oe,We,Ve,Qe;return{id:oe.id,name:oe.name,apiModelId:oe.apiModelId,requestBody:oe.requestBody,reasoningEfforts:oe.reasoningEfforts,contextWindow:((fe=X[oe.id])==null?void 0:fe.contextWindow)??oe.contextWindow,selected:Q.has(oe.id)||void 0,supportsVision:(Pe=X[oe.id])==null?void 0:Pe.supportsVision,thinkingEnabled:(St=X[oe.id])==null?void 0:St.thinkingEnabled,thinkingLevel:(bn=X[oe.id])==null?void 0:bn.thinkingLevel,nonThinkingEnabled:(fn=X[oe.id])==null?void 0:fn.nonThinkingEnabled,thinkingQueryParams:(Pr=X[oe.id])==null?void 0:Pr.thinkingQueryParams,nonThinkingQueryParams:(Ns=X[oe.id])==null?void 0:Ns.nonThinkingQueryParams,temperature:(xi=X[oe.id])==null?void 0:xi.temperature,topP:(Ts=X[oe.id])==null?void 0:Ts.topP,topK:(As=X[oe.id])==null?void 0:As.topK,maxTokens:(Se=X[oe.id])==null?void 0:Se.maxTokens,defaultMaxTokens:(Ce=X[oe.id])==null?void 0:Ce.defaultMaxTokens,defaultTemperature:(Oe=X[oe.id])==null?void 0:Oe.defaultTemperature,defaultTopP:(We=X[oe.id])==null?void 0:We.defaultTopP,defaultTopK:(Ve=X[oe.id])==null?void 0:Ve.defaultTopK,compactionThreshold:(Qe=X[oe.id])==null?void 0:Qe.compactionThreshold}})}),qe.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:rn,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(ye=>i.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${ye<u?"bg-accent-success":ye===u?"bg-accent-primary":"bg-border"}`},ye))}),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:[st.map(ye=>i.jsx("button",{type:"button",onClick:()=>{h(ye.defaults.name??ye.name),m(ye.defaults.url),y(ye.defaults.backend),S(!1),C(""),b(ye.authAdapter),N(ye.transportAdapter),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${j&&j===ye.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ye.name},ye.id)),i.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),b(void 0),N(void 0),O(null),dt()},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"),y7.map(ye=>{const Ge={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},oe={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return i.jsx("button",{type:"button",onClick:()=>{h(fe=>fe||(oe[ye]??"")),m(fe=>fe||`http://localhost:${ye}`),y(Ge[ye]??""),S(!0),b(void 0),N(void 0),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${x===Ge[ye]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:oe[ye]??`localhost:${ye}`},ye)})]})]}),!v&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),i.jsx("input",{ref:te,type:"text",value:p,"data-testid":"provider-modal-url",onChange:ye=>{m(ye.target.value),O(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:ye=>h(ye.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:ye=>C(ye.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:ye=>S(ye.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."})]}),ce==="connected"?i.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):i.jsx("button",{type:"button",onClick:()=>void Ye(),disabled:Re||ce==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:Re||ce==="pending"?"Connecting...":ce==="error"?"Retry":"Connect"})]}),Fe&&i.jsx("div",{className:"mt-4 border-t border-border pt-4",children:Fe.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 ct(),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:Fe.userCode??"Continue"}),i.jsxs("div",{className:"mt-3 flex gap-2",children:[i.jsx("button",{type:"button",onClick:()=>void ct(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:lt?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:Je,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"Reopen authorization":"Open authorization"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted mb-3",children:Fe.instructions}),i.jsx("button",{type:"button",onClick:Je,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"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:()=>Ze(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),i.jsx("button",{onClick:()=>{dt(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),M.length>0&&x&&(!v||ce==="connected")&&i.jsxs(i.Fragment,{children:[Q.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 (",Q.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:M.filter(ye=>Q.has(ye.id)).map(ye=>{var Ge;return i.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[i.jsxs("div",{onClick:()=>R(U===ye.id?null:ye.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:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((Ge=X[ye.id])==null?void 0:Ge.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[I.progress[ye.id]==="probing"?i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):I.progress[ye.id]==="done"?i.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):I.progress[ye.id]==="error"?i.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):v?null:i.jsx("button",{onClick:oe=>{oe.stopPropagation(),tt(ye.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),M.length>1&&i.jsx("button",{onClick:oe=>{oe.stopPropagation();const fe=new Set(Q);fe.delete(ye.id),K(fe),U===ye.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(hn,{className:`w-4 h-4 text-text-muted transition-transform ${U===ye.id?"rotate-180":""}`})]})]}),U===ye.id&&i.jsx(b7,{model:ye,modelConfigs:X,autoConfigState:I,testResults:q,onUpdateConfig:ae,onRunAutoConfig:tt,onTestParams:Nt,onShowRaw:re})]},ye.id)})})]}),M.length>1&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),Q.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:P,onChange:ye=>J(ye.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"}),P&&i.jsx("button",{onClick:()=>J(""),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 ",me(P).length," of ",M.length," models"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{const ye=new Set(Q),Ge=me(P);for(const oe of Ge)ye.add(oe.id);if(K(ye),$(oe=>{const fe={...oe};for(const Pe of Ge)fe[Pe.id]={contextWindow:Pe.contextWindow,...fe[Pe.id]};return fe}),!v)for(const oe of Ge)I.progress[oe.id]!=="probing"&&I.progress[oe.id]!=="done"&&tt(oe.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),i.jsx("button",{onClick:()=>{const ye=new Set(Q),Ge=me(P);for(const oe of Ge)ye.delete(oe.id);K(ye)},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:[me(P).map(ye=>{var oe;const Ge=Q.has(ye.id);return i.jsxs("div",{role:"checkbox","aria-checked":Ge,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${Ge?"bg-accent-primary/5":""}`,onClick:()=>{if(Ge){const fe=new Set(Q);fe.delete(ye.id),K(fe)}else se(ye),v||tt(ye.id)},onKeyDown:fe=>{(fe.key==="Enter"||fe.key===" ")&&(fe.preventDefault(),fe.currentTarget.click())},children:[i.jsx("input",{type:"checkbox",checked:Ge,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:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((oe=X[ye.id])==null?void 0:oe.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]}),I.progress[ye.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"}),I.progress[ye.id]==="done"&&i.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),I.progress[ye.id]==="error"&&i.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},ye.id)}),me(P).length===0&&i.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",P,"”"]})]})]})]})]}),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&&dt(),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:rn,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:Un,disabled:I.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:I.loading?"Configuring...":"Save Provider"})]})]})]}),H&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&G(!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:()=>G(!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:V,onChange:ye=>Z(ye.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:()=>G(!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"})})]})}),ne&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&re(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:()=>re(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:ne})]})})]}):null}function _7(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function S7(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 e1({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 w7({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:_7(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(L1,{className:"w-3.5 h-3.5 text-accent-warning"}):i.jsx(D1,{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(j1,{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(Mr,{className:"w-3.5 h-3.5"})})]})]})}function C7(){var Ge;const[,e]=Tn(),t=Le(oe=>oe.currentSession),n=Le(oe=>oe.setSessionProvider),[r,a]=E.useState(!1),[l,u]=E.useState([]),[c,d]=E.useState(null),h=E.useRef(null),[p,m]=E.useState(null),[x,y]=E.useState(!1),[w,C]=E.useState({}),[_,S]=E.useState(null),[v,b]=E.useState(null),[j,N]=E.useState(!1),T=E.useRef(null),[D,L]=E.useState(!1),O=E.useRef(new Set),[M,W]=E.useState(-1),U=E.useRef(null),R=Xt(oe=>oe.providers),H=Xt(oe=>oe.activeProviderId),G=Xt(oe=>oe.defaultModelSelection),V=Xt(oe=>oe.activating),Z=Xt(oe=>oe.activateProvider),X=Xt(oe=>oe.refreshModel),$=Xt(oe=>oe.refreshProviderModels),I=Xt(oe=>oe.setDefaultModel),B=Xt(oe=>oe.fetchConfig),q=Kl();Ol(q.modelSelector,()=>a(oe=>!oe));const z=(t==null?void 0:t.providerId)??null,ne=(t==null?void 0:t.providerModel)??null,re=(G==null?void 0:G.split("/")[0])??null,Q=(G==null?void 0:G.split("/").slice(1).join("/"))??null,K=z??re,P=ne??Q,J=P?((Ge=P.split("/").pop())==null?void 0:Ge.replace(/-/g," "))??P:"No model",[ie,he]=E.useState(!1),[ce,De]=E.useState(""),Re=E.useRef(null);E.useEffect(()=>{function oe(fe){h.current&&!h.current.contains(fe.target)&&(a(!1),u([]),O.current=new Set)}return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]),E.useEffect(()=>()=>{T.current!==null&&window.clearTimeout(T.current)},[]),E.useEffect(()=>{r||(De(""),W(-1))},[r]),E.useEffect(()=>{var oe;r&&((oe=Re.current)==null||oe.focus())},[r]),E.useEffect(()=>{M>=0&&U.current&&U.current.scrollIntoView({block:"nearest"})},[M]),E.useEffect(()=>{if(r){const oe=R.map(fe=>fe.id);u(oe),R.filter(fe=>!!fe.authAdapter).forEach(fe=>void Ie(fe.id)),oe.forEach(fe=>{O.current.has(fe)||(O.current.add(fe),ot(fe))})}},[r,R]),E.useEffect(()=>{if(!v)return;let oe=!1;const fe=async()=>{const St=await Ie(v.providerId);oe||St==="connected"&&(b(null),N(!1),L(!1),await B(),O.current.delete(v.providerId),await ot(v.providerId))};fe();const Pe=window.setInterval(()=>void fe(),2e3);return()=>{oe=!0,window.clearInterval(Pe)}},[v]);const ze=R.find(oe=>oe.id===K),Fe=(ze==null?void 0:ze.status)==="disconnected",Ee=(oe,fe)=>t?t.providerId===oe&&t.providerModel===fe:!1,st=(oe,fe)=>G?G===`${oe}/${fe}`:!1,ot=async oe=>{d(oe);try{await $(oe)}catch{}finally{d(null)}},je=oe=>{l.includes(oe.id)?u(l.filter(fe=>fe!==oe.id)):(u([...l,oe.id]),ot(oe.id))},Me=async oe=>{if(oe.id===H){je(oe);return}t?(n(oe.id,void 0),a(!1),u([])):await Z(oe.id)&&(a(!1),u([]))},lt=oe=>{je(oe)},we=async(oe,fe)=>{oe.stopPropagation(),O.current.delete(fe),await ot(fe)},Ie=async oe=>{const fe=await ve(`/api/provider-auth/${oe}/status`);if(!fe.ok)return"error";const Pe=await fe.json();return C(St=>({...St,[oe]:Pe.state})),Pe.state},qe=async(oe,fe)=>{oe.stopPropagation(),S(fe),C(Pe=>({...Pe,[fe]:"pending"})),N(!1),L(!1);try{const Pe=await ve(`/api/provider-auth/${fe}/login`,{method:"POST"});if(!Pe.ok)throw new Error("Unable to start provider sign-in");const St=await Pe.json();b({providerId:fe,...St})}catch{C(Pe=>({...Pe,[fe]:"error"}))}finally{S(null)}},te=async()=>{var oe;v!=null&&v.userCode&&(await((oe=navigator.clipboard)==null?void 0:oe.writeText(v.userCode)),T.current!==null&&window.clearTimeout(T.current),N(!1),requestAnimationFrame(()=>N(!0)),T.current=window.setTimeout(()=>{N(!1),T.current=null},1500))},ae=()=>{v&&(window.open(v.directUrl??v.verificationUrl,"_blank","noopener,noreferrer"),L(!0))},se=()=>{b(null),N(!1),L(!1)},me=async(oe,fe)=>{oe.stopPropagation(),S(fe);try{if(!(await ve(`/api/provider-auth/${fe}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");C(St=>({...St,[fe]:"disconnected"})),await B()}finally{S(null)}},Ue=(oe,fe)=>{m({providerId:oe,model:fe}),y(!0)},He=p?R.find(oe=>oe.id===p.providerId):void 0,Ye=()=>{m(null),y(!1)},ct=async oe=>{try{if(!(await ve(`/api/providers/${oe.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(_2(oe))})).ok)throw new Error("Failed to update provider");await Xt.getState().fetchConfig()}catch{}m(null),y(!1)},Je=async(oe,fe)=>{if(t){Le.setState(St=>({currentSession:St.currentSession?{...St.currentSession,providerId:oe,providerModel:fe}:null})),n(oe,fe),u([]),a(!1),Gl();return}await Z(oe)&&(u([]),a(!1),Gl())},Ze=async(oe,fe,Pe)=>{oe.stopPropagation(),he(!0);try{await I(fe,Pe)}catch{}finally{he(!1)}};function tt(oe){return oe.models.some(Pe=>Pe.selected)?oe.models.filter(Pe=>Pe.selected):oe.models}const Nt=E.useMemo(()=>ce.trim()?R.map(oe=>({provider:oe,models:tt(oe).filter(fe=>S7(fe,ce))})).filter(oe=>oe.models.length>0):R.map(oe=>({provider:oe,models:tt(oe)})),[R,ce]),dt=E.useMemo(()=>Nt.flatMap(oe=>oe.models.map(fe=>({providerId:oe.provider.id,modelConfig:fe}))),[Nt]),rn=dt.length+1,Un=M===dt.length;E.useEffect(()=>{rn===1?W(-1):M>=rn?W(rn-1):M<0&&ce.trim()&&W(0)},[rn,M,ce]);const ye=oe=>{switch(oe.key){case"Escape":a(!1);break;case"ArrowDown":oe.preventDefault(),rn>0&&W(fe=>fe<rn-1?fe+1:0);break;case"ArrowUp":oe.preventDefault(),rn>0&&W(fe=>fe>0?fe-1:rn-1);break;case"Home":oe.preventDefault(),W(0);break;case"End":oe.preventDefault(),W(rn-1);break;case"Enter":if(oe.preventDefault(),M===dt.length)e("/onboarding"),a(!1);else if(M>=0&&M<dt.length){const fe=dt[M];fe&&Je(fe.providerId,fe.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:Fe?"LLM server is offline. Click to retry.":J??"Click to refresh model",children:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):i.jsx(e1,{activeProvider:ze,shortModelName:J}),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:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):i.jsx(e1,{activeProvider:ze,shortModelName:J}),i.jsx(hn,{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(Xi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("input",{ref:Re,type:"text",value:ce,onInput:oe=>{De(oe.currentTarget.value),W(-1)},onKeyDown:ye,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:[Nt.map(oe=>{const fe=ce.trim().length>0||l.includes(oe.provider.id);return i.jsxs("div",{children:[i.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${oe.provider.id===K?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${V?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[i.jsxs("div",{onClick:()=>!V&&Me(oe.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[i.jsx("span",{className:`text-sm font-medium truncate ${oe.provider.id===K?"text-accent-primary":"text-text-primary"}`,children:oe.provider.name}),i.jsx("span",{className:"text-xs text-text-muted truncate",children:oe.provider.backend!=="unknown"&&g1(oe.provider.backend)})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!oe.provider.authAdapter&&(w[oe.provider.id]==="connected"||oe.provider.credentialRef?i.jsx("button",{type:"button",onClick:Pe=>me(Pe,oe.provider.id),disabled:_===oe.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:Pe=>qe(Pe,oe.provider.id),disabled:_===oe.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:_===oe.provider.id?"Starting…":w[oe.provider.id]==="error"||w[oe.provider.id]==="expired"?"Retry":"Connect"})),oe.provider.id===K?i.jsx("span",{className:"text-accent-success",title:"Active provider",children:i.jsx(Mr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-4"}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),we(Pe,oe.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:i.jsx(jd,{className:`w-4 h-4 ${c===oe.provider.id?"animate-spin":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),lt(oe.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:i.jsx(hn,{className:`w-4 h-4 transition-transform ${fe?"rotate-180":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})})]})]}),fe&&i.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===oe.provider.id?i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):oe.models.length>0?oe.models.map(Pe=>{const bn=dt.findIndex(fn=>fn.providerId===oe.provider.id&&fn.modelConfig.id===Pe.id)===M;return i.jsx("div",{ref:bn?U:void 0,children:i.jsx(w7,{providerId:oe.provider.id,modelConfig:Pe,isActive:Ee(oe.provider.id,Pe.id),isDefault:st(oe.provider.id,Pe.id),disabled:c==="activating",hasSession:!!t,settingDefault:ie,highlighted:bn,onModelClick:Je,onSetDefault:Ze,onEditModel:Ue})},`${oe.provider.id}/${Pe.id}`)}):i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},oe.provider.id)}),Nt.length===0&&ce.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 ${Un?"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:oe=>{oe.target===oe.currentTarget&&se()},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:se,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:te,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:j?"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:te,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:j?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:ae,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:ae,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(S2,{isOpen:!0,onClose:Ye,onSave:ct,initialStep:2,editProvider:{id:p.providerId,name:(He==null?void 0:He.name)??"",url:(He==null?void 0:He.url)??"",backend:(He==null?void 0:He.backend)??"unknown",apiKey:He==null?void 0:He.apiKey,isLocal:He==null?void 0:He.isLocal,thinkingField:He==null?void 0:He.thinkingField,authAdapter:He==null?void 0:He.authAdapter,transportAdapter:He==null?void 0:He.transportAdapter,models:He==null?void 0:He.models},editModelId:p.model.id})]})}function k7(){const e=Dl(j=>j.servers),t=Dl(j=>j.fetchServers),n=Le(j=>j.currentSession),r=n==null?void 0:n.id,[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(new Set),[p,m]=E.useState(new Set),x=E.useRef(null),y=E.useCallback(async()=>{if(r)try{const j=await ve(`/api/sessions/${r}/mcp/overrides`);if(j.ok){const N=await j.json();m(new Set(N.disabledServers??[]))}}catch{}},[r]),w=E.useCallback(async()=>{await t(),await y()},[t,y]);E.useEffect(()=>{const j=()=>w();return window.addEventListener("mcp-servers-changed",j),()=>window.removeEventListener("mcp-servers-changed",j)},[w]),E.useEffect(()=>{y()},[y]),E.useEffect(()=>{a&&y()},[a,y]),Jd(x,()=>l(!1));const C=j=>p.has(j.name),_=e.filter(j=>j.status==="connected"&&!C(j)),S=_.length,v=_.reduce((j,N)=>j+N.estimatedTokens,0),b=async(j,N)=>{if(r){c(null),h(T=>new Set(T).add(j));try{const T=new Set(p);N?T.add(j):T.delete(j);const D=await ve(`/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(j),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 (${md(v)})`:"MCP"}),i.jsx(hn,{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(j=>{const N=C(j),T=d.has(j.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 ${qg(N?"disabled":j.status)}`,children:Kg(N?"disabled":j.status)}),i.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:j.name})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[i.jsxs("span",{children:[j.tools.length," tools"]}),j.estimatedTokens>0&&i.jsxs("span",{children:[md(j.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(Kr,{enabled:!N,onClick:()=>b(j.name,!N)})]})]})},j.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 j7(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
- `)||a.includes(" ")?null:{query:a,startIndex:r}}const E7=E.forwardRef(function({text:t,cursorPos:n,workdir:r,onSelect:a},l){const u=j7(t,n),[c,d]=E.useState([]),[h,p]=E.useState(!1),[m,x]=E.useState(0),y=E.useRef(null),w=E.useRef([]),C=E.useRef(0),_=E.useRef([]);E.useEffect(()=>{C.current=m},[m]),E.useEffect(()=>{_.current=c},[c]),E.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 j=new URLSearchParams({q:b});r&&j.set("workdir",r);const T=await(await ve(`/api/files?${j.toString()}`)).json();d(T),x(0),C.current=0}catch(j){console.error("File search failed:",j),d([])}finally{p(!1)}},v=E.useCallback(b=>{if(!u)return!1;switch(b.key){case"ArrowDown":return b.preventDefault(),x(j=>{var T;const N=Math.min(j+1,_.current.length-1);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.min(C.current+1,_.current.length-1),!0;case"ArrowUp":return b.preventDefault(),x(j=>{var T;const N=Math.max(j-1,0);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.max(C.current-1,0),!0;case"Enter":case"Tab":{const j=_.current;return j[C.current]?(b.preventDefault(),a(j[C.current],u.startIndex),!0):!1}case"Escape":return b.preventDefault(),d([]),!0}return!1},[u,a]);return E.useImperativeHandle(l,()=>({handleKeyDown:v}),[v]),E.useEffect(()=>{if(!u)return;const b=j=>{y.current&&!y.current.contains(j.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(pi,{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",{children:c.map((b,j)=>i.jsxs("li",{ref:N=>{w.current[j]=N},className:`px-3 py-2 cursor-pointer flex items-center gap-2 text-sm ${j===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(Rr,{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 N7(e,t){const n=e.slice(0,t);if(n.length===0||n[0]!=="/")return null;const r=n.slice(1);return r.includes(" ")||r.includes(`
313
- `)||r.includes(" ")?null:{query:r,startIndex:0}}const T7=E.forwardRef(function({text:t,cursorPos:n,workflows:r,commands:a,onSelect:l},u){const c=N7(t,n),[d,h]=E.useState(0),p=E.useRef(null),m=E.useRef([]),x=E.useRef(0),y=E.useRef([]);E.useEffect(()=>{x.current=d},[d]),E.useEffect(()=>{y.current=C});const w=(c==null?void 0:c.query)??"",C=(()=>{if(!c)return[];const S=w.toLowerCase(),v=r.filter(j=>j.id.toLowerCase().includes(S)||j.name.toLowerCase().includes(S)).map(j=>({type:"workflow",id:j.id,name:j.name,paramCount:(j.parameters??[]).length})),b=a.filter(j=>j.id.toLowerCase().includes(S)||j.name.toLowerCase().includes(S)).map(j=>({type:"command",id:j.id,name:j.name,paramCount:0}));return[...v,...b]})();E.useEffect(()=>{h(0),x.current=0},[C.length]);const _=E.useCallback(S=>{if(!c||C.length===0)return!1;switch(S.key){case"ArrowDown":return S.preventDefault(),h(v=>{var j;const b=Math.min(v+1,C.length-1);return(j=m.current[b])==null||j.scrollIntoView({block:"nearest"}),b}),!0;case"ArrowUp":return S.preventDefault(),h(v=>{var j;const b=Math.max(v-1,0);return(j=m.current[b])==null||j.scrollIntoView({block:"nearest"}),b}),!0;case"Enter":case"Tab":{const v=C[x.current];return v?(S.preventDefault(),l(v,c.startIndex),!0):!1}case"Escape":return S.preventDefault(),!0}return!1},[c,C,l]);return E.useImperativeHandle(u,()=>({handleKeyDown:_}),[_]),!c||C.length===0?null:i.jsx("div",{ref:p,className:"absolute bottom-full left-0 right-0 mb-2 z-50",role:"listbox",children:i.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg max-h-64 overflow-y-auto",children:i.jsx("div",{children:C.map((S,v)=>i.jsxs("button",{ref:b=>{m.current[v]=b},role:"option","aria-selected":v===d,className:`w-full text-left px-3 py-2 flex items-center gap-2 text-sm ${v===d?"bg-accent-primary/20 text-text-primary":"text-text-muted hover:bg-bg-tertiary"}`,onClick:()=>{c&&l(S,c.startIndex)},children:[i.jsxs("span",{className:`font-medium ${S.type==="workflow"?"text-accent-primary":"text-accent-warning"}`,children:["/",S.id]}),i.jsx("span",{className:"truncate flex-1",children:S.name}),S.paramCount>0&&i.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary px-1.5 py-0.5 rounded",children:[S.paramCount," param",S.paramCount>1?"s":""]})]},`${S.type}-${S.id}`))})})})});function A7({input:e,setInput:t,attachments:n,setAttachments:r,dragOver:a,setDragOver:l,errorMessage:u,setErrorMessage:c,scrollContainerRef:d,sessionId:h,showHistory:p,history:m,selectedIndex:x,openHistory:y,closeHistory:w,navigateUp:C,navigateDown:_,selectCurrent:S,isAutoScrollActive:v,setAutoScroll:b,onOpenMessageSearch:j,onOpenCommandsModal:N,onOpenWorkflowsModal:T,onSelectWorkflow:D,onSelectWorkflowWithSubGroup:L,onSendCommand:O,clearInput:M}){const W=E.useRef(null),U=E.useRef(null),R=E.useRef(0),H=E.useRef(0),G=E.useRef(null),V=E.useRef(null),Z=kd(),X=Le(se=>se.stopGeneration),$=Le(se=>se.cancelQueued),I=Le(se=>se.queuedMessages),B=Le(se=>se.restoredInput),q=Le(se=>se.clearRestoredInput),z=Le(se=>{var me;return(me=se.currentSession)==null?void 0:me.workdir}),ne=Le(se=>se.currentSession),re=E.useRef(!1),Q=E.useRef(!1),K=E.useRef(!1),[P,J]=E.useState([]),{sendMessage:ie,launchWorkflow:he}=v2(b);E.useEffect(()=>{if(Q.current)return;Q.current=!0;const se=vt.getState();se.defaults.length===0&&se.userItems.length===0&&se.projectItems.length===0&&se.fetchWorkflows();const me=Yt.getState();me.defaults.length===0&&me.userItems.length===0&&me.projectItems.length===0&&me.fetchCommands()},[]),E.useEffect(()=>{e||J([])},[e]),E.useEffect(()=>{var se;B!==null&&(t(B),q(),(se=W.current)==null||se.focus())},[B,t,q]);const ce=E.useCallback(()=>{const se=W.current;if(!se)return;const me=e.length>=R.current;R.current=e.length,me||(se.style.height="auto"),se.style.height=`${Math.min(200,se.scrollHeight)}px`},[e]);E.useEffect(()=>{if(!h)return;const se=`openfox:draft:${h}`,me=localStorage.getItem(se);me!==null&&t(me)},[h,t]),E.useEffect(()=>{var se;(se=W.current)==null||se.focus(),ce()},[h,ce]),E.useEffect(()=>{if(!h)return;const se=`openfox:draft:${h}`,me=setTimeout(()=>{e?localStorage.setItem(se,e):localStorage.removeItem(se)},500);return()=>clearTimeout(me)},[h,e]),E.useEffect(()=>{ce()},[e,ce]),E.useEffect(()=>{const se=W.current;if(!se)return;const me=async Ue=>{var ct;if(document.activeElement!==se)return;const He=(ct=Ue.clipboardData)==null?void 0:ct.items;if(!He)return;const Ye=[];for(const Je of Array.from(He)){let Ze=Je.getAsFile();if(Ze&&l$(Ze.type)){if(Ue.preventDefault(),!Ze.name){const tt=o$(Ze.type);Ze=new File([Ze],`pasted-file.${tt}`,{type:Ze.type})}await QS(Ze,tt=>Ye.push(tt),c)}}Ye.length>0&&r(Je=>[...Je,...Ye])};return se.addEventListener("paste",me),()=>se.removeEventListener("paste",me)},[r,c]);const De=se=>{se.preventDefault(),!(!e.trim()&&n.length===0)&&lt()},Re=se=>{var me,Ue;if(!((me=V.current)!=null&&me.handleKeyDown(se))&&!((Ue=G.current)!=null&&Ue.handleKeyDown(se))){if(p)switch(se.key){case"Enter":{se.preventDefault();const He=S();He&&(t(He),w());return}case"Escape":se.preventDefault(),w(),Z&&X();return;case"ArrowUp":se.preventDefault(),C();return;case"ArrowDown":se.preventDefault(),_();return}if(se.key==="ArrowUp"&&e.trim()===""&&!p){se.preventDefault(),y();return}se.key==="Enter"&&!se.shiftKey&&(se.preventDefault(),De(se))}};async function ze(se,me,Ue){const He=[];for(const Ye of Array.from(se))await QS(Ye,ct=>He.push(ct),Ue);He.length>0&&me(Ye=>[...Ye,...He])}const Fe=E.useCallback(async se=>{const me=se.target.files;!me||me.length===0||(c(null),await ze(me,r,c),U.current&&(U.current.value=""))},[r,c]),Ee=E.useCallback(se=>{var me;(me=se.dataTransfer.types)!=null&&me.includes("Files")&&(se.preventDefault(),se.stopPropagation(),l(!0))},[l]),st=E.useCallback(se=>{se.preventDefault(),se.stopPropagation(),l(!1)},[l]),ot=E.useCallback(async se=>{se.preventDefault(),se.stopPropagation(),l(!1),c(null);const me=se.dataTransfer.files;!me||me.length===0||await ze(me,r,c)},[r,l,c]),je=E.useCallback(se=>{r(n.filter(me=>me.id!==se))},[n,r]),Me=E.useCallback(()=>{var se;(se=U.current)==null||se.click()},[]),lt=()=>{var me;if(K.current||!e.trim()&&n.length===0)return;if(K.current=!0,(me=d.current)==null||me.scrollTo({top:d.current.scrollHeight,behavior:"smooth"}),e.trim().startsWith("/")){const Ue=vt.getState(),He=[...Ue.defaults,...Ue.userItems,...Ue.projectItems],Ye=Yt.getState(),ct=[...Ye.defaults,...Ye.userItems,...Ye.projectItems],Je=F$(e,He,ct);if(Je!=null&&Je.workflowId){const Ze=He.find(Nt=>Nt.id===Je.workflowId),tt=((Ze==null?void 0:Ze.parameters)??[]).filter(Nt=>Nt.required&&!(Nt.id in Je.params));if(tt.length>0){const Nt=tt.map(dt=>dt.label||dt.id).join(", ");c(`Missing required parameter${tt.length>1?"s":""}: ${Nt}`),K.current=!1;return}he(void 0,void 0,Je.workflowId,void 0,Je.params),M(),K.current=!1;return}if(Je!=null&&Je.commandId){Ye.fetchCommand(Je.commandId).then(Ze=>{if(Ze){const tt=y2(Ze.prompt),Nt={};for(const[rn,Un]of Object.entries(Je.params)){const ye=parseInt(rn,10),Ge=tt[ye];Ge&&(Nt[Ge]=Un)}let dt=Ze.prompt;for(const[rn,Un]of Object.entries(Nt))dt=dt.replaceAll(`{{${rn}}}`,Un);ie(dt,void 0),M()}K.current=!1});return}M(),K.current=!1;return}ie(e,n),M(),K.current=!1},we=E.useCallback((se,me)=>{const He=se.type==="directory"?"/":" ",Ye=e.slice(0,me),ct=e.slice(H.current),Je=`${Ye}@${se.path}${He}${ct}`;t(Je);const Ze=me+se.path.length+2;H.current=Ze,W.current&&(W.current.selectionStart=Ze,W.current.selectionEnd=Ze,W.current.focus())},[e,t]),Ie=E.useCallback((se,me)=>{const Ue=e.slice(0,me),He=e.slice(H.current),Ye=`${Ue}/${se.id} ${He}`;t(Ye);const ct=me+se.id.length+2;if(H.current=ct,W.current&&(W.current.selectionStart=ct,W.current.selectionEnd=ct,W.current.focus()),se.type==="workflow"){const Je=[...vt.getState().defaults,...vt.getState().userItems,...vt.getState().projectItems].find(Ze=>Ze.id===se.id);J(((Je==null?void 0:Je.parameters)??[]).map(Ze=>Ze.id))}else{const Je=Yt.getState(),Ze=[...Je.defaults,...Je.userItems,...Je.projectItems].find(tt=>tt.id===se.id);J((Ze==null?void 0:Ze.paramNames)??[])}},[e,t]),qe=E.useCallback(se=>{const me=se.target.value;t(me),p&&w(),H.current=se.target.selectionStart,P.length>0&&(!me.startsWith("/")||!me.includes(" "))&&J([]),!re.current&&h&&me&&ne&&ne.messages.length===0&&(re.current=!0,ve(`/api/sessions/${h}/warmup`,{method:"POST"}).catch(()=>{}))},[t,p,w,h,ne,P]),te=E.useCallback(se=>{H.current=se.target.selectionStart},[]),ae=E.useCallback(se=>{H.current=se.currentTarget.selectionStart},[]);return i.jsxs("form",{onSubmit:De,className:"relative p-2 md:p-4 bg-secondary",children:[Z&&i.jsx("div",{className:"absolute -top-8 left-2 md:left-4 z-10",children:i.jsx(W$,{})}),i.jsxs("div",{className:`absolute -top-8 right-2 md:right-4 z-10 flex items-center gap-2 border${v?" border-transparent":" rounded backdrop-blur-xl saturate-150 border-border"}`,children:[i.jsx(Qg,{isActive:v,onToggle:b,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(Xi,{}),"Browse history"]})]}),i.jsx("input",{ref:U,type:"file",accept:"image/*,text/*,.pdf,.json,.xml,.yaml,.yml,.js,.sh,.xhtml",onChange:Fe,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(se=>i.jsx(V$,{attachment:se,onRemove:je},se.id))}),p&&i.jsx(G$,{history:m,selectedIndex:x,onSelect:se=>{t(se),w()},onEscape:w,onNavigate:se=>{se==="up"?C():_()}}),i.jsx(u7,{messages:I,onCancel:$}),i.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${a?"bg-accent-primary/10":"bg-primary"}`,onDragOver:Ee,onDragLeave:st,onDrop:ot,children:[i.jsxs("div",{className:"relative flex-1 min-w-0",children:[i.jsx("textarea",{id:Tk,ref:W,value:e,onChange:qe,onKeyDown:Re,onSelect:te,onKeyUp:ae,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(E7,{ref:G,text:e,cursorPos:H.current,workdir:z,onSelect:we}),i.jsx(T7,{ref:V,text:e,cursorPos:H.current,workflows:(()=>{const se=vt.getState();return[...se.defaults,...se.userItems,...se.projectItems]})(),commands:(()=>{const se=Yt.getState();return[...se.defaults,...se.userItems,...se.projectItems]})(),onSelect:Ie}),P.length>0&&(()=>{const se=e.match(/\/(\w+)\s+(.*)$/),Ue=(se?se[2].trim().split(/\s+/):[]).filter(Boolean).length,He=P[Ue];return He?i.jsxs("span",{className:"absolute left-3 top-[26px] text-sm text-text-muted/40 pointer-events-none select-none","aria-hidden":!0,children:[He,"=?"]}):null})()]}),i.jsxs("div",{className:"flex items-center self-center gap-1.5",children:[Z&&i.jsxs("button",{type:"button",onClick:()=>X(),"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(og,{}),"Abort"]}),i.jsxs("div",{className:"flex items-center",children:[i.jsx("button",{type:"button",onClick:lt,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(l7,{onSendCommand:O,onSelectWorkflow:D,onSelectWorkflowWithSubGroup:L,onOpenCommandsManager:N,onOpenWorkflowsManager:T,onAttach:Me,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(g7,{}),i.jsx(x7,{})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[Ft(se=>se.settings)[Te.FEATURES_PER_SESSION_MCP]==="true"&&i.jsx(k7,{}),i.jsx(C7,{})]})]})]})}function t1({workflowName:e,parameters:t,onConfirm:n,onCancel:r,confirmLabel:a="Run workflow"}){const[l,u]=E.useState({}),c=[...t].sort((p,m)=>(p.position??0)-(m.position??0)),d=()=>{var m;const p={};for(const x of c){const y=(m=l[x.id])==null?void 0:m.trim();y&&(p[x.id]=y)}n(p)},h=c.every(p=>{var m;return!p.required||(((m=l[p.id])==null?void 0:m.trim())??"")!==""});return i.jsxs(jt,{isOpen:!0,onClose:r,title:`Run: ${e}`,size:"sm",closeOnEscape:!0,closeOnBackdropClick:!0,children:[i.jsx("div",{className:"space-y-3 py-2",children:c.map(p=>i.jsxs("label",{className:"block",children:[i.jsxs("span",{className:"text-sm text-text-primary font-medium",children:[p.label||p.id,p.required&&i.jsx("span",{className:"text-accent-error ml-1",children:"*"})]}),p.description&&i.jsx("span",{className:"block text-xs text-text-muted mt-0.5",children:p.description}),i.jsx("input",{value:l[p.id]??"",onChange:m=>u(x=>({...x,[p.id]:m.target.value})),placeholder:p.label||p.id,className:"mt-1 w-full px-3 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-accent-primary",autoFocus:p.position===0||p===c[0]})]},p.id))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border",children:[i.jsx("button",{onClick:r,className:"px-3 py-1.5 text-sm text-text-muted hover:text-text-primary transition-colors",children:"Cancel"}),i.jsx("button",{onClick:d,disabled:!h,className:"px-4 py-1.5 text-sm font-medium rounded bg-accent-primary/20 text-accent-primary hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a})]})]})}const n1=9999,Hu=E.forwardRef(function({trigger:t,children:n},r){const[a,l]=E.useState(!1),u=E.useRef(null),c=E.useRef(null),d=E.useRef(null),h=E.useCallback(()=>{l(!1)},[]);E.useImperativeHandle(r,()=>({close:h}),[h]);const p=E.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 E.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&&mi.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:n1,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:n1,top:m.bottom+4,left:w}})(),children:n}),document.body)]})});function L7({entries:e}){const t=new Map;for(const r of e)t.set(r.status,(t.get(r.status)??0)+1);const n=Hk.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(xo,{status:r}),i.jsx("span",{className:"text-text-muted",children:t.get(r)})]},r))})}function D7({visible:e}){const t=Le(P=>P.currentSession),n=Dn(P=>P.status),r=Dn(P=>P.config),a=Dn(P=>P.start),l=Le(P=>P.contextState),u=Le(P=>P.queueUpdate),c=Dn(P=>P.logs),{branch:d,diff:h}=Yg(),[p,m]=E.useState(!1),[x,y]=E.useState(!1),[w,C]=E.useState(!1),[_,S]=E.useState(null),[v,b]=E.useState(!1),[j,N]=E.useState(!1),T=E.useRef(null),D=E.useRef(null),L=E.useRef(null),O=E.useRef(null),M=Ft(P=>P.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true";if(!e||!t)return null;const W=t.workspace?t.workspace.split("/").pop()??"original":"original",U=t.workspace??t.workdir,R=t.metadataEntries??{},H=R.criteria??[],G=["review_findings","todos"],V=G.filter(P=>{var J;return P in R&&(((J=R[P])==null?void 0:J.length)??0)>0}),Z=Object.keys(R).filter(P=>P!=="criteria"&&!G.includes(P)).filter(P=>{var J;return(((J=R[P])==null?void 0:J.length)??0)>0}),X=[...V,...Z].reduce((P,J)=>{var ie;return P+(((ie=R[J])==null?void 0:ie.length)??0)},0),$=[...V,...Z].map(so),I=h.files,B=I.reduce((P,J)=>P+J.additions,0),q=I.reduce((P,J)=>P+J.deletions,0),z=(n==null?void 0:n.state)??"off",ne=z==="running"||z==="warning",re=r!==null,Q=P=>{P.stopPropagation(),a()},K=P=>{P.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(Rr,{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(Ki,{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??"-"}),I.length>0?i.jsxs("span",{className:"text-text-muted shrink-0 font-mono",children:["+",B," -",q]}):i.jsx("span",{className:"shrink-0"}),i.jsx(Hu,{ref:O,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(n2,{workspaceName:W,branch:d,workdir:U,showEditorLink:M,sessionId:t.id,projectId:t.projectId,onEditWorkspace:()=>{var P;(P=O.current)==null||P.close(),b(!0)},onEditBranch:()=>{var P;(P=O.current)==null||P.close(),N(!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(L7,{entries:H}),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(Hu,{ref:L,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var P;(P=L.current)==null||P.close(),S("criteria")},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(xd,{entries:H,title:"Acceptance Criteria"})}),i.jsx(Vk,{entries:H,sessionId:t.id})]}),[...V,...Z].map(P=>{const J=R[P];return i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var ie;(ie=L.current)==null||ie.close(),S(P)},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(xd,{entries:J,title:so(P)})}),i.jsx(Uk,{entries:J})]},P)})]})})]}),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(Zg,{percent:Math.round(l.currentTokens/l.maxTokens*100),dangerZone:l.dangerZone,size:"sm"}),i.jsx(Hu,{ref:D,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(s2,{onUpdateSystemPrompt:()=>{var P;(P=D.current)==null||P.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"}`}),re?ne?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(T1,{className:"w-3.5 h-3.5"})}):i.jsx("button",{onClick:Q,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(A1,{className:"w-3.5 h-3.5"})}):i.jsx("span",{className:"text-text-muted text-xs",children:"No config"}),i.jsx(Hu,{ref:T,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(qk,{workdir:U,compact:!0,onExpand:()=>m(!0),onConfigure:()=>{var P;(P=T.current)==null||P.close(),y(!0)}})})]})]}),p&&i.jsx(Jg,{title:"Dev Server Logs",logs:c,onClose:()=>m(!1)}),x&&i.jsx(Gk,{isOpen:!0,onClose:()=>y(!1)}),_&&t&&i.jsx(Fk,{isOpen:!0,onClose:()=>S(null),entries:R[_]??[],sessionId:t.id,metadataKey:_,title:so(_)}),v&&i.jsx(e2,{isOpen:!0,onClose:()=>b(!1),projectId:t.projectId,sessionId:t.id,currentWorkspace:W,currentBranch:d}),j&&i.jsx(t2,{isOpen:!0,onClose:()=>N(!1),sessionId:t.id}),w&&l&&i.jsx(ex,{isOpen:!0,onClose:()=>C(!1),isRunning:t.isRunning,onApply:()=>{t.isRunning?u():Bt.send("context.applyDynamic",{}),C(!1)}})]})}function R7(e){return(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="f"&&document.querySelector("[data-global-settings]")===null}function w2(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 O7=10,I7=150;function M7(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 P7(e){return[...e].sort((r,a)=>new Date(a.timestamp).getTime()-new Date(r.timestamp).getTime()).slice(0,O7).reverse().map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,formattedTimestamp:iB(r.timestamp),trimmedContent:pd(r.content,I7),sessionId:r.sessionId,sessionName:r.sessionName}))}function B7(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(...M7(l));return P7(r)}function $7(e,t=[],n=null){const[r,a]=E.useState(0),[l,u]=E.useState(!1),c=E.useMemo(()=>B7(e,t,n),[e,t,n]),d=E.useCallback(()=>{c.length>0&&(a(c.length-1),u(!0))},[c.length]),h=E.useCallback(()=>{u(!1),a(0)},[]),p=E.useCallback(()=>{a(y=>c.length===0?y:y===0?c.length-1:y-1)},[c.length]),m=E.useCallback(()=>{a(y=>c.length===0?y:y===c.length-1?0:y+1)},[c.length]),x=E.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}}E.memo(function({item:t}){const[n,r]=E.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(zn,{content:t.description})})]})]})});function z7({criteriaSidebarOpen:e,onCriteriaSidebarToggle:t,rawMessages:n,hiddenCount:r}={}){const a=e??!0,[l,u]=E.useState(""),[c,d]=E.useState([]),[h,p]=E.useState(!1),[m,x]=E.useState(null),[y,w]=E.useState(!1),[C,_]=E.useState(!1),[S,v]=E.useState(!1),[b,j]=E.useState(!1),[N,T]=E.useState(null),D=E.useRef(null),L=Le(te=>te.currentSession),O=Le(te=>te.messages),M=Le(te=>te.sessions),W=kd(),U=Le(te=>te.stopGeneration),R=n??O,{maxVisibleItems:H}=Zi(),G=xt(te=>te.defaults),V=xt(te=>te.userItems),Z=[...G,...V].filter(te=>!te.subagent),{history:X,selectedIndex:$,showHistory:I,openHistory:B,closeHistory:q,navigateUp:z,navigateDown:ne,selectCurrent:re}=$7(R,M,L==null?void 0:L.id);E.useEffect(()=>{const te=ae=>{T(ae.detail.stats)};return window.addEventListener("open-turn-stats",te),()=>window.removeEventListener("open-turn-stats",te)},[]),E.useEffect(()=>{vt.getState().fetchWorkflows()},[]),E.useEffect(()=>{const te=ae=>{R7(ae)&&(ae.preventDefault(),j(!0))};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[]);const Q=E.useRef([]),{displayItems:K,hiddenCount:P}=E.useMemo(()=>{const te=w2(R,Q.current);return Q.current=te,H>0&&te.length>H?{displayItems:te.slice(-H),hiddenCount:te.length-H}:{displayItems:te,hiddenCount:0}},[R,H]),J=r??P,{isAutoScrollActive:ie,setAutoScroll:he}=Qd(D,L),{sendMessage:ce,launchWorkflow:De}=v2(he),[Re,ze]=E.useState(null),[Fe,Ee]=E.useState(null),st=E.useCallback((te,ae,se)=>{const me=vt.getState(),He=[...me.defaults,...me.userItems,...me.projectItems].find(ct=>ct.id===te);((He==null?void 0:He.parameters)??[]).filter(ct=>ct.position!==void 0||ct.required).length>0?ze({id:te,name:(He==null?void 0:He.name)??te,subGroup:ae}):De(void 0,void 0,te,ae,se)},[De]),ot=E.useCallback((te,ae,se)=>{st(te,ae,se)},[st]),je=E.useCallback(te=>{he(!1);const ae=document.querySelector(`[data-item-index="${te}"]`);ae&&ae.scrollIntoView({behavior:"smooth",block:"center"})},[he]);E.useEffect(()=>{const te=ae=>{const se=S||y||C||b||N;ae.key==="Escape"&&W&&!se&&U(),ae.key==="ScrollLock"&&he(!ie)};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[W,U,ie,S,y,C,b,N]);const Me=Kl();Ol(Me.quickAction,()=>{v(!0)}),Ol(Me.criteriaSidebar,()=>{t==null||t()}),ST(Me.agentSwitching,Z,te=>{Le.getState().switchMode(te)});const lt=te=>{st(te),Ie()},we=(te,ae)=>{st(te,ae),Ie()},Ie=()=>{u(""),d([]),L!=null&&L.id&&localStorage.removeItem(`openfox:draft:${L.id}`)},qe=E.useCallback(async(te,ae,se,me)=>{const Ue=y2(te);if(Ue.length>0)Ee({prompt:te,paramKeys:Ue,agentMode:ae,textareaContent:se,attachments:me});else{ae&&(L==null?void 0:L.mode)!==ae&&await Le.getState().switchMode(ae);const He=se&&se.trim()?`${se.trim()}
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 W$(){const e=WN(),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"})]})}function q$(){const e=Le(u=>u.activeWorkflowExecution),t=Le(u=>u.exitWorkflow),[n,r]=E.useState(!1);E.useEffect(()=>{r(!1)},[e==null?void 0:e.id]);const a=E.useCallback(()=>{n||(r(!0),t())},[n,t]);if(!e||e.status!=="running"&&e.status!=="waiting")return null;const l=e.workflowColor&&/^#[0-9a-fA-F]{6}$/.test(e.workflowColor)?e.workflowColor:"#3b82f6";return i.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-xs border-b border-border",children:[i.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l}}),i.jsx("span",{className:"font-medium text-text-primary truncate",children:e.workflowName}),e.currentStepName&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("span",{className:"text-text-muted truncate",children:e.currentStepName})]}),i.jsx("div",{className:"ml-auto shrink-0",children:i.jsx("button",{onClick:a,disabled:n,className:"text-xs px-2 py-0.5 rounded text-text-tool-error hover:bg-text-tool-error/10 transition-colors disabled:opacity-50",children:n?"Exiting...":"✕ Exit"})})]})}const K$={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function Y$(e,t={}){const n={...K$,...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=n7(a),u=`data:${e.type};base64,${l}`,c=await bj(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await X$(e,n)}async function X$(e,t){const n=await J$(e),r=await bj(n),{width:a,height:l}=Q$(r.width,r.height,t.maxWidth,t.maxHeight),u=Z$();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),!(KS(h)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=KS(h);return{dataUrl:h,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function Q$(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 J$(e){return new Promise((t,n)=>{const r=t7(),a=new r;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function bj(e){return new Promise((t,n)=>{const r=e7(),a=new r;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function Z$(){var t;const e=sx();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function e7(){const e=sx();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function t7(){const e=sx();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function sx(){return globalThis}function n7(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 KS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}const YS=50*1024*1024,XS=1024*1024,r7=["image/png","image/jpeg","image/gif"];function s7(e){return e==="application/pdf"}function i7(e){return r7.includes(e.type)}async function a7(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 QS(e,t,n){try{if(nx(e.type)){if(e.size>XS){n(`Text file too large (${Za(e.size)}). Maximum is ${Za(XS)}.`);return}const r=await e.text(),a={id:Uu(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}else if(Yu(e.type)||s7(e.type)){if(e.size>YS){const r=Yu(e.type)?"Image":"PDF";n(`${r} file too large (${Za(e.size)}). Maximum is ${Za(YS)}.`);return}if(Yu(e.type)&&i7(e)){const r=await Y$(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),a={id:Uu(),filename:e.name||"unnamed-file",mimeType:r.mimeType,size:r.size,data:r.dataUrl};t(a)}else{const r=await a7(e),a={id:Uu(),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 vj(e){const t=Le(l=>l.sendMessage),n=Le(l=>l.launchWorkflow),r=E.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=E.useCallback((l,u,c,d,h)=>{e(!0),n(l,u,c,d,h)},[e,n]);return{sendMessage:r,launchWorkflow:a}}function o7({children:e}){return mi.createPortal(e,document.body)}function l7(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 c7({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,h]=E.useState(!1),[p,m]=E.useState("commands"),[x,y]=E.useState(""),[w,C]=E.useState(0),[_,S]=E.useState(null),[v,b]=E.useState(null),j=E.useRef(null),N=E.useRef(null),T=Yt(ne=>ne.defaults),D=Yt(ne=>ne.userItems),L=Yt(ne=>ne.projectItems),O=Yt(ne=>ne.fetchCommands),M=vt(ne=>ne.defaults),W=vt(ne=>ne.userItems),U=vt(ne=>ne.projectItems),R=vt(ne=>ne.fetchWorkflows),H=qr(qr(T,D),L),G=qr(qr(M,W),U);E.useEffect(()=>{d&&(p==="commands"?O():p==="workflows"&&R())},[d,p,O,R]),E.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ne;return(ne=j.current)==null?void 0:ne.focus()}))},[d,p]),E.useEffect(()=>{if(!d)return;const ne=re=>{var Q;(Q=N.current)!=null&&Q.contains(re.target)||h(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[d]);const V=ne=>{switch(ne.key){case"ArrowDown":ne.preventDefault(),C(re=>{const K=(p==="commands"?H:G).filter(P=>{const J=x.toLowerCase();return!J||P.name.toLowerCase().includes(J)});return Math.min(re+1,K.length-1)});break;case"ArrowUp":ne.preventDefault(),C(re=>Math.max(re-1,0));break;case"Enter":ne.preventDefault();break;case"Escape":ne.preventDefault(),h(!1);break}},Z=ne=>{y(ne),C(0)},X=H.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),$=G.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),I=async ne=>{const re=await Yt.getState().fetchCommand(ne);re&&e(re.prompt,re.metadata.agentMode,u,c),h(!1)},B=ne=>{t(ne),h(!1)},q=(ne,re)=>{re.stopPropagation(),h(!1),S(ne)},z=(ne,re)=>{re.stopPropagation(),h(!1),b(ne)};return i.jsxs("div",{ref:N,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(N1,{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:j,value:x,onChange:ne=>Z(ne.target.value),onKeyDown:V,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:H.length===0?"No commands yet":"No matches"}):X.map((ne,re)=>i.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsx("button",{type:"button",onClick:()=>I(ne.id),className:"flex-1 text-left",children:i.jsx("div",{className:"text-sm text-text-primary font-medium",children:ne.name})}),i.jsx(ci,{className:"opacity-0 group-hover:opacity-100",onClick:Q=>q(ne.id,Q)})]},ne.id)):p==="workflows"?$.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:G.length===0?"No workflows yet":"No matches"}):$.map((ne,re)=>{const Q=l7(ne),K=ne.color??"#3b82f6";return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsxs("button",{type:"button",onClick:()=>B(ne.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:ne.name}),Q!==null&&i.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:Q?"#22c55e":"#6b7280"},title:Q?"Entry condition met":"Entry condition not met"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[ne.subGroups&&ne.subGroups.length>0&&i.jsx(u7,{subGroups:ne.subGroups,onSelect:P=>{h(!1),n(ne.id,P)}}),i.jsx(ci,{className:"opacity-0 group-hover:opacity-100",onClick:P=>z(ne.id,P)})]})]},ne.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(nT,{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(fj,{isOpen:!!_,onClose:()=>S(null),initialEditId:_}),i.jsx(gj,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function u7({subGroups:e,onSelect:t}){const[n,r]=E.useState(!1),[a,l]=E.useState({top:0,right:0}),u=E.useRef(null),c=E.useRef(null);Jd(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(o7,{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 d7({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(rc,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function h7({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(V1,{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 JS({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(h7,{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 f7(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 fp(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function m7({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:j}){const N=f7(a),T=p.filter(O=>!(r&&O.topLevelOnly)),D=(O,M)=>{const W=new Map(N),U=W.get(O)||new Set,R=new Set(U);R.has(M)?R.delete(M):R.add(M),R.size===0?W.set(O,new Set):W.set(O,R),C(fp(W))},L=O=>{const M=new Map(N);M.has(O)?M.delete(O):M.set(O,new Set),C(fp(M))};return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3",children:[c&&i.jsx(eo,{message:c}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:h}),i.jsx(Cr,{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(Cr,{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:O=>!h&&_(O.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(O=>{const M=N.has(O.name),W=O.actions.length>0,U=N.get(O.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:O.name}),i.jsx("span",{className:"text-[10px]",children:"*"})]},O.name):i.jsx(nc,{trigger:i.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[i.jsx("span",{children:O.name}),W&&i.jsx("span",{className:`text-[10px] ${M&&U.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...O.actions.map(R=>({label:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${O.name}-${R}`,children:[i.jsx("input",{type:"checkbox",id:`${O.name}-${R}`,checked:U.has(R),onChange:()=>D(O.name,R),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),i.jsx("span",{children:R})]}),closeOnClick:!1})),{label:M?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(M)L(O.name);else{const R=new Map(N);R.set(O.name,new Set(O.actions)),C(fp(R))}}}]},O.name):i.jsx("button",{onClick:()=>!h&&L(O.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"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:O.name})},O.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:O=>!h&&S(O.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(NT,{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:j,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 p7(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function g7({isOpen:e,onClose:t,initialEditId:n}){const r=xt(ae=>ae.defaults),a=xt(ae=>ae.userItems),l=xt(ae=>ae.projectItems),u=xt(ae=>ae.loading),c=xt(ae=>ae.fetchAgents),d=xt(ae=>ae.fetchAgent),h=xt(ae=>ae.fetchDefaultContent),p=xt(ae=>ae.createAgent),m=xt(ae=>ae.updateAgent),x=xt(ae=>ae.deleteAgent),[y,w]=E.useState("list"),[C,_]=E.useState(null),[S,v]=E.useState(!1),[b,j]=E.useState(""),[N,T]=E.useState(""),[D,L]=E.useState(""),[O,M]=E.useState(!0),[W,U]=E.useState([]),[R,H]=E.useState("#6b7280"),[G,V]=E.useState(""),[Z,X]=E.useState("user"),[$,I]=E.useState(""),[B,q]=E.useState(!1),[z,ne]=E.useState([]),[re,Q]=E.useState(new Set),{requestDelete:K,clearConfirm:P,isConfirming:J}=Yl(),ie=ae=>{j(ae.metadata.name),T(ae.metadata.id),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I("")},he=(ae,se,me)=>{j(ae.metadata.name+" (copy)"),T(`${se}-copy-${Date.now()}`),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I(""),_(null),v(!1),w("edit")},ce=(ae,se)=>{ie(ae),_(se),v(!0),w("edit")};E.useEffect(()=>{e&&(c(),ve("/api/tools").then(ae=>ae.json()).then(ae=>{const se=ae.tools||[];Q(new Set(se.filter(me=>me.alwaysAllowed).map(me=>me.name))),ne(se.filter(me=>!me.alwaysAllowed))}).catch(()=>{ne([]),Q(new Set)}),n?r.some(se=>se.id===n)?h(n).then(se=>{se&&he(se,n)}):d(n).then(se=>{se&&(ie(se),_(n),v(!1),w("edit"))}):(w("list"),_(null),v(!1)))},[e,c,d,h,n]);const De=async ae=>{if(r.some(me=>me.id===ae)){const me=await h(ae);if(!me)return;ce(me,ae)}else{const me=await d(ae);if(!me)return;ce(me,ae)}},Re=async ae=>{let se=await h(ae);se||(se=await d(ae)),se&&he(se,ae)},ze=()=>{_(null),j(""),T(""),L(""),M(!0),U(["read_file"]),H("#6b7280"),V(""),X("user"),I(""),v(!1),w("edit")},Fe=async ae=>{const se=await d(ae);se&&(ie(se),_(ae),v(!1),w("edit"))},Ee=async ae=>{await x(ae)},st=async()=>{const ae=C??N;if(!ae||!b||!G){I("Name and prompt are required.");return}q(!0),I("");const se={metadata:{id:ae,name:b,description:D,subagent:O,allowedTools:W.filter(Ue=>!re.has(Ue)),color:R},prompt:G},me=C?await m(C,se):await p(se,Z);if(q(!1),!me.success){I(me.error??"Failed to save agent.");return}n?t():w("list")},ot=()=>{n?t():(w("list"),v(!1))},je=ae=>{j(ae),C||T(p7(ae))},Me=r.filter(ae=>ae.subagent),lt=r.filter(ae=>!ae.subagent),we=a.filter(ae=>ae.subagent),Ie=a.filter(ae=>!ae.subagent),qe=l.filter(ae=>ae.subagent),te=l.filter(ae=>!ae.subagent);return y==="edit"?i.jsxs(jt,{isOpen:e,onClose:ot,title:S?`${b}`:C?"Edit Agent":"New Agent",size:"xl",children:[!C&&!S&&i.jsx(Nd,{value:Z,onChange:X}),i.jsx(m7,{formName:b,formId:N,formDescription:D,formSubagent:O,formTools:W,formColor:R,formPrompt:G,formError:$,saving:B,isReadOnly:S,availableTools:z,onNameChange:je,onIdChange:T,onDescriptionChange:L,onSubagentChange:ae=>{M(ae),ae&&U(se=>se.filter(me=>{var Ue;return!((Ue=z.find(He=>He.name===me))!=null&&Ue.topLevelOnly)}))},onToolsChange:U,onColorChange:H,onPromptChange:V,onSave:st,onCancel:ot,onDuplicate:()=>{j(b+" (copy)"),T(`${C}-copy-${Date.now()}`),_(null),v(!1)}})]}):i.jsx(jt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:i.jsx(I1,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ze,loading:u,hasItems:r.length>0||a.length>0||l.length>0,children:i.jsxs("div",{className:"space-y-4",children:[r.length>0&&i.jsx(JS,{title:"Built-in",agents:lt,subagents:Me,isBuiltIn:!0,alwaysAllowedNames:re,onView:De,onDuplicate:Re}),[{title:"Custom",agents:Ie,subagents:we},{title:"Project",agents:te,subagents:qe}].map(ae=>ae.agents.length>0&&i.jsx(JS,{title:ae.title,agents:ae.agents,subagents:ae.subagents,isBuiltIn:!1,alwaysAllowedNames:re,isConfirmingDelete:se=>J(se,"delete"),onView:De,onDuplicate:Re,onEdit:Fe,onDelete:se=>{J(se,"delete")?(Ee(se),P()):K(se)},onCancelDelete:P},ae.title))]})})})}function x7(){const e=Le(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=Le(v=>v.switchMode),n=xt(v=>v.defaults),r=xt(v=>v.userItems),a=xt(v=>v.fetchAgents),l=[...n,...r],[u,c]=E.useState(!1),[d,h]=E.useState(!1),[p,m]=E.useState(null),x=E.useRef(null);E.useEffect(()=>{a()},[a]),Jd(x,()=>c(!1));const y=Kl();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=Vl(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(hn,{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 j=v.id===e,N=Vl(l,v.id),T=y.agentSwitching[b],D=T?Xu(T):null;return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${j?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[i.jsxs("button",{type:"button",onClick:()=>{j||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:N},children:v.name}),j&&i.jsx(Mr,{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(g7,{isOpen:d,onClose:()=>{h(!1),m(null)},initialEditId:p})]})}function y7(){const e=Le(r=>r.currentSession),t=Le(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 ZS({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 b7=[8080,11434,8e3,1234];function eg(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function _j(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 v7({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,j,N,T,D,L,O,M,W,U,R,H,G,V,Z,X,$,I,B,q,z,ne,re,Q,K,P,J,ie,he,ce,De,Re,ze,Fe;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:Ee=>a(e.id,{contextWindow:parseInt(Ee.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:Ee=>a(e.id,{supportsVision:Ee.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:(j=r[e.id+"-non-thinking"])==null?void 0:j.error,children:"Fail"}),((N=r[e.id+"-non-thinking"])==null?void 0:N.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(hn,{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:Ee=>a(e.id,{thinkingEnabled:Ee.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:((O=t[e.id])==null?void 0:O.thinkingLevel)??eg(e.reasoningEfforts),onChange:Ee=>a(e.id,{thinkingLevel:Ee.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(Ee=>i.jsx("option",{value:Ee,children:Ee},Ee))}):i.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((M=t[e.id])==null?void 0:M.thinkingLevel)??"",onChange:Ee=>a(e.id,{thinkingLevel:Ee.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsx(ZS,{value:(W=t[e.id])==null?void 0:W.thinkingQueryParams,onChange:Ee=>a(e.id,{thinkingQueryParams:Ee})})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((U=t[e.id])==null?void 0:U.nonThinkingEnabled)??!1,onChange:Ee=>a(e.id,{nonThinkingEnabled:Ee.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(ZS,{value:(H=t[e.id])==null?void 0:H.nonThinkingQueryParams,onChange:Ee=>a(e.id,{nonThinkingQueryParams:Ee})})})]}),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:((G=t[e.id])==null?void 0:G.temperature)??"",onChange:Ee=>a(e.id,{temperature:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((Z=(V=t[e.id])==null?void 0:V.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:((I=t[e.id])==null?void 0:I.topP)??"",onChange:Ee=>a(e.id,{topP:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((q=(B=t[e.id])==null?void 0:B.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: ",(ne=t[e.id])==null?void 0:ne.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:((re=t[e.id])==null?void 0:re.topK)??"",onChange:Ee=>a(e.id,{topK:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((K=(Q=t[e.id])==null?void 0:Q.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"}),((P=t[e.id])==null?void 0:P.defaultTopK)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(J=t[e.id])==null?void 0:J.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:((ie=t[e.id])==null?void 0:ie.maxTokens)??"",onChange:Ee=>a(e.id,{maxTokens:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((ce=(he=t[e.id])==null?void 0:he.defaultMaxTokens)==null?void 0:ce.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((De=t[e.id])==null?void 0:De.defaultMaxTokens)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Re=t[e.id])==null?void 0:Re.defaultMaxTokens]})]})]})]}),i.jsx("div",{className:"pt-3 border-t border-border",children:i.jsx(_7,{value:(ze=t[e.id])==null?void 0:ze.compactionThreshold,maxTokens:((Fe=t[e.id])==null?void 0:Fe.contextWindow)??e.contextWindow,onChange:Ee=>a(e.id,{compactionThreshold:Ee})})})]})]})}function _7({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]=E.useState(Math.round(c*100));E.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,"% · ",oo(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 ",oo(15e3)," tokens · maximum ",l,"% · default 85%"]})]})}function Sj({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:a,editModelId:l}){const[u,c]=E.useState(r),[d,h]=E.useState(""),[p,m]=E.useState(""),[x,y]=E.useState("unknown"),[w,C]=E.useState(""),[_,S]=E.useState(!1),[v,b]=E.useState(),[j,N]=E.useState(),[T,D]=E.useState(!1),[L,O]=E.useState(null),[M,W]=E.useState([]),[U,R]=E.useState(null),[H,G]=E.useState(!1),[V,Z]=E.useState(""),[X,$]=E.useState({}),[I,B]=E.useState({loading:!1,progress:{}}),[q,z]=E.useState({}),[ne,re]=E.useState(null),[Q,K]=E.useState(new Set),[P,J]=E.useState(""),[ie,he]=E.useState(null),[ce,De]=E.useState("disconnected"),[Re,ze]=E.useState(!1),[Fe,Ee]=E.useState(null),[st,ot]=E.useState([]),[je,Me]=E.useState(!1),[lt,we]=E.useState(!1),Ie=E.useRef(null),qe=E.useRef(!1),te=E.useRef(null);E.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var ye;return(ye=te.current)==null?void 0:ye.focus()})},[u,e]),E.useEffect(()=>()=>{Ie.current!==null&&window.clearTimeout(Ie.current)},[]),E.useEffect(()=>{e&&ve("/api/provider-presets").then(async ye=>ye.ok?await ye.json():{presets:[]}).then(ye=>ot(ye.presets)).catch(()=>ot([]))},[e]);function ae(ye,Ge){$(oe=>({...oe,[ye]:{...oe[ye],...Ge}}))}function se(ye){K(Ge=>new Set(Ge).add(ye.id)),$(Ge=>({...Ge,[ye.id]:{contextWindow:ye.contextWindow,...Ge[ye.id]}}))}function me(ye){if(!ye.trim())return M;const Ge=ye.toLowerCase().split(/\s+/).filter(Boolean);return M.filter(oe=>Ge.every(fe=>oe.id.toLowerCase().includes(fe)))}E.useEffect(()=>{var ye,Ge;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),N(a==null?void 0:a.transportAdapter),O(null),Z((a==null?void 0:a.thinkingField)??""),z({}),re(null),he(null),De("disconnected"),Ee(null),Me(!1),we(!1),(ye=a==null?void 0:a.models)!=null&&ye.length){const oe={},fe=new Set;for(const Pe of a.models)oe[Pe.id]={contextWindow:Pe.contextWindow,supportsVision:Pe.supportsVision,thinkingEnabled:Pe.thinkingEnabled,thinkingLevel:Pe.thinkingLevel??eg(Pe.reasoningEfforts),nonThinkingEnabled:Pe.nonThinkingEnabled,thinkingQueryParams:Pe.thinkingQueryParams,nonThinkingQueryParams:Pe.nonThinkingQueryParams,defaultTemperature:Pe.defaultTemperature,defaultTopP:Pe.defaultTopP,defaultTopK:Pe.defaultTopK,defaultMaxTokens:Pe.defaultMaxTokens,temperature:Pe.temperature,topP:Pe.topP,topK:Pe.topK,maxTokens:Pe.maxTokens,compactionThreshold:Pe.compactionThreshold},Pe.selected&&fe.add(Pe.id);if(fe.size===0)for(const Pe of a.models)fe.add(Pe.id);K(fe),$(oe),W(a.models),R(l??((Ge=a.models[0])==null?void 0:Ge.id)??null)}else W([]),$({}),R(null),K(new Set)},[e,r,a==null?void 0:a.id,l]),E.useEffect(()=>{const ye=!!v;u===2&&p&&M.length===0&&!T&&!L&&(!ye||ce==="connected")&&Ze(p)},[u,ce]),E.useEffect(()=>{!e||!v||!(a!=null&&a.id)||He(a.id)},[e,j,a==null?void 0:a.id]),E.useEffect(()=>{if(!Fe)return;const ye=(a==null?void 0:a.id)??ie;if(!ye)return;let Ge=!1;const oe=async()=>{const Pe=await He(ye);Ge||Pe!=="connected"||(Ee(null),Me(!1),we(!1),await Ze(p))};oe();const fe=window.setInterval(()=>void oe(),2e3);return()=>{Ge=!0,window.clearInterval(fe)}},[Fe,ie,a==null?void 0:a.id]);async function Ue(){if(a!=null&&a.id)return a.id;if(ie)return ie;const ye=await ve("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d||"Provider",url:p,backend:x,authAdapter:v,transportAdapter:j,isLocal:!1,models:[]})});if(!ye.ok)throw new Error("Unable to create provider");const Ge=await ye.json();return he(Ge.provider.id),Ge.provider.id}async function He(ye){const Ge=await ve(`/api/provider-auth/${ye}/status`);if(!Ge.ok)return"error";const oe=await Ge.json(),fe=oe.state==="connected"?"connected":oe.state==="pending"?"pending":oe.state==="error"?"error":"disconnected";return De(fe),fe}async function Ye(){ze(!0),De("pending");try{const ye=await Ue(),Ge=await ve(`/api/provider-auth/${ye}/login`,{method:"POST"});if(!Ge.ok)throw new Error("Unable to start provider sign-in");const oe=await Ge.json();Ee(oe)}catch{De("error")}finally{ze(!1)}}async function ct(){var ye;Fe!=null&&Fe.userCode&&(await((ye=navigator.clipboard)==null?void 0:ye.writeText(Fe.userCode)),Ie.current!==null&&window.clearTimeout(Ie.current),we(!1),requestAnimationFrame(()=>we(!0)),Ie.current=window.setTimeout(()=>{we(!1),Ie.current=null},1500))}function Je(){Fe&&(window.open(Fe.directUrl??Fe.verificationUrl,"_blank","noopener,noreferrer"),Me(!0))}async function Ze(ye){var Ge,oe;D(!0),O(null),W([]);try{const fe=new URLSearchParams({url:ye});w&&fe.set("apiKey",w),x&&fe.set("backend",x);const Pe=j?await ve(`/api/providers/${await Ue()}/models`):await ve(`/api/providers/models?${fe.toString()}`);if(Pe.ok){const St=await Pe.json();if((Ge=St.models)!=null&&Ge.length){W(St.models),R(((oe=St.models[0])==null?void 0:oe.id)??null);const bn={};for(const fn of St.models)bn[fn.id]={contextWindow:fn.contextWindow,thinkingEnabled:!0,thinkingLevel:eg(fn.reasoningEfforts),defaultTemperature:fn.defaultTemperature,defaultTopP:fn.defaultTopP,defaultTopK:fn.defaultTopK,defaultMaxTokens:fn.defaultMaxTokens};$(bn),St.models.length===1&&(K(new Set([St.models[0].id])),R(St.models[0].id),tt(St.models[0].id))}}else{const St=await Pe.json();O(St.error??`Failed to fetch models from ${ye}`)}}catch(fe){O(`Failed to fetch models from ${ye}: ${fe instanceof Error?fe.message:"Unknown error"}`)}D(!1)}async function tt(ye){B(Ge=>({loading:!0,progress:{...Ge.progress,[ye]:"probing"}}));try{const Ge=await ve("/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:ye}]})});if(!Ge.ok){const fe=await Ge.json();throw new Error(fe.error??"Auto-config failed")}const oe=await Ge.json();for(const fe of oe.models){const Pe={};fe.contextSource!=="default"&&(Pe.contextWindow=fe.contextWindow,Pe.supportsVision=fe.supportsVision),fe.thinkingConfig&&(Pe.thinkingEnabled=!0,Pe.thinkingQueryParams=JSON.stringify(fe.thinkingConfig)),fe.nonThinkingConfig&&(Pe.nonThinkingEnabled=!0,Pe.nonThinkingQueryParams=JSON.stringify(fe.nonThinkingConfig)),ae(fe.id,Pe),B(St=>({...St,progress:{...St.progress,[fe.id]:"done"}}))}}catch(Ge){console.error("Auto-config error:",Ge),B(oe=>({...oe,progress:{...oe.progress,[ye]:"error"}}))}finally{B(Ge=>({...Ge,loading:!1}))}}async function Nt(ye,Ge){const oe=ye+"-"+Ge;z(fe=>({...fe,[oe]:{loading:!0}}));try{const fe=X[ye],Pe=await ve("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,providerId:(a==null?void 0:a.id)??ie??void 0,transportAdapter:j,model:ye,apiKey:w||void 0,backend:x||"unknown",thinkingField:V||void 0,mode:Ge,modelConfig:{temperature:fe==null?void 0:fe.temperature,topP:fe==null?void 0:fe.topP,topK:fe==null?void 0:fe.topK,maxTokens:fe==null?void 0:fe.maxTokens,supportsVision:fe==null?void 0:fe.supportsVision,thinkingEnabled:fe==null?void 0:fe.thinkingEnabled,thinkingLevel:fe==null?void 0:fe.thinkingLevel,nonThinkingEnabled:fe==null?void 0:fe.nonThinkingEnabled,thinkingQueryParams:fe==null?void 0:fe.thinkingQueryParams,nonThinkingQueryParams:fe==null?void 0:fe.nonThinkingQueryParams}})}),St=await Pe.json();Pe.ok?z(bn=>({...bn,[oe]:{loading:!1,result:JSON.stringify(St,null,2),message:St.message}})):z(bn=>({...bn,[oe]:{loading:!1,error:St.error??"Test failed"}}))}catch(fe){z(Pe=>({...Pe,[oe]:{loading:!1,error:fe instanceof Error?fe.message:"Request failed"}}))}}function dt(){W([]),$({}),B({loading:!1,progress:{}}),z({}),re(null),K(new Set),J("")}function rn(){ie&&!qe.current&&ve(`/api/providers/${ie}`,{method:"DELETE"}).catch(ye=>{console.warn("Failed to clean up draft provider",ye)}),t()}function Un(){const ye=d||"Provider",Ge=(a==null?void 0:a.id)??ie??`temp-${Date.now()}`;n({id:Ge,name:ye,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:_,thinkingField:V||void 0,authAdapter:v,transportAdapter:j,models:M.map(oe=>{var fe,Pe,St,bn,fn,Pr,Ns,xi,Ts,As,Se,Ce,Oe,We,Ve,Qe;return{id:oe.id,name:oe.name,apiModelId:oe.apiModelId,requestBody:oe.requestBody,reasoningEfforts:oe.reasoningEfforts,contextWindow:((fe=X[oe.id])==null?void 0:fe.contextWindow)??oe.contextWindow,selected:Q.has(oe.id)||void 0,supportsVision:(Pe=X[oe.id])==null?void 0:Pe.supportsVision,thinkingEnabled:(St=X[oe.id])==null?void 0:St.thinkingEnabled,thinkingLevel:(bn=X[oe.id])==null?void 0:bn.thinkingLevel,nonThinkingEnabled:(fn=X[oe.id])==null?void 0:fn.nonThinkingEnabled,thinkingQueryParams:(Pr=X[oe.id])==null?void 0:Pr.thinkingQueryParams,nonThinkingQueryParams:(Ns=X[oe.id])==null?void 0:Ns.nonThinkingQueryParams,temperature:(xi=X[oe.id])==null?void 0:xi.temperature,topP:(Ts=X[oe.id])==null?void 0:Ts.topP,topK:(As=X[oe.id])==null?void 0:As.topK,maxTokens:(Se=X[oe.id])==null?void 0:Se.maxTokens,defaultMaxTokens:(Ce=X[oe.id])==null?void 0:Ce.defaultMaxTokens,defaultTemperature:(Oe=X[oe.id])==null?void 0:Oe.defaultTemperature,defaultTopP:(We=X[oe.id])==null?void 0:We.defaultTopP,defaultTopK:(Ve=X[oe.id])==null?void 0:Ve.defaultTopK,compactionThreshold:(Qe=X[oe.id])==null?void 0:Qe.compactionThreshold}})}),qe.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:rn,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(ye=>i.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${ye<u?"bg-accent-success":ye===u?"bg-accent-primary":"bg-border"}`},ye))}),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:[st.map(ye=>i.jsx("button",{type:"button",onClick:()=>{h(ye.defaults.name??ye.name),m(ye.defaults.url),y(ye.defaults.backend),S(!1),C(""),b(ye.authAdapter),N(ye.transportAdapter),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${j&&j===ye.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ye.name},ye.id)),i.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),b(void 0),N(void 0),O(null),dt()},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"),b7.map(ye=>{const Ge={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},oe={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return i.jsx("button",{type:"button",onClick:()=>{h(fe=>fe||(oe[ye]??"")),m(fe=>fe||`http://localhost:${ye}`),y(Ge[ye]??""),S(!0),b(void 0),N(void 0),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${x===Ge[ye]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:oe[ye]??`localhost:${ye}`},ye)})]})]}),!v&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),i.jsx("input",{ref:te,type:"text",value:p,"data-testid":"provider-modal-url",onChange:ye=>{m(ye.target.value),O(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:ye=>h(ye.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:ye=>C(ye.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:ye=>S(ye.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."})]}),ce==="connected"?i.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):i.jsx("button",{type:"button",onClick:()=>void Ye(),disabled:Re||ce==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:Re||ce==="pending"?"Connecting...":ce==="error"?"Retry":"Connect"})]}),Fe&&i.jsx("div",{className:"mt-4 border-t border-border pt-4",children:Fe.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 ct(),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:Fe.userCode??"Continue"}),i.jsxs("div",{className:"mt-3 flex gap-2",children:[i.jsx("button",{type:"button",onClick:()=>void ct(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:lt?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:Je,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"Reopen authorization":"Open authorization"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted mb-3",children:Fe.instructions}),i.jsx("button",{type:"button",onClick:Je,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"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:()=>Ze(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),i.jsx("button",{onClick:()=>{dt(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),M.length>0&&x&&(!v||ce==="connected")&&i.jsxs(i.Fragment,{children:[Q.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 (",Q.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:M.filter(ye=>Q.has(ye.id)).map(ye=>{var Ge;return i.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[i.jsxs("div",{onClick:()=>R(U===ye.id?null:ye.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:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((Ge=X[ye.id])==null?void 0:Ge.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[I.progress[ye.id]==="probing"?i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):I.progress[ye.id]==="done"?i.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):I.progress[ye.id]==="error"?i.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):v?null:i.jsx("button",{onClick:oe=>{oe.stopPropagation(),tt(ye.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),M.length>1&&i.jsx("button",{onClick:oe=>{oe.stopPropagation();const fe=new Set(Q);fe.delete(ye.id),K(fe),U===ye.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(hn,{className:`w-4 h-4 text-text-muted transition-transform ${U===ye.id?"rotate-180":""}`})]})]}),U===ye.id&&i.jsx(v7,{model:ye,modelConfigs:X,autoConfigState:I,testResults:q,onUpdateConfig:ae,onRunAutoConfig:tt,onTestParams:Nt,onShowRaw:re})]},ye.id)})})]}),M.length>1&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),Q.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:P,onChange:ye=>J(ye.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"}),P&&i.jsx("button",{onClick:()=>J(""),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 ",me(P).length," of ",M.length," models"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{const ye=new Set(Q),Ge=me(P);for(const oe of Ge)ye.add(oe.id);if(K(ye),$(oe=>{const fe={...oe};for(const Pe of Ge)fe[Pe.id]={contextWindow:Pe.contextWindow,...fe[Pe.id]};return fe}),!v)for(const oe of Ge)I.progress[oe.id]!=="probing"&&I.progress[oe.id]!=="done"&&tt(oe.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),i.jsx("button",{onClick:()=>{const ye=new Set(Q),Ge=me(P);for(const oe of Ge)ye.delete(oe.id);K(ye)},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:[me(P).map(ye=>{var oe;const Ge=Q.has(ye.id);return i.jsxs("div",{role:"checkbox","aria-checked":Ge,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${Ge?"bg-accent-primary/5":""}`,onClick:()=>{if(Ge){const fe=new Set(Q);fe.delete(ye.id),K(fe)}else se(ye),v||tt(ye.id)},onKeyDown:fe=>{(fe.key==="Enter"||fe.key===" ")&&(fe.preventDefault(),fe.currentTarget.click())},children:[i.jsx("input",{type:"checkbox",checked:Ge,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:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((oe=X[ye.id])==null?void 0:oe.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]}),I.progress[ye.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"}),I.progress[ye.id]==="done"&&i.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),I.progress[ye.id]==="error"&&i.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},ye.id)}),me(P).length===0&&i.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",P,"”"]})]})]})]})]}),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&&dt(),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:rn,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:Un,disabled:I.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:I.loading?"Configuring...":"Save Provider"})]})]})]}),H&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&G(!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:()=>G(!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:V,onChange:ye=>Z(ye.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:()=>G(!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"})})]})}),ne&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&re(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:()=>re(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:ne})]})})]}):null}function S7(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function w7(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 e1({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 C7({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:S7(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(L1,{className:"w-3.5 h-3.5 text-accent-warning"}):i.jsx(D1,{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(j1,{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(Mr,{className:"w-3.5 h-3.5"})})]})]})}function k7(){var Ge;const[,e]=Tn(),t=Le(oe=>oe.currentSession),n=Le(oe=>oe.setSessionProvider),[r,a]=E.useState(!1),[l,u]=E.useState([]),[c,d]=E.useState(null),h=E.useRef(null),[p,m]=E.useState(null),[x,y]=E.useState(!1),[w,C]=E.useState({}),[_,S]=E.useState(null),[v,b]=E.useState(null),[j,N]=E.useState(!1),T=E.useRef(null),[D,L]=E.useState(!1),O=E.useRef(new Set),[M,W]=E.useState(-1),U=E.useRef(null),R=Xt(oe=>oe.providers),H=Xt(oe=>oe.activeProviderId),G=Xt(oe=>oe.defaultModelSelection),V=Xt(oe=>oe.activating),Z=Xt(oe=>oe.activateProvider),X=Xt(oe=>oe.refreshModel),$=Xt(oe=>oe.refreshProviderModels),I=Xt(oe=>oe.setDefaultModel),B=Xt(oe=>oe.fetchConfig),q=Kl();Ol(q.modelSelector,()=>a(oe=>!oe));const z=(t==null?void 0:t.providerId)??null,ne=(t==null?void 0:t.providerModel)??null,re=(G==null?void 0:G.split("/")[0])??null,Q=(G==null?void 0:G.split("/").slice(1).join("/"))??null,K=z??re,P=ne??Q,J=P?((Ge=P.split("/").pop())==null?void 0:Ge.replace(/-/g," "))??P:"No model",[ie,he]=E.useState(!1),[ce,De]=E.useState(""),Re=E.useRef(null);E.useEffect(()=>{function oe(fe){h.current&&!h.current.contains(fe.target)&&(a(!1),u([]),O.current=new Set)}return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]),E.useEffect(()=>()=>{T.current!==null&&window.clearTimeout(T.current)},[]),E.useEffect(()=>{r||(De(""),W(-1))},[r]),E.useEffect(()=>{var oe;r&&((oe=Re.current)==null||oe.focus())},[r]),E.useEffect(()=>{M>=0&&U.current&&U.current.scrollIntoView({block:"nearest"})},[M]),E.useEffect(()=>{if(r){const oe=R.map(fe=>fe.id);u(oe),R.filter(fe=>!!fe.authAdapter).forEach(fe=>void Ie(fe.id)),oe.forEach(fe=>{O.current.has(fe)||(O.current.add(fe),ot(fe))})}},[r,R]),E.useEffect(()=>{if(!v)return;let oe=!1;const fe=async()=>{const St=await Ie(v.providerId);oe||St==="connected"&&(b(null),N(!1),L(!1),await B(),O.current.delete(v.providerId),await ot(v.providerId))};fe();const Pe=window.setInterval(()=>void fe(),2e3);return()=>{oe=!0,window.clearInterval(Pe)}},[v]);const ze=R.find(oe=>oe.id===K),Fe=(ze==null?void 0:ze.status)==="disconnected",Ee=(oe,fe)=>t?t.providerId===oe&&t.providerModel===fe:!1,st=(oe,fe)=>G?G===`${oe}/${fe}`:!1,ot=async oe=>{d(oe);try{await $(oe)}catch{}finally{d(null)}},je=oe=>{l.includes(oe.id)?u(l.filter(fe=>fe!==oe.id)):(u([...l,oe.id]),ot(oe.id))},Me=async oe=>{if(oe.id===H){je(oe);return}t?(n(oe.id,void 0),a(!1),u([])):await Z(oe.id)&&(a(!1),u([]))},lt=oe=>{je(oe)},we=async(oe,fe)=>{oe.stopPropagation(),O.current.delete(fe),await ot(fe)},Ie=async oe=>{const fe=await ve(`/api/provider-auth/${oe}/status`);if(!fe.ok)return"error";const Pe=await fe.json();return C(St=>({...St,[oe]:Pe.state})),Pe.state},qe=async(oe,fe)=>{oe.stopPropagation(),S(fe),C(Pe=>({...Pe,[fe]:"pending"})),N(!1),L(!1);try{const Pe=await ve(`/api/provider-auth/${fe}/login`,{method:"POST"});if(!Pe.ok)throw new Error("Unable to start provider sign-in");const St=await Pe.json();b({providerId:fe,...St})}catch{C(Pe=>({...Pe,[fe]:"error"}))}finally{S(null)}},te=async()=>{var oe;v!=null&&v.userCode&&(await((oe=navigator.clipboard)==null?void 0:oe.writeText(v.userCode)),T.current!==null&&window.clearTimeout(T.current),N(!1),requestAnimationFrame(()=>N(!0)),T.current=window.setTimeout(()=>{N(!1),T.current=null},1500))},ae=()=>{v&&(window.open(v.directUrl??v.verificationUrl,"_blank","noopener,noreferrer"),L(!0))},se=()=>{b(null),N(!1),L(!1)},me=async(oe,fe)=>{oe.stopPropagation(),S(fe);try{if(!(await ve(`/api/provider-auth/${fe}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");C(St=>({...St,[fe]:"disconnected"})),await B()}finally{S(null)}},Ue=(oe,fe)=>{m({providerId:oe,model:fe}),y(!0)},He=p?R.find(oe=>oe.id===p.providerId):void 0,Ye=()=>{m(null),y(!1)},ct=async oe=>{try{if(!(await ve(`/api/providers/${oe.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(_j(oe))})).ok)throw new Error("Failed to update provider");await Xt.getState().fetchConfig()}catch{}m(null),y(!1)},Je=async(oe,fe)=>{if(t){Le.setState(St=>({currentSession:St.currentSession?{...St.currentSession,providerId:oe,providerModel:fe}:null})),n(oe,fe),u([]),a(!1),Gl();return}await Z(oe)&&(u([]),a(!1),Gl())},Ze=async(oe,fe,Pe)=>{oe.stopPropagation(),he(!0);try{await I(fe,Pe)}catch{}finally{he(!1)}};function tt(oe){return oe.models.some(Pe=>Pe.selected)?oe.models.filter(Pe=>Pe.selected):oe.models}const Nt=E.useMemo(()=>ce.trim()?R.map(oe=>({provider:oe,models:tt(oe).filter(fe=>w7(fe,ce))})).filter(oe=>oe.models.length>0):R.map(oe=>({provider:oe,models:tt(oe)})),[R,ce]),dt=E.useMemo(()=>Nt.flatMap(oe=>oe.models.map(fe=>({providerId:oe.provider.id,modelConfig:fe}))),[Nt]),rn=dt.length+1,Un=M===dt.length;E.useEffect(()=>{rn===1?W(-1):M>=rn?W(rn-1):M<0&&ce.trim()&&W(0)},[rn,M,ce]);const ye=oe=>{switch(oe.key){case"Escape":a(!1);break;case"ArrowDown":oe.preventDefault(),rn>0&&W(fe=>fe<rn-1?fe+1:0);break;case"ArrowUp":oe.preventDefault(),rn>0&&W(fe=>fe>0?fe-1:rn-1);break;case"Home":oe.preventDefault(),W(0);break;case"End":oe.preventDefault(),W(rn-1);break;case"Enter":if(oe.preventDefault(),M===dt.length)e("/onboarding"),a(!1);else if(M>=0&&M<dt.length){const fe=dt[M];fe&&Je(fe.providerId,fe.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:Fe?"LLM server is offline. Click to retry.":J??"Click to refresh model",children:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):i.jsx(e1,{activeProvider:ze,shortModelName:J}),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:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):i.jsx(e1,{activeProvider:ze,shortModelName:J}),i.jsx(hn,{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(Xi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("input",{ref:Re,type:"text",value:ce,onInput:oe=>{De(oe.currentTarget.value),W(-1)},onKeyDown:ye,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:[Nt.map(oe=>{const fe=ce.trim().length>0||l.includes(oe.provider.id);return i.jsxs("div",{children:[i.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${oe.provider.id===K?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${V?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[i.jsxs("div",{onClick:()=>!V&&Me(oe.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[i.jsx("span",{className:`text-sm font-medium truncate ${oe.provider.id===K?"text-accent-primary":"text-text-primary"}`,children:oe.provider.name}),i.jsx("span",{className:"text-xs text-text-muted truncate",children:oe.provider.backend!=="unknown"&&g1(oe.provider.backend)})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!oe.provider.authAdapter&&(w[oe.provider.id]==="connected"||oe.provider.credentialRef?i.jsx("button",{type:"button",onClick:Pe=>me(Pe,oe.provider.id),disabled:_===oe.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:Pe=>qe(Pe,oe.provider.id),disabled:_===oe.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:_===oe.provider.id?"Starting…":w[oe.provider.id]==="error"||w[oe.provider.id]==="expired"?"Retry":"Connect"})),oe.provider.id===K?i.jsx("span",{className:"text-accent-success",title:"Active provider",children:i.jsx(Mr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-4"}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),we(Pe,oe.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:i.jsx(jd,{className:`w-4 h-4 ${c===oe.provider.id?"animate-spin":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),lt(oe.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:i.jsx(hn,{className:`w-4 h-4 transition-transform ${fe?"rotate-180":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})})]})]}),fe&&i.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===oe.provider.id?i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):oe.models.length>0?oe.models.map(Pe=>{const bn=dt.findIndex(fn=>fn.providerId===oe.provider.id&&fn.modelConfig.id===Pe.id)===M;return i.jsx("div",{ref:bn?U:void 0,children:i.jsx(C7,{providerId:oe.provider.id,modelConfig:Pe,isActive:Ee(oe.provider.id,Pe.id),isDefault:st(oe.provider.id,Pe.id),disabled:c==="activating",hasSession:!!t,settingDefault:ie,highlighted:bn,onModelClick:Je,onSetDefault:Ze,onEditModel:Ue})},`${oe.provider.id}/${Pe.id}`)}):i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},oe.provider.id)}),Nt.length===0&&ce.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 ${Un?"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:oe=>{oe.target===oe.currentTarget&&se()},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:se,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:te,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:j?"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:te,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:j?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:ae,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:ae,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(Sj,{isOpen:!0,onClose:Ye,onSave:ct,initialStep:2,editProvider:{id:p.providerId,name:(He==null?void 0:He.name)??"",url:(He==null?void 0:He.url)??"",backend:(He==null?void 0:He.backend)??"unknown",apiKey:He==null?void 0:He.apiKey,isLocal:He==null?void 0:He.isLocal,thinkingField:He==null?void 0:He.thinkingField,authAdapter:He==null?void 0:He.authAdapter,transportAdapter:He==null?void 0:He.transportAdapter,models:He==null?void 0:He.models},editModelId:p.model.id})]})}function j7(){const e=Dl(j=>j.servers),t=Dl(j=>j.fetchServers),n=Le(j=>j.currentSession),r=n==null?void 0:n.id,[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(new Set),[p,m]=E.useState(new Set),x=E.useRef(null),y=E.useCallback(async()=>{if(r)try{const j=await ve(`/api/sessions/${r}/mcp/overrides`);if(j.ok){const N=await j.json();m(new Set(N.disabledServers??[]))}}catch{}},[r]),w=E.useCallback(async()=>{await t(),await y()},[t,y]);E.useEffect(()=>{const j=()=>w();return window.addEventListener("mcp-servers-changed",j),()=>window.removeEventListener("mcp-servers-changed",j)},[w]),E.useEffect(()=>{y()},[y]),E.useEffect(()=>{a&&y()},[a,y]),Jd(x,()=>l(!1));const C=j=>p.has(j.name),_=e.filter(j=>j.status==="connected"&&!C(j)),S=_.length,v=_.reduce((j,N)=>j+N.estimatedTokens,0),b=async(j,N)=>{if(r){c(null),h(T=>new Set(T).add(j));try{const T=new Set(p);N?T.add(j):T.delete(j);const D=await ve(`/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(j),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 (${md(v)})`:"MCP"}),i.jsx(hn,{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(j=>{const N=C(j),T=d.has(j.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 ${qg(N?"disabled":j.status)}`,children:Kg(N?"disabled":j.status)}),i.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:j.name})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[i.jsxs("span",{children:[j.tools.length," tools"]}),j.estimatedTokens>0&&i.jsxs("span",{children:[md(j.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(Kr,{enabled:!N,onClick:()=>b(j.name,!N)})]})]})},j.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 E7(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
+ `)||a.includes(" ")?null:{query:a,startIndex:r}}const N7=E.forwardRef(function({text:t,cursorPos:n,workdir:r,onSelect:a},l){const u=E7(t,n),[c,d]=E.useState([]),[h,p]=E.useState(!1),[m,x]=E.useState(0),y=E.useRef(null),w=E.useRef([]),C=E.useRef(0),_=E.useRef([]);E.useEffect(()=>{C.current=m},[m]),E.useEffect(()=>{_.current=c},[c]),E.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 j=new URLSearchParams({q:b});r&&j.set("workdir",r);const T=await(await ve(`/api/files?${j.toString()}`)).json();d(T),x(0),C.current=0}catch(j){console.error("File search failed:",j),d([])}finally{p(!1)}},v=E.useCallback(b=>{if(!u)return!1;switch(b.key){case"ArrowDown":return b.preventDefault(),x(j=>{var T;const N=Math.min(j+1,_.current.length-1);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.min(C.current+1,_.current.length-1),!0;case"ArrowUp":return b.preventDefault(),x(j=>{var T;const N=Math.max(j-1,0);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.max(C.current-1,0),!0;case"Enter":case"Tab":{const j=_.current;return j[C.current]?(b.preventDefault(),a(j[C.current],u.startIndex),!0):!1}case"Escape":return b.preventDefault(),d([]),!0}return!1},[u,a]);return E.useImperativeHandle(l,()=>({handleKeyDown:v}),[v]),E.useEffect(()=>{if(!u)return;const b=j=>{y.current&&!y.current.contains(j.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(pi,{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",{children:c.map((b,j)=>i.jsxs("li",{ref:N=>{w.current[j]=N},className:`px-3 py-2 cursor-pointer flex items-center gap-2 text-sm ${j===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(Rr,{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 T7(e,t){const n=e.slice(0,t);if(n.length===0||n[0]!=="/")return null;const r=n.slice(1);return r.includes(" ")||r.includes(`
313
+ `)||r.includes(" ")?null:{query:r,startIndex:0}}const A7=E.forwardRef(function({text:t,cursorPos:n,workflows:r,commands:a,onSelect:l},u){const c=T7(t,n),[d,h]=E.useState(0),p=E.useRef(null),m=E.useRef([]),x=E.useRef(0),y=E.useRef([]);E.useEffect(()=>{x.current=d},[d]),E.useEffect(()=>{y.current=C});const w=(c==null?void 0:c.query)??"",C=(()=>{if(!c)return[];const S=w.toLowerCase(),v=r.filter(j=>j.id.toLowerCase().includes(S)||j.name.toLowerCase().includes(S)).map(j=>({type:"workflow",id:j.id,name:j.name,paramCount:(j.parameters??[]).length})),b=a.filter(j=>j.id.toLowerCase().includes(S)||j.name.toLowerCase().includes(S)).map(j=>({type:"command",id:j.id,name:j.name,paramCount:0}));return[...v,...b]})();E.useEffect(()=>{h(0),x.current=0},[C.length]);const _=E.useCallback(S=>{if(!c||C.length===0)return!1;switch(S.key){case"ArrowDown":return S.preventDefault(),h(v=>{var j;const b=Math.min(v+1,C.length-1);return(j=m.current[b])==null||j.scrollIntoView({block:"nearest"}),b}),!0;case"ArrowUp":return S.preventDefault(),h(v=>{var j;const b=Math.max(v-1,0);return(j=m.current[b])==null||j.scrollIntoView({block:"nearest"}),b}),!0;case"Enter":case"Tab":{const v=C[x.current];return v?(S.preventDefault(),l(v,c.startIndex),!0):!1}case"Escape":return S.preventDefault(),!0}return!1},[c,C,l]);return E.useImperativeHandle(u,()=>({handleKeyDown:_}),[_]),!c||C.length===0?null:i.jsx("div",{ref:p,className:"absolute bottom-full left-0 right-0 mb-2 z-50",role:"listbox",children:i.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg max-h-64 overflow-y-auto",children:i.jsx("div",{children:C.map((S,v)=>i.jsxs("button",{ref:b=>{m.current[v]=b},role:"option","aria-selected":v===d,className:`w-full text-left px-3 py-2 flex items-center gap-2 text-sm ${v===d?"bg-accent-primary/20 text-text-primary":"text-text-muted hover:bg-bg-tertiary"}`,onClick:()=>{c&&l(S,c.startIndex)},children:[i.jsxs("span",{className:`font-medium ${S.type==="workflow"?"text-accent-primary":"text-accent-warning"}`,children:["/",S.id]}),i.jsx("span",{className:"truncate flex-1",children:S.name}),S.paramCount>0&&i.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary px-1.5 py-0.5 rounded",children:[S.paramCount," param",S.paramCount>1?"s":""]})]},`${S.type}-${S.id}`))})})})});function L7({input:e,setInput:t,attachments:n,setAttachments:r,dragOver:a,setDragOver:l,errorMessage:u,setErrorMessage:c,scrollContainerRef:d,sessionId:h,showHistory:p,history:m,selectedIndex:x,openHistory:y,closeHistory:w,navigateUp:C,navigateDown:_,selectCurrent:S,isAutoScrollActive:v,setAutoScroll:b,onOpenMessageSearch:j,onOpenCommandsModal:N,onOpenWorkflowsModal:T,onSelectWorkflow:D,onSelectWorkflowWithSubGroup:L,onSendCommand:O,clearInput:M}){const W=E.useRef(null),U=E.useRef(null),R=E.useRef(0),H=E.useRef(0),G=E.useRef(null),V=E.useRef(null),Z=kd(),X=Le(se=>se.stopGeneration),$=Le(se=>se.cancelQueued),I=Le(se=>se.queuedMessages),B=Le(se=>se.restoredInput),q=Le(se=>se.clearRestoredInput),z=Le(se=>{var me;return(me=se.currentSession)==null?void 0:me.workdir}),ne=Le(se=>se.currentSession),re=E.useRef(!1),Q=E.useRef(!1),K=E.useRef(!1),[P,J]=E.useState([]),{sendMessage:ie,launchWorkflow:he}=vj(b);E.useEffect(()=>{if(Q.current)return;Q.current=!0;const se=vt.getState();se.defaults.length===0&&se.userItems.length===0&&se.projectItems.length===0&&se.fetchWorkflows();const me=Yt.getState();me.defaults.length===0&&me.userItems.length===0&&me.projectItems.length===0&&me.fetchCommands()},[]),E.useEffect(()=>{e||J([])},[e]),E.useEffect(()=>{var se;B!==null&&(t(B),q(),(se=W.current)==null||se.focus())},[B,t,q]);const ce=E.useCallback(()=>{const se=W.current;if(!se)return;const me=e.length>=R.current;R.current=e.length,me||(se.style.height="auto"),se.style.height=`${Math.min(200,se.scrollHeight)}px`},[e]);E.useEffect(()=>{if(!h)return;const se=`openfox:draft:${h}`,me=localStorage.getItem(se);me!==null&&t(me)},[h,t]),E.useEffect(()=>{var se;(se=W.current)==null||se.focus(),ce()},[h,ce]),E.useEffect(()=>{if(!h)return;const se=`openfox:draft:${h}`,me=setTimeout(()=>{e?localStorage.setItem(se,e):localStorage.removeItem(se)},500);return()=>clearTimeout(me)},[h,e]),E.useEffect(()=>{ce()},[e,ce]),E.useEffect(()=>{const se=W.current;if(!se)return;const me=async Ue=>{var ct;if(document.activeElement!==se)return;const He=(ct=Ue.clipboardData)==null?void 0:ct.items;if(!He)return;const Ye=[];for(const Je of Array.from(He)){let Ze=Je.getAsFile();if(Ze&&l$(Ze.type)){if(Ue.preventDefault(),!Ze.name){const tt=o$(Ze.type);Ze=new File([Ze],`pasted-file.${tt}`,{type:Ze.type})}await QS(Ze,tt=>Ye.push(tt),c)}}Ye.length>0&&r(Je=>[...Je,...Ye])};return se.addEventListener("paste",me),()=>se.removeEventListener("paste",me)},[r,c]);const De=se=>{se.preventDefault(),!(!e.trim()&&n.length===0)&&lt()},Re=se=>{var me,Ue;if(!((me=V.current)!=null&&me.handleKeyDown(se))&&!((Ue=G.current)!=null&&Ue.handleKeyDown(se))){if(p)switch(se.key){case"Enter":{se.preventDefault();const He=S();He&&(t(He),w());return}case"Escape":se.preventDefault(),w(),Z&&X();return;case"ArrowUp":se.preventDefault(),C();return;case"ArrowDown":se.preventDefault(),_();return}if(se.key==="ArrowUp"&&e.trim()===""&&!p){se.preventDefault(),y();return}se.key==="Enter"&&!se.shiftKey&&(se.preventDefault(),De(se))}};async function ze(se,me,Ue){const He=[];for(const Ye of Array.from(se))await QS(Ye,ct=>He.push(ct),Ue);He.length>0&&me(Ye=>[...Ye,...He])}const Fe=E.useCallback(async se=>{const me=se.target.files;!me||me.length===0||(c(null),await ze(me,r,c),U.current&&(U.current.value=""))},[r,c]),Ee=E.useCallback(se=>{var me;(me=se.dataTransfer.types)!=null&&me.includes("Files")&&(se.preventDefault(),se.stopPropagation(),l(!0))},[l]),st=E.useCallback(se=>{se.preventDefault(),se.stopPropagation(),l(!1)},[l]),ot=E.useCallback(async se=>{se.preventDefault(),se.stopPropagation(),l(!1),c(null);const me=se.dataTransfer.files;!me||me.length===0||await ze(me,r,c)},[r,l,c]),je=E.useCallback(se=>{r(n.filter(me=>me.id!==se))},[n,r]),Me=E.useCallback(()=>{var se;(se=U.current)==null||se.click()},[]),lt=()=>{var me;if(K.current||!e.trim()&&n.length===0)return;if(K.current=!0,(me=d.current)==null||me.scrollTo({top:d.current.scrollHeight,behavior:"smooth"}),e.trim().startsWith("/")){const Ue=vt.getState(),He=[...Ue.defaults,...Ue.userItems,...Ue.projectItems],Ye=Yt.getState(),ct=[...Ye.defaults,...Ye.userItems,...Ye.projectItems],Je=F$(e,He,ct);if(Je!=null&&Je.workflowId){const Ze=He.find(Nt=>Nt.id===Je.workflowId),tt=((Ze==null?void 0:Ze.parameters)??[]).filter(Nt=>Nt.required&&!(Nt.id in Je.params));if(tt.length>0){const Nt=tt.map(dt=>dt.label||dt.id).join(", ");c(`Missing required parameter${tt.length>1?"s":""}: ${Nt}`),K.current=!1;return}he(void 0,void 0,Je.workflowId,void 0,Je.params),M(),K.current=!1;return}if(Je!=null&&Je.commandId){Ye.fetchCommand(Je.commandId).then(Ze=>{if(Ze){const tt=yj(Ze.prompt),Nt={};for(const[rn,Un]of Object.entries(Je.params)){const ye=parseInt(rn,10),Ge=tt[ye];Ge&&(Nt[Ge]=Un)}let dt=Ze.prompt;for(const[rn,Un]of Object.entries(Nt))dt=dt.replaceAll(`{{${rn}}}`,Un);ie(dt,void 0),M()}K.current=!1});return}M(),K.current=!1;return}ie(e,n),M(),K.current=!1},we=E.useCallback((se,me)=>{const He=se.type==="directory"?"/":" ",Ye=e.slice(0,me),ct=e.slice(H.current),Je=`${Ye}@${se.path}${He}${ct}`;t(Je);const Ze=me+se.path.length+2;H.current=Ze,W.current&&(W.current.selectionStart=Ze,W.current.selectionEnd=Ze,W.current.focus())},[e,t]),Ie=E.useCallback((se,me)=>{const Ue=e.slice(0,me),He=e.slice(H.current),Ye=`${Ue}/${se.id} ${He}`;t(Ye);const ct=me+se.id.length+2;if(H.current=ct,W.current&&(W.current.selectionStart=ct,W.current.selectionEnd=ct,W.current.focus()),se.type==="workflow"){const Je=[...vt.getState().defaults,...vt.getState().userItems,...vt.getState().projectItems].find(Ze=>Ze.id===se.id);J(((Je==null?void 0:Je.parameters)??[]).map(Ze=>Ze.id))}else{const Je=Yt.getState(),Ze=[...Je.defaults,...Je.userItems,...Je.projectItems].find(tt=>tt.id===se.id);J((Ze==null?void 0:Ze.paramNames)??[])}},[e,t]),qe=E.useCallback(se=>{const me=se.target.value;t(me),p&&w(),H.current=se.target.selectionStart,P.length>0&&(!me.startsWith("/")||!me.includes(" "))&&J([]),!re.current&&h&&me&&ne&&ne.messages.length===0&&(re.current=!0,ve(`/api/sessions/${h}/warmup`,{method:"POST"}).catch(()=>{}))},[t,p,w,h,ne,P]),te=E.useCallback(se=>{H.current=se.target.selectionStart},[]),ae=E.useCallback(se=>{H.current=se.currentTarget.selectionStart},[]);return i.jsxs("div",{className:"relative",children:[Z&&i.jsx("div",{className:"absolute -top-8 left-2 md:left-4 z-10",children:i.jsx(W$,{})}),i.jsxs("div",{className:`absolute -top-8 right-2 md:right-4 z-10 flex items-center gap-2 border${v?" border-transparent":" rounded backdrop-blur-xl saturate-150 border-border"}`,children:[i.jsx(Qg,{isActive:v,onToggle:b,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(Xi,{}),"Browse history"]})]}),i.jsx(q$,{}),i.jsxs("form",{onSubmit:De,className:"p-2 md:p-4 bg-secondary rounded-lg",children:[i.jsx("input",{ref:U,type:"file",accept:"image/*,text/*,.pdf,.json,.xml,.yaml,.yml,.js,.sh,.xhtml",onChange:Fe,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(se=>i.jsx(V$,{attachment:se,onRemove:je},se.id))}),p&&i.jsx(G$,{history:m,selectedIndex:x,onSelect:se=>{t(se),w()},onEscape:w,onNavigate:se=>{se==="up"?C():_()}}),i.jsx(d7,{messages:I,onCancel:$}),i.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${a?"bg-accent-primary/10":"bg-primary"}`,onDragOver:Ee,onDragLeave:st,onDrop:ot,children:[i.jsxs("div",{className:"relative flex-1 min-w-0",children:[i.jsx("textarea",{id:Tk,ref:W,value:e,onChange:qe,onKeyDown:Re,onSelect:te,onKeyUp:ae,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(N7,{ref:G,text:e,cursorPos:H.current,workdir:z,onSelect:we}),i.jsx(A7,{ref:V,text:e,cursorPos:H.current,workflows:(()=>{const se=vt.getState();return[...se.defaults,...se.userItems,...se.projectItems]})(),commands:(()=>{const se=Yt.getState();return[...se.defaults,...se.userItems,...se.projectItems]})(),onSelect:Ie}),P.length>0&&(()=>{const se=e.match(/\/(\w+)\s+(.*)$/),Ue=(se?se[2].trim().split(/\s+/):[]).filter(Boolean).length,He=P[Ue];return He?i.jsxs("span",{className:"absolute left-3 top-[26px] text-sm text-text-muted/40 pointer-events-none select-none","aria-hidden":!0,children:[He,"=?"]}):null})()]}),i.jsxs("div",{className:"flex items-center self-center gap-1.5",children:[Z&&i.jsxs("button",{type:"button",onClick:()=>X(),"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(og,{}),"Abort"]}),i.jsxs("div",{className:"flex items-center",children:[i.jsx("button",{type:"button",onClick:lt,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(c7,{onSendCommand:O,onSelectWorkflow:D,onSelectWorkflowWithSubGroup:L,onOpenCommandsManager:N,onOpenWorkflowsManager:T,onAttach:Me,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(x7,{}),i.jsx(y7,{})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[Ft(se=>se.settings)[Te.FEATURES_PER_SESSION_MCP]==="true"&&i.jsx(j7,{}),i.jsx(k7,{})]})]})]})]})}function t1({workflowName:e,parameters:t,onConfirm:n,onCancel:r,confirmLabel:a="Run workflow"}){const[l,u]=E.useState({}),c=[...t].sort((p,m)=>(p.position??0)-(m.position??0)),d=()=>{var m;const p={};for(const x of c){const y=(m=l[x.id])==null?void 0:m.trim();y&&(p[x.id]=y)}n(p)},h=c.every(p=>{var m;return!p.required||(((m=l[p.id])==null?void 0:m.trim())??"")!==""});return i.jsxs(jt,{isOpen:!0,onClose:r,title:`Run: ${e}`,size:"sm",closeOnEscape:!0,closeOnBackdropClick:!0,children:[i.jsx("div",{className:"space-y-3 py-2",children:c.map(p=>i.jsxs("label",{className:"block",children:[i.jsxs("span",{className:"text-sm text-text-primary font-medium",children:[p.label||p.id,p.required&&i.jsx("span",{className:"text-accent-error ml-1",children:"*"})]}),p.description&&i.jsx("span",{className:"block text-xs text-text-muted mt-0.5",children:p.description}),i.jsx("input",{value:l[p.id]??"",onChange:m=>u(x=>({...x,[p.id]:m.target.value})),placeholder:p.label||p.id,className:"mt-1 w-full px-3 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-accent-primary",autoFocus:p.position===0||p===c[0]})]},p.id))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border",children:[i.jsx("button",{onClick:r,className:"px-3 py-1.5 text-sm text-text-muted hover:text-text-primary transition-colors",children:"Cancel"}),i.jsx("button",{onClick:d,disabled:!h,className:"px-4 py-1.5 text-sm font-medium rounded bg-accent-primary/20 text-accent-primary hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a})]})]})}const n1=9999,Hu=E.forwardRef(function({trigger:t,children:n},r){const[a,l]=E.useState(!1),u=E.useRef(null),c=E.useRef(null),d=E.useRef(null),h=E.useCallback(()=>{l(!1)},[]);E.useImperativeHandle(r,()=>({close:h}),[h]);const p=E.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 E.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&&mi.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:n1,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:n1,top:m.bottom+4,left:w}})(),children:n}),document.body)]})});function D7({entries:e}){const t=new Map;for(const r of e)t.set(r.status,(t.get(r.status)??0)+1);const n=Hk.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(xo,{status:r}),i.jsx("span",{className:"text-text-muted",children:t.get(r)})]},r))})}function R7({visible:e}){const t=Le(P=>P.currentSession),n=Dn(P=>P.status),r=Dn(P=>P.config),a=Dn(P=>P.start),l=Le(P=>P.contextState),u=Le(P=>P.queueUpdate),c=Dn(P=>P.logs),{branch:d,diff:h}=Yg(),[p,m]=E.useState(!1),[x,y]=E.useState(!1),[w,C]=E.useState(!1),[_,S]=E.useState(null),[v,b]=E.useState(!1),[j,N]=E.useState(!1),T=E.useRef(null),D=E.useRef(null),L=E.useRef(null),O=E.useRef(null),M=Ft(P=>P.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true";if(!e||!t)return null;const W=t.workspace?t.workspace.split("/").pop()??"original":"original",U=t.workspace??t.workdir,R=t.metadataEntries??{},H=R.criteria??[],G=["review_findings","todos"],V=G.filter(P=>{var J;return P in R&&(((J=R[P])==null?void 0:J.length)??0)>0}),Z=Object.keys(R).filter(P=>P!=="criteria"&&!G.includes(P)).filter(P=>{var J;return(((J=R[P])==null?void 0:J.length)??0)>0}),X=[...V,...Z].reduce((P,J)=>{var ie;return P+(((ie=R[J])==null?void 0:ie.length)??0)},0),$=[...V,...Z].map(so),I=h.files,B=I.reduce((P,J)=>P+J.additions,0),q=I.reduce((P,J)=>P+J.deletions,0),z=(n==null?void 0:n.state)??"off",ne=z==="running"||z==="warning",re=r!==null,Q=P=>{P.stopPropagation(),a()},K=P=>{P.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(Rr,{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(Ki,{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??"-"}),I.length>0?i.jsxs("span",{className:"text-text-muted shrink-0 font-mono",children:["+",B," -",q]}):i.jsx("span",{className:"shrink-0"}),i.jsx(Hu,{ref:O,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(nj,{workspaceName:W,branch:d,workdir:U,showEditorLink:M,sessionId:t.id,projectId:t.projectId,onEditWorkspace:()=>{var P;(P=O.current)==null||P.close(),b(!0)},onEditBranch:()=>{var P;(P=O.current)==null||P.close(),N(!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(D7,{entries:H}),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(Hu,{ref:L,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var P;(P=L.current)==null||P.close(),S("criteria")},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(xd,{entries:H,title:"Acceptance Criteria"})}),i.jsx(Vk,{entries:H,sessionId:t.id})]}),[...V,...Z].map(P=>{const J=R[P];return i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var ie;(ie=L.current)==null||ie.close(),S(P)},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(xd,{entries:J,title:so(P)})}),i.jsx(Uk,{entries:J})]},P)})]})})]}),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(Zg,{percent:Math.round(l.currentTokens/l.maxTokens*100),dangerZone:l.dangerZone,size:"sm"}),i.jsx(Hu,{ref:D,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(sj,{onUpdateSystemPrompt:()=>{var P;(P=D.current)==null||P.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"}`}),re?ne?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(T1,{className:"w-3.5 h-3.5"})}):i.jsx("button",{onClick:Q,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(A1,{className:"w-3.5 h-3.5"})}):i.jsx("span",{className:"text-text-muted text-xs",children:"No config"}),i.jsx(Hu,{ref:T,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(qk,{workdir:U,compact:!0,onExpand:()=>m(!0),onConfigure:()=>{var P;(P=T.current)==null||P.close(),y(!0)}})})]})]}),p&&i.jsx(Jg,{title:"Dev Server Logs",logs:c,onClose:()=>m(!1)}),x&&i.jsx(Gk,{isOpen:!0,onClose:()=>y(!1)}),_&&t&&i.jsx(Fk,{isOpen:!0,onClose:()=>S(null),entries:R[_]??[],sessionId:t.id,metadataKey:_,title:so(_)}),v&&i.jsx(ej,{isOpen:!0,onClose:()=>b(!1),projectId:t.projectId,sessionId:t.id,currentWorkspace:W,currentBranch:d}),j&&i.jsx(tj,{isOpen:!0,onClose:()=>N(!1),sessionId:t.id}),w&&l&&i.jsx(ex,{isOpen:!0,onClose:()=>C(!1),isRunning:t.isRunning,onApply:()=>{t.isRunning?u():Dt.send("context.applyDynamic",{}),C(!1)}})]})}function O7(e){return(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="f"&&document.querySelector("[data-global-settings]")===null}function wj(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 I7=10,M7=150;function P7(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 B7(e){return[...e].sort((r,a)=>new Date(a.timestamp).getTime()-new Date(r.timestamp).getTime()).slice(0,I7).reverse().map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,formattedTimestamp:iB(r.timestamp),trimmedContent:pd(r.content,M7),sessionId:r.sessionId,sessionName:r.sessionName}))}function $7(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(...P7(l));return B7(r)}function z7(e,t=[],n=null){const[r,a]=E.useState(0),[l,u]=E.useState(!1),c=E.useMemo(()=>$7(e,t,n),[e,t,n]),d=E.useCallback(()=>{c.length>0&&(a(c.length-1),u(!0))},[c.length]),h=E.useCallback(()=>{u(!1),a(0)},[]),p=E.useCallback(()=>{a(y=>c.length===0?y:y===0?c.length-1:y-1)},[c.length]),m=E.useCallback(()=>{a(y=>c.length===0?y:y===c.length-1?0:y+1)},[c.length]),x=E.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}}E.memo(function({item:t}){const[n,r]=E.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(zn,{content:t.description})})]})]})});function H7({criteriaSidebarOpen:e,onCriteriaSidebarToggle:t,rawMessages:n,hiddenCount:r}={}){const a=e??!0,[l,u]=E.useState(""),[c,d]=E.useState([]),[h,p]=E.useState(!1),[m,x]=E.useState(null),[y,w]=E.useState(!1),[C,_]=E.useState(!1),[S,v]=E.useState(!1),[b,j]=E.useState(!1),[N,T]=E.useState(null),D=E.useRef(null),L=Le(te=>te.currentSession),O=Le(te=>te.messages),M=Le(te=>te.sessions),W=kd(),U=Le(te=>te.stopGeneration),R=n??O,{maxVisibleItems:H}=Zi(),G=xt(te=>te.defaults),V=xt(te=>te.userItems),Z=[...G,...V].filter(te=>!te.subagent),{history:X,selectedIndex:$,showHistory:I,openHistory:B,closeHistory:q,navigateUp:z,navigateDown:ne,selectCurrent:re}=z7(R,M,L==null?void 0:L.id);E.useEffect(()=>{const te=ae=>{T(ae.detail.stats)};return window.addEventListener("open-turn-stats",te),()=>window.removeEventListener("open-turn-stats",te)},[]),E.useEffect(()=>{vt.getState().fetchWorkflows()},[]),E.useEffect(()=>{const te=ae=>{O7(ae)&&(ae.preventDefault(),j(!0))};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[]);const Q=E.useRef([]),{displayItems:K,hiddenCount:P}=E.useMemo(()=>{const te=wj(R,Q.current);return Q.current=te,H>0&&te.length>H?{displayItems:te.slice(-H),hiddenCount:te.length-H}:{displayItems:te,hiddenCount:0}},[R,H]),J=r??P,{isAutoScrollActive:ie,setAutoScroll:he}=Qd(D,L),{sendMessage:ce,launchWorkflow:De}=vj(he),[Re,ze]=E.useState(null),[Fe,Ee]=E.useState(null),st=E.useCallback((te,ae,se)=>{const me=vt.getState(),He=[...me.defaults,...me.userItems,...me.projectItems].find(ct=>ct.id===te);((He==null?void 0:He.parameters)??[]).filter(ct=>ct.position!==void 0||ct.required).length>0?ze({id:te,name:(He==null?void 0:He.name)??te,subGroup:ae}):De(void 0,void 0,te,ae,se)},[De]),ot=E.useCallback((te,ae,se)=>{st(te,ae,se)},[st]),je=E.useCallback(te=>{he(!1);const ae=document.querySelector(`[data-item-index="${te}"]`);ae&&ae.scrollIntoView({behavior:"smooth",block:"center"})},[he]);E.useEffect(()=>{const te=ae=>{const se=S||y||C||b||N;ae.key==="Escape"&&W&&!se&&U(),ae.key==="ScrollLock"&&he(!ie)};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[W,U,ie,S,y,C,b,N]);const Me=Kl();Ol(Me.quickAction,()=>{v(!0)}),Ol(Me.criteriaSidebar,()=>{t==null||t()}),ST(Me.agentSwitching,Z,te=>{Le.getState().switchMode(te)});const lt=te=>{st(te),Ie()},we=(te,ae)=>{st(te,ae),Ie()},Ie=()=>{u(""),d([]),L!=null&&L.id&&localStorage.removeItem(`openfox:draft:${L.id}`)},qe=E.useCallback(async(te,ae,se,me)=>{const Ue=yj(te);if(Ue.length>0)Ee({prompt:te,paramKeys:Ue,agentMode:ae,textareaContent:se,attachments:me});else{ae&&(L==null?void 0:L.mode)!==ae&&await Le.getState().switchMode(ae);const He=se&&se.trim()?`${se.trim()}
314
314
 
315
- ${te}`:te;ce(He,me!=null&&me.length?me:void 0,{messageKind:"command",isSystemGenerated:!0}),Ie()}},[ce,Ie,L]);return i.jsxs(i.Fragment,{children:[i.jsxs(y8,{criteriaSidebarOpen:a,onCriteriaSidebarToggle:t,messages:R,children:[i.jsx(D7,{visible:!a}),i.jsx(b8,{}),N&&i.jsx(v8,{stats:N,onClose:()=>T(null)}),i.jsx(b$,{}),i.jsx(x$,{displayItems:K,scrollContainerRef:D,highlightedMessageId:null,onLaunchWorkflow:ot,onScrollToTop:()=>he(!1),hiddenCount:J}),i.jsx(A7,{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,showHistory:I,history:X,selectedIndex:$,openHistory:B,closeHistory:q,navigateUp:z,navigateDown:ne,selectCurrent:re,isAutoScrollActive:ie,setAutoScroll:he,onOpenMessageSearch:()=>j(!0),onOpenCommandsModal:()=>w(!0),onOpenWorkflowsModal:()=>_(!0),onSelectWorkflow:lt,onSelectWorkflowWithSubGroup:we,onSendCommand:qe,clearInput:Ie}),i.jsx(f2,{isOpen:y,onClose:()=>w(!1)}),i.jsx(g2,{isOpen:C,onClose:()=>_(!1)}),i.jsx(R$,{isOpen:S,onClose:()=>v(!1),onSearchMessages:()=>j(!0),isAutoScrollActive:ie,onToggleAutoScroll:he,textareaContent:l,onCloseComplete:Gl,onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(te,ae)=>{const se=await Yt.getState().fetchCommand(te);se&&qe(se.prompt,se.metadata.agentMode,ae)},onSelectWorkflow:te=>{st(te),Ie()}}),Re&&i.jsx(t1,{workflowName:Re.name,parameters:(()=>{var se;const te=vt.getState();return((se=[...te.defaults,...te.userItems,...te.projectItems].find(me=>me.id===Re.id))==null?void 0:se.parameters)??[]})(),onConfirm:te=>{De(void 0,void 0,Re.id,Re.subGroup,te),ze(null)},onCancel:()=>ze(null)}),Fe&&i.jsx(t1,{workflowName:"Command",confirmLabel:"Launch command",parameters:Fe.paramKeys.map((te,ae)=>({id:te,label:te,position:ae})),onConfirm:te=>{let ae=Fe.prompt;for(const[Ye,ct]of Object.entries(te))ae=ae.replaceAll(`{{${Ye}}}`,ct);const{agentMode:se,textareaContent:me,attachments:Ue}=Fe;se&&(L==null?void 0:L.mode)!==se&&Le.getState().switchMode(se);const He=me&&me.trim()?`${me.trim()}
315
+ ${te}`:te;ce(He,me!=null&&me.length?me:void 0,{messageKind:"command",isSystemGenerated:!0}),Ie()}},[ce,Ie,L]);return i.jsxs(i.Fragment,{children:[i.jsxs(y8,{criteriaSidebarOpen:a,onCriteriaSidebarToggle:t,messages:R,children:[i.jsx(R7,{visible:!a}),i.jsx(b8,{}),N&&i.jsx(v8,{stats:N,onClose:()=>T(null)}),i.jsx(b$,{}),i.jsx(x$,{displayItems:K,scrollContainerRef:D,highlightedMessageId:null,onLaunchWorkflow:ot,onScrollToTop:()=>he(!1),hiddenCount:J}),i.jsx(L7,{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,showHistory:I,history:X,selectedIndex:$,openHistory:B,closeHistory:q,navigateUp:z,navigateDown:ne,selectCurrent:re,isAutoScrollActive:ie,setAutoScroll:he,onOpenMessageSearch:()=>j(!0),onOpenCommandsModal:()=>w(!0),onOpenWorkflowsModal:()=>_(!0),onSelectWorkflow:lt,onSelectWorkflowWithSubGroup:we,onSendCommand:qe,clearInput:Ie}),i.jsx(fj,{isOpen:y,onClose:()=>w(!1)}),i.jsx(gj,{isOpen:C,onClose:()=>_(!1)}),i.jsx(R$,{isOpen:S,onClose:()=>v(!1),onSearchMessages:()=>j(!0),isAutoScrollActive:ie,onToggleAutoScroll:he,textareaContent:l,onCloseComplete:Gl,onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(te,ae)=>{const se=await Yt.getState().fetchCommand(te);se&&qe(se.prompt,se.metadata.agentMode,ae)},onSelectWorkflow:te=>{st(te),Ie()}}),Re&&i.jsx(t1,{workflowName:Re.name,parameters:(()=>{var se;const te=vt.getState();return((se=[...te.defaults,...te.userItems,...te.projectItems].find(me=>me.id===Re.id))==null?void 0:se.parameters)??[]})(),onConfirm:te=>{De(void 0,void 0,Re.id,Re.subGroup,te),ze(null)},onCancel:()=>ze(null)}),Fe&&i.jsx(t1,{workflowName:"Command",confirmLabel:"Launch command",parameters:Fe.paramKeys.map((te,ae)=>({id:te,label:te,position:ae})),onConfirm:te=>{let ae=Fe.prompt;for(const[Ye,ct]of Object.entries(te))ae=ae.replaceAll(`{{${Ye}}}`,ct);const{agentMode:se,textareaContent:me,attachments:Ue}=Fe;se&&(L==null?void 0:L.mode)!==se&&Le.getState().switchMode(se);const He=me&&me.trim()?`${me.trim()}
316
316
 
317
- ${ae}`:ae;ce(He,Ue!=null&&Ue.length?Ue:void 0,{messageKind:"command",isSystemGenerated:!0}),Ie(),Ee(null)},onCancel:()=>Ee(null)})]}),b&&i.jsx(U$,{isOpen:b,onClose:()=>{j(!1),Gl(!0)},displayItems:K,onNavigate:je})]})}function H7(){var b;const[,e]=uo("/p/:projectId/s/:sessionId/readonly"),t=e==null?void 0:e.sessionId,[n,r]=E.useState(null),[a,l]=E.useState([]),[u,c]=E.useState(0),[d,h]=E.useState(!0),[p,m]=E.useState(null),x=async()=>{if(t){h(!0),m(null);try{const j=await ve(`/api/sessions/${t}?full=true`);if(!j.ok){m(`Failed to load session (${j.status})`),h(!1);return}const N=await j.json();r(N.session??null),l(N.messages??[]),c(N.hiddenCount??0)}catch(j){m(j instanceof Error?j.message:"Unknown error")}finally{h(!1)}}};E.useEffect(()=>{Ft.getState().getSettings([...sg])},[]),E.useEffect(()=>{x()},[t]);const{showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S}=Zi(),v=E.useMemo(()=>w2(a),[a]);return d?i.jsx("div",{className:"h-screen flex items-center justify-center bg-primary",children:i.jsx(pi,{})}):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(h2,{displayItems:v,showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S})}),i.jsx("div",{className:"h-8"})]})]})}function r1({isOpen:e,isRetry:t,onSubmit:n,onCancel:r}){const[a,l]=E.useState(""),u=E.useRef(null);E.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(jt,{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(ui,{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(rt,{type:"button",variant:"secondary",onClick:r,children:"Cancel"}),i.jsx(rt,{type:"submit",disabled:!a.trim(),children:t?"Try Again":"Connect"})]})]})})}function U7({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 F7({onNext:e}){const[t,n]=E.useState([]),[r,a]=E.useState([]),[l,u]=E.useState(!1),[c,d]=E.useState(null),[h,p]=E.useState(null),[m,x]=E.useState(null);E.useEffect(()=>{y()},[]);async function y(){try{const N=await ve("/api/providers");if(N.ok){const D=(await N.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(N){const T=N.id.startsWith("temp-"),D=r.some(M=>M.id===N.id),L=r.length===0&&c===null,O=_2(N);try{let M;if(T){const U=await ve("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!U.ok)throw new Error("Failed to create provider");const R=await U.json();M={...N,id:R.provider.id,model:null}}else{if(!(await ve(`/api/providers/${N.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)})).ok)throw new Error("Failed to update provider");M={...N,model:null}}const W=U=>U.some(R=>R.id===M.id)?U.map(R=>R.id===M.id?M:R):[...U,M];a(W),n(W),L&&!D&&e({providers:[M]})}catch{if(T){const M={...N,model:null};a(W=>[...W,M])}}}function C(){d(null),u(!0)}function _(N){d(N),u(!0)}function S(){u(!1),d(null)}function v(N){p(N),t.some(D=>D.id===N)?ve(`/api/providers/${N}`,{method:"DELETE"}).then(()=>{a(r.filter(D=>D.id!==N)),n(t.filter(D=>D.id!==N)),p(null)}).catch(()=>p(null)):(a(r.filter(D=>D.id!==N)),p(null))}function b(){const N=r.filter(T=>!T.id.startsWith("temp-"));e({providers:N})}const j=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(N=>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:g1(N.backend)}),i.jsx("span",{className:"text-text-primary font-medium",children:N.name}),i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${N.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:N.isLocal?"local":"api"})]}),i.jsx("p",{className:"text-text-muted text-sm mt-1 truncate",children:N.url}),N.model&&i.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",N.model]})]}),i.jsx("div",{className:"flex items-center gap-1",children:m===N.id?i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>v(N.id),disabled:h===N.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===N.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:()=>_(N),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(N.id),className:"p-2 text-text-muted hover:text-red-500 transition-colors",title:"Remove provider",children:i.jsx(ea,{})})]})})]},N.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(Xr,{className:"w-4 h-4"}),"Add Provider"]}),i.jsx("button",{onClick:b,disabled:!j,"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(S2,{isOpen:l,onClose:S,onSave:w,initialStep:1,editProvider:c??void 0})]})}function V7({onNext:e}){const[t,n]=E.useState(""),[r,a]=E.useState(!1);return E.useEffect(()=>{ve("/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(Td,{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 G7({onNext:e}){const[t,n]=E.useState(!1),[r,a]=E.useState("http://localhost:11434"),[l,u]=E.useState("qwen3.5:0.8b"),[c,d]=E.useState("ollama"),{copied:h,copy:p}=wk();E.useEffect(()=>{ve("/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(Mr,{className:"w-4 h-4 text-accent-primary"}):i.jsx(iT,{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 W7({onComplete:e}){const[t,n]=E.useState(1),[r,a]=E.useState(!1),[l,u]=E.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 ve("/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(rc,{onClick:e,className:"absolute top-4 right-4 p-2",variant:"modal",size:"xl"}),i.jsx(U7,{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(Xr,{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(F7,{onNext:c}),t===2&&i.jsx(V7,{onNext:d}),t===3&&i.jsx(G7,{onNext:h})]})})]})}function q7({projectId:e}){var p;const[,t]=Tn(),n=Le(m=>m.sessionsWithPendingConfirmations),r=Le(m=>{var x;return(x=m.currentSession)==null?void 0:x.id}),a=Le(m=>m.crossSessionConfirmations),l=Le(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(ag,{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 mp="openfox_updated_to",pp="update_pending";function K7(){const[e,t]=E.useState(!1),n=localStorage.getItem(mp),r=localStorage.getItem(pp);E.useEffect(()=>{if(!n||!r)return;const l=setTimeout(()=>{localStorage.removeItem(mp),localStorage.removeItem(pp),t(!0)},8e3);return()=>clearTimeout(l)},[n,r]);const a=()=>{localStorage.removeItem(mp),localStorage.removeItem(pp),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(Mr,{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(lg,{className:"w-3.5 h-3.5"})})]})}typeof window<"u"&&(Pt.getState().loadUserPresets(),Pt.getState().applySavedTheme());function ix(){return typeof window>"u"?!1:localStorage.getItem("openfox_token")!==null}function C2(){return i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx(pi,{})})}function Y7({sidebarOpen:e,onSidebarToggle:t}){const[,n]=uo("/p/:projectId"),r=n==null?void 0:n.projectId,a=Le(d=>d.connectionStatus),l=Gt(d=>d.currentProject),u=ix();return ZN({canLoad:a==="connected"||u,projectId:r,currentProjectId:l==null?void 0:l.id}),!l||l.id!==r?i.jsx(C2,{}):i.jsxs(i.Fragment,{children:[i.jsx(Bk,{projectId:r,isOpen:e,onClose:t}),i.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:i.jsx(_B,{})})]})}function X7({sidebarOpen:e,onSidebarToggle:t,rightSidebarOpen:n,onRightSidebarToggle:r}){const[,a]=uo("/p/:projectId/s/:sessionId"),l=a==null?void 0:a.projectId,u=a==null?void 0:a.sessionId,[,c]=Tn(),d=Le(C=>C.connectionStatus),h=Le(C=>C.currentSession),p=Le(C=>C.error),m=Le(C=>C.clearError),x=Gt(C=>C.currentProject),y=ix();return eT({canLoad:d==="connected"||y,projectId:l,sessionId:u,currentProjectId:x==null?void 0:x.id,currentSessionId:h==null?void 0:h.id}),E.useEffect(()=>{(p==null?void 0:p.code)==="NOT_FOUND"&&l&&(m(),c(`/p/${l}`))},[p,l,m,c]),!x||x.id!==l?i.jsx(C2,{}):i.jsxs(i.Fragment,{children:[i.jsx(Bk,{projectId:l,isOpen:e,onClose:t}),i.jsxs("div",{className:"flex-1 min-w-0 bg-primary flex flex-col",children:[i.jsx(q7,{projectId:l}),i.jsx(z7,{criteriaSidebarOpen:n,onCriteriaSidebarToggle:r})]})]})}function Q7(){const e=Xt(r=>r.fetchConfig),[,t]=Tn();async function n(){await e(),t("/")}return i.jsx("div",{className:"flex-1 overflow-y-auto",children:i.jsx(W7,{onComplete:n})})}function J7(){const{connectionStatus:e}=qN(),t=Xt(I=>I.fetchConfig),n=Xt(I=>I.refreshProviderModels),r=Xt(I=>I.providers),a=Xt(I=>I.activeProviderId),[,l]=Tn(),u=ix(),[c,d]=E.useState(!1);E.useEffect(()=>{(e==="connected"||u)&&t().then(()=>{d(!0),Ft.getState().getSettings([...sg,Te.DISPLAY_THEME,Te.DISPLAY_USER_PRESETS,Te.DISPLAY_CUSTOM_CSS,Te.KEYBINDINGS]),Dl.getState().fetchServers()})},[e,u,t]),E.useEffect(()=>{c&&a&&n(a).then(()=>{const I=Xt.getState().defaultModelSelection;(I?I.split("/")[0]:null)!==a&&t()})},[c,a,n,t]);const h=Ft(I=>I.settings);E.useEffect(()=>{c&&r.length===0&&l("/onboarding")},[c,r.length]),E.useEffect(()=>{const{applyPreset:I,applyTokens:B,setFollowSystemTheme:q,initSystemThemeListener:z}=Pt.getState(),ne=h[Te.DISPLAY_THEME],re=h[Te.DISPLAY_USER_PRESETS],Q=h[Te.DISPLAY_FOLLOW_SYSTEM_THEME];if(re&&localStorage.setItem("openfox:userPresets",re),ne){localStorage.setItem("openfox:theme",ne);try{const P=JSON.parse(ne);P.preset&&P.tokens?(I(P.preset),Pt.setState({basePreset:P.preset}),B(P.tokens)):P.preset?I(P.preset):P.tokens&&B(P.tokens)}catch{I("dark")}}else I("system");Q!==void 0&&Pt.getState().followSystemTheme!==(Q==="true")&&q(Q==="true");const K=z();return()=>K()},[h[Te.DISPLAY_THEME],h[Te.DISPLAY_USER_PRESETS]]),E.useEffect(()=>{const I=h[Te.DISPLAY_CUSTOM_CSS]??"";let B=document.getElementById("custom-css");B||(B=document.createElement("style"),B.id="custom-css",document.head.appendChild(B)),B.textContent=I},[h[Te.DISPLAY_CUSTOM_CSS]]);const[p,m]=E.useState(!1);E.useEffect(()=>{const I=Ft.getState().settings[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE];if(I===void 0||I==="false")return;let B=!1;if(localStorage.getItem("update_pending")==="true"&&(B=!0,localStorage.removeItem("update_pending")),c){const z=Xt.getState().version,ne=localStorage.getItem("openfox_last_version");z&&ne&&z!==ne&&(B=!0),localStorage.setItem("openfox_last_version",z??"")}B&&m(!0)},[h[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE],c]);const x=()=>{const I=localStorage.getItem("openfox:leftSidebar");return I!==null?I==="true":!0},y=()=>{const I=localStorage.getItem("openfox:rightSidebar");return I!==null?I==="true":!0},[w,C]=E.useState(x),[_,S]=E.useState(y),[v,b]=E.useState(!1),[j,N]=E.useState(!1),[T,D]=E.useState(!1),L=SN();E.useEffect(()=>{const I=()=>{D(window.innerWidth<768)};return I(),window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]);const[O]=Tn(),M=/^\/p\/[^/]+$/.test(O),W=T?v:M?!0:w,U=T?j:_,R=()=>{T?b(!v):C(!w)},H=()=>{T?N(!j):S(!_)};E.useEffect(()=>{T||localStorage.setItem("openfox:leftSidebar",String(w))},[w,T]),E.useEffect(()=>{T||localStorage.setItem("openfox:rightSidebar",String(_))},[_,T]),E.useEffect(()=>{(e==="connected"||u)&&t()},[e,t,u]);const G=Le(I=>I.showPasswordModal),V=Le(I=>I.passwordModalRetry),Z=Le(I=>I.submitPassword),X=Le(I=>I.cancelPassword),[$]=uo("/p/:projectId/s/:sessionId/readonly");return!$&&e!=="connected"&&!G&&!u?i.jsxs(i.Fragment,{children:[i.jsx(r1,{isOpen:!0,isRetry:V,onSubmit:Z,onCancel:X}),i.jsx("div",{className:"h-screen flex items-center justify-center",children:i.jsx(AT,{text:"Connecting to server..."})})]}):$?i.jsx(H7,{}):i.jsxs(i.Fragment,{children:[i.jsx(r1,{isOpen:G,isRetry:V,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(xB,{}),i.jsx(cB,{onMenuClick:R,onCriteriaToggle:H}),i.jsx("div",{className:"flex-1 flex overflow-hidden",children:i.jsxs(xN,{children:[i.jsx(cl,{path:"/onboarding",children:i.jsx(Q7,{})}),i.jsx(cl,{path:"/p/:projectId/s/:sessionId",children:i.jsx(X7,{sidebarOpen:W,onSidebarToggle:R,rightSidebarOpen:U,onRightSidebarToggle:H})}),i.jsx(cl,{path:"/p/:projectId/new",children:i.jsx(vB,{})}),i.jsx(cl,{path:"/p/:projectId",children:i.jsx(Y7,{sidebarOpen:W,onSidebarToggle:R})}),i.jsx(cl,{path:"/",children:i.jsx(bB,{})})]})})]}),i.jsx(K7,{}),i.jsx(Ck,{isOpen:p,onClose:()=>m(!1)})]})}XE.createRoot(document.getElementById("root")).render(i.jsx(ai.StrictMode,{children:i.jsx(h1,{base:m1,children:i.jsx(J7,{})})}));
317
+ ${ae}`:ae;ce(He,Ue!=null&&Ue.length?Ue:void 0,{messageKind:"command",isSystemGenerated:!0}),Ie(),Ee(null)},onCancel:()=>Ee(null)})]}),b&&i.jsx(U$,{isOpen:b,onClose:()=>{j(!1),Gl(!0)},displayItems:K,onNavigate:je})]})}function U7(){var b;const[,e]=uo("/p/:projectId/s/:sessionId/readonly"),t=e==null?void 0:e.sessionId,[n,r]=E.useState(null),[a,l]=E.useState([]),[u,c]=E.useState(0),[d,h]=E.useState(!0),[p,m]=E.useState(null),x=async()=>{if(t){h(!0),m(null);try{const j=await ve(`/api/sessions/${t}?full=true`);if(!j.ok){m(`Failed to load session (${j.status})`),h(!1);return}const N=await j.json();r(N.session??null),l(N.messages??[]),c(N.hiddenCount??0)}catch(j){m(j instanceof Error?j.message:"Unknown error")}finally{h(!1)}}};E.useEffect(()=>{Ft.getState().getSettings([...sg])},[]),E.useEffect(()=>{x()},[t]);const{showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S}=Zi(),v=E.useMemo(()=>wj(a),[a]);return d?i.jsx("div",{className:"h-screen flex items-center justify-center bg-primary",children:i.jsx(pi,{})}):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(hj,{displayItems:v,showThinking:y,showVerboseToolOutput:w,showStats:C,showAgentDefinitions:_,showWorkflowBars:S})}),i.jsx("div",{className:"h-8"})]})]})}function r1({isOpen:e,isRetry:t,onSubmit:n,onCancel:r}){const[a,l]=E.useState(""),u=E.useRef(null);E.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(jt,{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(ui,{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(rt,{type:"button",variant:"secondary",onClick:r,children:"Cancel"}),i.jsx(rt,{type:"submit",disabled:!a.trim(),children:t?"Try Again":"Connect"})]})]})})}function F7({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 V7({onNext:e}){const[t,n]=E.useState([]),[r,a]=E.useState([]),[l,u]=E.useState(!1),[c,d]=E.useState(null),[h,p]=E.useState(null),[m,x]=E.useState(null);E.useEffect(()=>{y()},[]);async function y(){try{const N=await ve("/api/providers");if(N.ok){const D=(await N.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(N){const T=N.id.startsWith("temp-"),D=r.some(M=>M.id===N.id),L=r.length===0&&c===null,O=_j(N);try{let M;if(T){const U=await ve("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!U.ok)throw new Error("Failed to create provider");const R=await U.json();M={...N,id:R.provider.id,model:null}}else{if(!(await ve(`/api/providers/${N.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)})).ok)throw new Error("Failed to update provider");M={...N,model:null}}const W=U=>U.some(R=>R.id===M.id)?U.map(R=>R.id===M.id?M:R):[...U,M];a(W),n(W),L&&!D&&e({providers:[M]})}catch{if(T){const M={...N,model:null};a(W=>[...W,M])}}}function C(){d(null),u(!0)}function _(N){d(N),u(!0)}function S(){u(!1),d(null)}function v(N){p(N),t.some(D=>D.id===N)?ve(`/api/providers/${N}`,{method:"DELETE"}).then(()=>{a(r.filter(D=>D.id!==N)),n(t.filter(D=>D.id!==N)),p(null)}).catch(()=>p(null)):(a(r.filter(D=>D.id!==N)),p(null))}function b(){const N=r.filter(T=>!T.id.startsWith("temp-"));e({providers:N})}const j=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(N=>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:g1(N.backend)}),i.jsx("span",{className:"text-text-primary font-medium",children:N.name}),i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${N.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:N.isLocal?"local":"api"})]}),i.jsx("p",{className:"text-text-muted text-sm mt-1 truncate",children:N.url}),N.model&&i.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",N.model]})]}),i.jsx("div",{className:"flex items-center gap-1",children:m===N.id?i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>v(N.id),disabled:h===N.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===N.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:()=>_(N),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(N.id),className:"p-2 text-text-muted hover:text-red-500 transition-colors",title:"Remove provider",children:i.jsx(ea,{})})]})})]},N.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(Xr,{className:"w-4 h-4"}),"Add Provider"]}),i.jsx("button",{onClick:b,disabled:!j,"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(Sj,{isOpen:l,onClose:S,onSave:w,initialStep:1,editProvider:c??void 0})]})}function G7({onNext:e}){const[t,n]=E.useState(""),[r,a]=E.useState(!1);return E.useEffect(()=>{ve("/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(Td,{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 W7({onNext:e}){const[t,n]=E.useState(!1),[r,a]=E.useState("http://localhost:11434"),[l,u]=E.useState("qwen3.5:0.8b"),[c,d]=E.useState("ollama"),{copied:h,copy:p}=wk();E.useEffect(()=>{ve("/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(Mr,{className:"w-4 h-4 text-accent-primary"}):i.jsx(iT,{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 q7({onComplete:e}){const[t,n]=E.useState(1),[r,a]=E.useState(!1),[l,u]=E.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 ve("/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(rc,{onClick:e,className:"absolute top-4 right-4 p-2",variant:"modal",size:"xl"}),i.jsx(F7,{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(Xr,{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(V7,{onNext:c}),t===2&&i.jsx(G7,{onNext:d}),t===3&&i.jsx(W7,{onNext:h})]})})]})}function K7({projectId:e}){var p;const[,t]=Tn(),n=Le(m=>m.sessionsWithPendingConfirmations),r=Le(m=>{var x;return(x=m.currentSession)==null?void 0:x.id}),a=Le(m=>m.crossSessionConfirmations),l=Le(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(ag,{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 mp="openfox_updated_to",pp="update_pending";function Y7(){const[e,t]=E.useState(!1),n=localStorage.getItem(mp),r=localStorage.getItem(pp);E.useEffect(()=>{if(!n||!r)return;const l=setTimeout(()=>{localStorage.removeItem(mp),localStorage.removeItem(pp),t(!0)},8e3);return()=>clearTimeout(l)},[n,r]);const a=()=>{localStorage.removeItem(mp),localStorage.removeItem(pp),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(Mr,{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(lg,{className:"w-3.5 h-3.5"})})]})}typeof window<"u"&&(Bt.getState().loadUserPresets(),Bt.getState().applySavedTheme());function ix(){return typeof window>"u"?!1:localStorage.getItem("openfox_token")!==null}function Cj(){return i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx(pi,{})})}function X7({sidebarOpen:e,onSidebarToggle:t}){const[,n]=uo("/p/:projectId"),r=n==null?void 0:n.projectId,a=Le(d=>d.connectionStatus),l=Gt(d=>d.currentProject),u=ix();return ZN({canLoad:a==="connected"||u,projectId:r,currentProjectId:l==null?void 0:l.id}),!l||l.id!==r?i.jsx(Cj,{}):i.jsxs(i.Fragment,{children:[i.jsx(Bk,{projectId:r,isOpen:e,onClose:t}),i.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:i.jsx(_B,{})})]})}function Q7({sidebarOpen:e,onSidebarToggle:t,rightSidebarOpen:n,onRightSidebarToggle:r}){const[,a]=uo("/p/:projectId/s/:sessionId"),l=a==null?void 0:a.projectId,u=a==null?void 0:a.sessionId,[,c]=Tn(),d=Le(C=>C.connectionStatus),h=Le(C=>C.currentSession),p=Le(C=>C.error),m=Le(C=>C.clearError),x=Gt(C=>C.currentProject),y=ix();return eT({canLoad:d==="connected"||y,projectId:l,sessionId:u,currentProjectId:x==null?void 0:x.id,currentSessionId:h==null?void 0:h.id}),E.useEffect(()=>{(p==null?void 0:p.code)==="NOT_FOUND"&&l&&(m(),c(`/p/${l}`))},[p,l,m,c]),!x||x.id!==l?i.jsx(Cj,{}):i.jsxs(i.Fragment,{children:[i.jsx(Bk,{projectId:l,isOpen:e,onClose:t}),i.jsxs("div",{className:"flex-1 min-w-0 bg-primary flex flex-col",children:[i.jsx(K7,{projectId:l}),i.jsx(H7,{criteriaSidebarOpen:n,onCriteriaSidebarToggle:r})]})]})}function J7(){const e=Xt(r=>r.fetchConfig),[,t]=Tn();async function n(){await e(),t("/")}return i.jsx("div",{className:"flex-1 overflow-y-auto",children:i.jsx(q7,{onComplete:n})})}function Z7(){const{connectionStatus:e}=qN(),t=Xt(I=>I.fetchConfig),n=Xt(I=>I.refreshProviderModels),r=Xt(I=>I.providers),a=Xt(I=>I.activeProviderId),[,l]=Tn(),u=ix(),[c,d]=E.useState(!1);E.useEffect(()=>{(e==="connected"||u)&&t().then(()=>{d(!0),Ft.getState().getSettings([...sg,Te.DISPLAY_THEME,Te.DISPLAY_USER_PRESETS,Te.DISPLAY_CUSTOM_CSS,Te.KEYBINDINGS]),Dl.getState().fetchServers()})},[e,u,t]),E.useEffect(()=>{c&&a&&n(a).then(()=>{const I=Xt.getState().defaultModelSelection;(I?I.split("/")[0]:null)!==a&&t()})},[c,a,n,t]);const h=Ft(I=>I.settings);E.useEffect(()=>{c&&r.length===0&&l("/onboarding")},[c,r.length]),E.useEffect(()=>{const{applyPreset:I,applyTokens:B,setFollowSystemTheme:q,initSystemThemeListener:z}=Bt.getState(),ne=h[Te.DISPLAY_THEME],re=h[Te.DISPLAY_USER_PRESETS],Q=h[Te.DISPLAY_FOLLOW_SYSTEM_THEME];if(re&&localStorage.setItem("openfox:userPresets",re),ne){localStorage.setItem("openfox:theme",ne);try{const P=JSON.parse(ne);P.preset&&P.tokens?(I(P.preset),Bt.setState({basePreset:P.preset}),B(P.tokens)):P.preset?I(P.preset):P.tokens&&B(P.tokens)}catch{I("dark")}}else I("system");Q!==void 0&&Bt.getState().followSystemTheme!==(Q==="true")&&q(Q==="true");const K=z();return()=>K()},[h[Te.DISPLAY_THEME],h[Te.DISPLAY_USER_PRESETS]]),E.useEffect(()=>{const I=h[Te.DISPLAY_CUSTOM_CSS]??"";let B=document.getElementById("custom-css");B||(B=document.createElement("style"),B.id="custom-css",document.head.appendChild(B)),B.textContent=I},[h[Te.DISPLAY_CUSTOM_CSS]]);const[p,m]=E.useState(!1);E.useEffect(()=>{const I=Ft.getState().settings[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE];if(I===void 0||I==="false")return;let B=!1;if(localStorage.getItem("update_pending")==="true"&&(B=!0,localStorage.removeItem("update_pending")),c){const z=Xt.getState().version,ne=localStorage.getItem("openfox_last_version");z&&ne&&z!==ne&&(B=!0),localStorage.setItem("openfox_last_version",z??"")}B&&m(!0)},[h[Te.DISPLAY_SHOW_CHANGELOG_ON_UPDATE],c]);const x=()=>{const I=localStorage.getItem("openfox:leftSidebar");return I!==null?I==="true":!0},y=()=>{const I=localStorage.getItem("openfox:rightSidebar");return I!==null?I==="true":!0},[w,C]=E.useState(x),[_,S]=E.useState(y),[v,b]=E.useState(!1),[j,N]=E.useState(!1),[T,D]=E.useState(!1),L=SN();E.useEffect(()=>{const I=()=>{D(window.innerWidth<768)};return I(),window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]);const[O]=Tn(),M=/^\/p\/[^/]+$/.test(O),W=T?v:M?!0:w,U=T?j:_,R=()=>{T?b(!v):C(!w)},H=()=>{T?N(!j):S(!_)};E.useEffect(()=>{T||localStorage.setItem("openfox:leftSidebar",String(w))},[w,T]),E.useEffect(()=>{T||localStorage.setItem("openfox:rightSidebar",String(_))},[_,T]),E.useEffect(()=>{(e==="connected"||u)&&t()},[e,t,u]);const G=Le(I=>I.showPasswordModal),V=Le(I=>I.passwordModalRetry),Z=Le(I=>I.submitPassword),X=Le(I=>I.cancelPassword),[$]=uo("/p/:projectId/s/:sessionId/readonly");return!$&&e!=="connected"&&!G&&!u?i.jsxs(i.Fragment,{children:[i.jsx(r1,{isOpen:!0,isRetry:V,onSubmit:Z,onCancel:X}),i.jsx("div",{className:"h-screen flex items-center justify-center",children:i.jsx(AT,{text:"Connecting to server..."})})]}):$?i.jsx(U7,{}):i.jsxs(i.Fragment,{children:[i.jsx(r1,{isOpen:G,isRetry:V,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(xB,{}),i.jsx(cB,{onMenuClick:R,onCriteriaToggle:H}),i.jsx("div",{className:"flex-1 flex overflow-hidden",children:i.jsxs(xN,{children:[i.jsx(cl,{path:"/onboarding",children:i.jsx(J7,{})}),i.jsx(cl,{path:"/p/:projectId/s/:sessionId",children:i.jsx(Q7,{sidebarOpen:W,onSidebarToggle:R,rightSidebarOpen:U,onRightSidebarToggle:H})}),i.jsx(cl,{path:"/p/:projectId/new",children:i.jsx(vB,{})}),i.jsx(cl,{path:"/p/:projectId",children:i.jsx(X7,{sidebarOpen:W,onSidebarToggle:R})}),i.jsx(cl,{path:"/",children:i.jsx(bB,{})})]})})]}),i.jsx(Y7,{}),i.jsx(Ck,{isOpen:p,onClose:()=>m(!1)})]})}XE.createRoot(document.getElementById("root")).render(i.jsx(ai.StrictMode,{children:i.jsx(h1,{base:m1,children:i.jsx(Z7,{})})}));