tide-commander 1.52.0 → 1.53.0

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 (36) hide show
  1. package/dist/assets/{BossLogsModal-Ymc3oi56.js → BossLogsModal-B9STSmb6.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-DnGG9qzz.js → BossSpawnModal-BYeEp5OI.js} +1 -1
  3. package/dist/assets/{ControlsModal-DRP1_rbW.js → ControlsModal-COpfbGtj.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-ko1qlvFd.js → DockerLogsModal-CwQx-3bW.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-B2ca-rLR.js → EmbeddedEditor-ehRGRrRs.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-BRoIudc6.js → GmailOAuthSetup-B_uaH1bN.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-CFu5df99.js → GoogleOAuthSetup-CNbkfN9l.js} +1 -1
  8. package/dist/assets/{IframeModal-CUUf2I-4.js → IframeModal-Cx0TmGPl.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-BUFdQGGO.js → IntegrationsPanel-sQyZpWqW.js} +2 -2
  10. package/dist/assets/{LogViewerModal-CXnvkEuC.js → LogViewerModal-pA33JkFl.js} +1 -1
  11. package/dist/assets/{MonitoringModal-myaLpP0P.js → MonitoringModal-Dw90UKnf.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-xYkfYrSr.js → PM2LogsModal-Bya_5RuS.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-DFk4VoA6.js → RestoreArchivedAreaModal-Dbc4G6uO.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-Gw6nYE44.js → Scene2DCanvas-VknyyTen.js} +1 -1
  15. package/dist/assets/{SceneManager-CeqztySP.js → SceneManager-BXqFLaeT.js} +1 -1
  16. package/dist/assets/{SkillsPanel-CocWkSNx.js → SkillsPanel-BrCcIF3N.js} +1 -1
  17. package/dist/assets/{SpawnModal-Bn3ZqlXN.js → SpawnModal-IkjbZFhe.js} +1 -1
  18. package/dist/assets/{SubordinateAssignmentModal-DhejKnmh.js → SubordinateAssignmentModal-fzxC42PS.js} +1 -1
  19. package/dist/assets/{TriggerManagerPanel-2TubwcF4.js → TriggerManagerPanel-D9zIVYkR.js} +1 -1
  20. package/dist/assets/{WorkflowEditorPanel-DvIqQCf4.js → WorkflowEditorPanel-CxAWtPcO.js} +1 -1
  21. package/dist/assets/{index-D-GeyVri.js → index-8bWbGeBs.js} +1 -1
  22. package/dist/assets/{index-iyddtr0v.js → index-BC1k8mon.js} +2 -2
  23. package/dist/assets/{index-D3rq1hsg.js → index-CDC9XyS8.js} +1 -1
  24. package/dist/assets/{index-C7D5bylg.js → index-CJXUPevi.js} +1 -1
  25. package/dist/assets/{index-D8ooZD2k.js → index-CMwlYuij.js} +3 -3
  26. package/dist/assets/{index-B4lXmEKE.js → index-Crfe-OV4.js} +1 -1
  27. package/dist/assets/{index-BafIwYn2.js → index-FrQm2j1t.js} +1 -1
  28. package/dist/assets/{index-W4C-3jYM.js → index-IvXUXoCa.js} +1 -1
  29. package/dist/assets/{main-5tHJV1Fa.js → main-9Cs_hNs-.js} +4 -4
  30. package/dist/assets/{main-CeP2eT5V.css → main-BhrN5Ajl.css} +1 -1
  31. package/dist/assets/{web-DYkyfUtH.js → web-BaEueqP3.js} +1 -1
  32. package/dist/assets/{web-Wkb7M9bi.js → web-C0QtHZck.js} +1 -1
  33. package/dist/index.html +2 -2
  34. package/dist/src/packages/server/routes/notifications.js +5 -1
  35. package/dist/src/packages/server/websocket/handlers/notification-handler.js +3 -1
  36. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-ponyfill-DZOWXZ4K.js","assets/vendor-react--Eh9ivFN.js","assets/index-iyddtr0v.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-Chj50gSY.js","assets/web-DYkyfUtH.js","assets/SceneManager-CeqztySP.js","assets/prism-cpp-CK2Ly5dS.js","assets/prism-java-CK6tws4L.js","assets/prism-csharp-ByDDDiWW.js","assets/prism-ruby-CQBUuZIF.js","assets/prism-php-Dt9698bA.js","assets/prism-scss-CeN16CFC.js","assets/prism-perl-UZfqnD51.js","assets/prism-haskell-Ce8aBmia.js","assets/prism-elixir-df27OMMQ.js","assets/xterm-6GBZ9nXN.css","assets/SpawnModal-Bn3ZqlXN.js","assets/BossSpawnModal-DnGG9qzz.js","assets/SubordinateAssignmentModal-DhejKnmh.js","assets/index-BafIwYn2.js","assets/index-Bykeknjl.css","assets/index-W4C-3jYM.js","assets/index-C7D5bylg.js","assets/index-D8ooZD2k.js","assets/index-D3rq1hsg.js","assets/ControlsModal-DRP1_rbW.js","assets/SkillsPanel-CocWkSNx.js","assets/RestoreArchivedAreaModal-DFk4VoA6.js","assets/IntegrationsPanel-BUFdQGGO.js","assets/MonitoringModal-myaLpP0P.js","assets/WorkflowEditorPanel-DvIqQCf4.js","assets/TriggerManagerPanel-2TubwcF4.js","assets/index-B4lXmEKE.js","assets/index-CprCD9du.css","assets/PM2LogsModal-xYkfYrSr.js","assets/LogViewerModal-CXnvkEuC.js","assets/DockerLogsModal-ko1qlvFd.js","assets/BossLogsModal-Ymc3oi56.js","assets/Scene2DCanvas-Gw6nYE44.js","assets/Scene2DCanvas-DwXbvB-b.css","assets/index-D-GeyVri.js","assets/index-BZyCMBzi.css","assets/IframeModal-CUUf2I-4.js","assets/IframeModal-DJkCGwT6.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-ponyfill-DZOWXZ4K.js","assets/vendor-react--Eh9ivFN.js","assets/index-BC1k8mon.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-Chj50gSY.js","assets/web-BaEueqP3.js","assets/SceneManager-BXqFLaeT.js","assets/prism-cpp-CK2Ly5dS.js","assets/prism-java-CK6tws4L.js","assets/prism-csharp-ByDDDiWW.js","assets/prism-ruby-CQBUuZIF.js","assets/prism-php-Dt9698bA.js","assets/prism-scss-CeN16CFC.js","assets/prism-perl-UZfqnD51.js","assets/prism-haskell-Ce8aBmia.js","assets/prism-elixir-df27OMMQ.js","assets/xterm-6GBZ9nXN.css","assets/SpawnModal-IkjbZFhe.js","assets/BossSpawnModal-BYeEp5OI.js","assets/SubordinateAssignmentModal-fzxC42PS.js","assets/index-FrQm2j1t.js","assets/index-Bykeknjl.css","assets/index-IvXUXoCa.js","assets/index-CJXUPevi.js","assets/index-CMwlYuij.js","assets/index-CDC9XyS8.js","assets/ControlsModal-COpfbGtj.js","assets/SkillsPanel-BrCcIF3N.js","assets/RestoreArchivedAreaModal-Dbc4G6uO.js","assets/IntegrationsPanel-sQyZpWqW.js","assets/MonitoringModal-Dw90UKnf.js","assets/WorkflowEditorPanel-CxAWtPcO.js","assets/TriggerManagerPanel-D9zIVYkR.js","assets/index-Crfe-OV4.js","assets/index-CprCD9du.css","assets/PM2LogsModal-Bya_5RuS.js","assets/LogViewerModal-pA33JkFl.js","assets/DockerLogsModal-CwQx-3bW.js","assets/BossLogsModal-B9STSmb6.js","assets/Scene2DCanvas-VknyyTen.js","assets/Scene2DCanvas-DwXbvB-b.css","assets/index-8bWbGeBs.js","assets/index-BZyCMBzi.css","assets/IframeModal-Cx0TmGPl.js","assets/IframeModal-DJkCGwT6.css"])))=>i.map(i=>d[i]);
2
2
  var AE=Object.defineProperty;var jE=(n,e,t)=>e in n?AE(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var et=(n,e,t)=>jE(n,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as Ub,g as Cu,a as _A,c as N0}from"./vendor-react--Eh9ivFN.js";import{T as NE,a as Qg,b as EA,L as MA,c as Qc,F as _f,M as rr,V as DA,C as Lr,d as sr,S as Dr,e as TE,P as _E,D as Xg,f as Ef,g as eo,I as EE,Q as RA,h as ME,O as OA,i as DE,j as RE,B as Xc,k as OE,l as LA,N as LE,m as PE,n as IE,o as Jg,p as PA,R as Zg,q as BE,r as FE,s as zE,t as bf,u as $E,v as Wb,w as IA,x as pl,y as HE,z as BA,A as UE,E as ul,G as WE,H as VE,J as qE,K as GE,U as Om,W as FA,X as YE,Y as KE,Z as QE,_ as XE,$ as JE,a0 as ZE,a1 as zA,a2 as eM,a3 as T0,a4 as _0,a5 as E0,a6 as M0,a7 as eb,a8 as tM,a9 as nM,aa as sM,ab as aM,ac as rM,ad as iM,ae as oM,af as lM,ag as cM,ah as uM,ai as dM,aj as fM}from"./vendor-three-Chj50gSY.js";function pM(n,e){for(var t=0;t<e.length;t++){const s=e[t];if(typeof s!="string"&&!Array.isArray(s)){for(const a in s)if(a!=="default"&&!(a in n)){const r=Object.getOwnPropertyDescriptor(s,a);r&&Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>s[a]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}var Lm={exports:{}},Ac={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
@@ -39,7 +39,7 @@ Error generating stack: `+g.message+`
39
39
  *
40
40
  * This source code is licensed under the MIT license found in the
41
41
  * LICENSE file in the root directory of this source tree.
42
- */var J0;function eD(){if(J0)return Um;J0=1;var n=Ub();function e(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var t=typeof Object.is=="function"?Object.is:e,s=n.useState,a=n.useEffect,r=n.useLayoutEffect,i=n.useDebugValue;function c(m,b){var y=b(),v=s({inst:{value:y,getSnapshot:b}}),S=v[0].inst,N=v[1];return r(function(){S.value=y,S.getSnapshot=b,d(S)&&N({inst:S})},[m,y,b]),a(function(){return d(S)&&N({inst:S}),m(function(){d(S)&&N({inst:S})})},[m]),i(y),y}function d(m){var b=m.getSnapshot;m=m.value;try{var y=b();return!t(m,y)}catch{return!0}}function f(m,b){return b()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return Um.useSyncExternalStore=n.useSyncExternalStore!==void 0?n.useSyncExternalStore:h,Um}var Z0;function tD(){return Z0||(Z0=1,Hm.exports=eD()),Hm.exports}var nD=tD();const sD=(n,e)=>{if(oo(e))return e;if(HM(e)&&oo(e.defaultValue))return e.defaultValue;if(typeof n=="function")return"";if(Array.isArray(n)){const t=n[n.length-1];return typeof t=="function"?"":t}return n},aD={t:sD,ready:!1},rD=()=>()=>{},ut=(n,e={})=>{var T,M,R;const{i18n:t}=e,{i18n:s,defaultNS:a}=x.useContext(JM)||{},r=t||s||QM();r&&!r.reportNamespaces&&(r.reportNamespaces=new ZM),r||nb(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=x.useMemo(()=>{var O;return{...YM(),...(O=r==null?void 0:r.options)==null?void 0:O.react,...e}},[r,e]),{useSuspense:c,keyPrefix:d}=i,f=n||a||((T=r==null?void 0:r.options)==null?void 0:T.defaultNS),h=oo(f)?[f]:f||["translation"],m=x.useMemo(()=>h,h);(R=(M=r==null?void 0:r.reportNamespaces)==null?void 0:M.addUsedNamespaces)==null||R.call(M,m);const b=x.useRef(0),y=x.useCallback(O=>{if(!r)return rD;const{bindI18n:U,bindI18nStore:H}=i,I=()=>{b.current+=1,O()};return U&&r.on(U,I),H&&r.store.on(H,I),()=>{U&&U.split(" ").forEach($=>r.off($,I)),H&&H.split(" ").forEach($=>r.store.off($,I))}},[r,i]),v=x.useRef(),S=x.useCallback(()=>{if(!r)return aD;const O=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(q=>$M(q,r,i)),U=e.lng||r.language,H=b.current,I=v.current;if(I&&I.ready===O&&I.lng===U&&I.keyPrefix===d&&I.revision===H)return I;const z={t:r.getFixedT(U,i.nsMode==="fallback"?m:m[0],d),ready:O,lng:U,keyPrefix:d,revision:H};return v.current=z,z},[r,m,d,i,e.lng]),[N,k]=x.useState(0),{t:C,ready:A}=nD.useSyncExternalStore(y,S,S);x.useEffect(()=>{if(r&&!A&&!c){const O=()=>k(U=>U+1);e.lng?X0(r,e.lng,m,O):sb(r,m,O)}},[r,e.lng,m,A,c,N]);const E=r||{},D=x.useRef(null),_=x.useRef(),F=O=>{const U=Object.getOwnPropertyDescriptors(O);U.__original&&delete U.__original;const H=Object.create(Object.getPrototypeOf(O),U);if(!Object.prototype.hasOwnProperty.call(H,"__original"))try{Object.defineProperty(H,"__original",{value:O,writable:!1,enumerable:!1,configurable:!1})}catch{}return H},P=x.useMemo(()=>{const O=E,U=O==null?void 0:O.language;let H=O;O&&(D.current&&D.current.__original===O?_.current!==U?(H=F(O),D.current=H,_.current=U):H=D.current:(H=F(O),D.current=H,_.current=U));const I=!A&&!c?(...z)=>(nb(r,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),C(...z)):C,$=[I,H,A];return $.t=I,$.i18n=H,$.ready=A,$},[C,E,A,E.resolvedLanguage,E.language,E.languages]);if(r&&c&&!A)throw new Promise(O=>{const U=()=>O();e.lng?X0(r,e.lng,m,U):sb(r,m,U)});return P};function rb(n){"@babel/helpers - typeof";return rb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rb(n)}function GA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":rb(XMLHttpRequest))==="object"}function iD(n){return!!n&&typeof n.then=="function"}function oD(n){return iD(n)?n:Promise.resolve(n)}var lD=/\{\{(.+?)\}\}/g;function ek(n,e){return n.replace(lD,function(t,s){var a=e[s.trim()];return a??t})}const cD="modulepreload",uD=function(n){return"/"+n},tk={},gt=function(e,t,s){let a=Promise.resolve();if(t&&t.length>0){let i=function(f){return Promise.all(f.map(h=>Promise.resolve(h).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=i(t.map(f=>{if(f=uD(f),f in tk)return;tk[f]=!0;const h=f.endsWith(".css"),m=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const b=document.createElement("link");if(b.rel=h?"stylesheet":cD,h||(b.as="script"),b.crossOrigin="",b.href=f,d&&b.setAttribute("nonce",d),document.head.appendChild(b),h)return new Promise((y,v)=>{b.addEventListener("load",y),b.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${f}`)))})}))}function r(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&r(c.reason);return e().catch(r)})};function nk(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(n,a).enumerable})),t.push.apply(t,s)}return t}function sk(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?nk(Object(t),!0).forEach(function(s){dD(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):nk(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function dD(n,e,t){return(e=fD(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function fD(n){var e=pD(n,"string");return lo(e)=="symbol"?e:e+""}function pD(n,e){if(lo(n)!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(lo(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function lo(n){"@babel/helpers - typeof";return lo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lo(n)}var Ci=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Ci=global.fetch:typeof window<"u"&&window.fetch&&(Ci=window.fetch);var du;GA()&&(typeof global<"u"&&global.XMLHttpRequest?du=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(du=window.XMLHttpRequest));var Of;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Of=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Of=window.ActiveXObject));typeof Ci!="function"&&(Ci=void 0);if(!Ci&&!du&&!Of)try{gt(()=>import("./browser-ponyfill-DZOWXZ4K.js").then(n=>n.b),__vite__mapDeps([0,1])).then(function(n){Ci=n.default}).catch(function(){})}catch{}var ib=function(e,t){if(t&&lo(t)==="object"){var s="";for(var a in t)s+="&"+encodeURIComponent(a)+"="+encodeURIComponent(t[a]);if(!s)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+s.slice(1)}return e},ak=function(e,t,s,a){var r=function(d){if(!d.ok)return s(d.statusText||"Error",{status:d.status});d.text().then(function(f){s(null,{status:d.status,data:f})}).catch(s)};if(a){var i=a(e,t);if(i instanceof Promise){i.then(r).catch(s);return}}typeof fetch=="function"?fetch(e,t).then(r).catch(s):Ci(e,t).then(r).catch(s)},rk=!1,hD=function(e,t,s,a){e.queryStringParams&&(t=ib(t,e.queryStringParams));var r=sk({},typeof e.customHeaders=="function"?e.customHeaders():e.customHeaders);typeof window>"u"&&typeof global<"u"&&typeof global.process<"u"&&global.process.versions&&global.process.versions.node&&(r["User-Agent"]="i18next-http-backend (node/".concat(global.process.version,"; ").concat(global.process.platform," ").concat(global.process.arch,")")),s&&(r["Content-Type"]="application/json");var i=typeof e.requestOptions=="function"?e.requestOptions(s):e.requestOptions,c=sk({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},rk?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{ak(t,c,a,d)}catch(f){if(!i||Object.keys(i).length===0||!f.message||f.message.indexOf("not implemented")<0)return a(f);try{Object.keys(i).forEach(function(h){delete c[h]}),ak(t,c,a,d),rk=!0}catch(h){a(h)}}},mD=function(e,t,s,a){s&&lo(s)==="object"&&(s=ib("",s).slice(1)),e.queryStringParams&&(t=ib(t,e.queryStringParams));try{var r=du?new du:new Of("MSXML2.XMLHTTP.3.0");r.open(s?"POST":"GET",t,1),e.crossDomain||r.setRequestHeader("X-Requested-With","XMLHttpRequest"),r.withCredentials=!!e.withCredentials,s&&r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.overrideMimeType&&r.overrideMimeType("application/json");var i=e.customHeaders;if(i=typeof i=="function"?i():i,i)for(var c in i)r.setRequestHeader(c,i[c]);r.onreadystatechange=function(){r.readyState>3&&a(r.status>=400?r.statusText:null,{status:r.status,data:r.responseText})},r.send(s)}catch(d){console&&console.log(d)}},gD=function(e,t,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Ci&&t.indexOf("file:")!==0)return hD(e,t,s,a);if(GA()||typeof ActiveXObject=="function")return mD(e,t,s,a);a(new Error("No fetch and no xhr implementation found!"))};function wl(n){"@babel/helpers - typeof";return wl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wl(n)}function ik(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(n,a).enumerable})),t.push.apply(t,s)}return t}function Wm(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ik(Object(t),!0).forEach(function(s){YA(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):ik(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function bD(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function xD(n,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(n,KA(s.key),s)}}function yD(n,e,t){return e&&xD(n.prototype,e),Object.defineProperty(n,"prototype",{writable:!1}),n}function YA(n,e,t){return(e=KA(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function KA(n){var e=vD(n,"string");return wl(e)=="symbol"?e:e+""}function vD(n,e){if(wl(n)!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(wl(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(n)}var wD=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(t){return JSON.parse(t)},stringify:JSON.stringify,parsePayload:function(t,s,a){return YA({},s,a||"")},parseLoadPayload:function(t,s){},request:gD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},QA=(function(){function n(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};bD(this,n),this.services=e,this.options=t,this.allOptions=s,this.type="backend",this.init(e,t,s)}return yD(n,[{key:"init",value:function(t){var s=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.services=t,this.options=Wm(Wm(Wm({},wD()),this.options||{}),a),this.allOptions=r,this.services&&this.options.reloadInterval){var i=setInterval(function(){return s.reload()},this.options.reloadInterval);wl(i)==="object"&&typeof i.unref=="function"&&i.unref()}}},{key:"readMulti",value:function(t,s,a){this._readAny(t,t,s,s,a)}},{key:"read",value:function(t,s,a){this._readAny([t],t,[s],s,a)}},{key:"_readAny",value:function(t,s,a,r,i){var c=this,d=this.options.loadPath;typeof this.options.loadPath=="function"&&(d=this.options.loadPath(t,a)),d=oD(d),d.then(function(f){if(!f)return i(null,{});var h=ek(f,{lng:t.join("+"),ns:a.join("+")});c.loadUrl(h,i,s,r)})}},{key:"loadUrl",value:function(t,s,a,r){var i=this,c=typeof a=="string"?[a]:a,d=typeof r=="string"?[r]:r,f=this.options.parseLoadPayload(c,d);this.options.request(this.options,t,f,function(h,m){if(m&&(m.status>=500&&m.status<600||!m.status))return s("failed loading "+t+"; status code: "+m.status,!0);if(m&&m.status>=400&&m.status<500)return s("failed loading "+t+"; status code: "+m.status,!1);if(!m&&h&&h.message){var b=h.message.toLowerCase(),y=["failed","fetch","network","load"].find(function(N){return b.indexOf(N)>-1});if(y)return s("failed loading "+t+": "+h.message,!0)}if(h)return s(h,!1);var v,S;try{typeof m.data=="string"?v=i.options.parse(m.data,a,r):v=m.data}catch{S="failed parsing "+t+" to json"}if(S)return s(S,!1);s(null,v)})}},{key:"create",value:function(t,s,a,r,i){var c=this;if(this.options.addPath){typeof t=="string"&&(t=[t]);var d=this.options.parsePayload(s,a,r),f=0,h=[],m=[];t.forEach(function(b){var y=c.options.addPath;typeof c.options.addPath=="function"&&(y=c.options.addPath(b,s));var v=ek(y,{lng:b,ns:s});c.options.request(c.options,v,d,function(S,N){f+=1,h.push(S),m.push(N),f===t.length&&typeof i=="function"&&i(h,m)})})}}},{key:"reload",value:function(){var t=this,s=this.services,a=s.backendConnector,r=s.languageUtils,i=s.logger,c=a.language;if(!(c&&c.toLowerCase()==="cimode")){var d=[],f=function(m){var b=r.toResolveHierarchy(m);b.forEach(function(y){d.indexOf(y)<0&&d.push(y)})};f(c),this.allOptions.preload&&this.allOptions.preload.forEach(function(h){return f(h)}),d.forEach(function(h){t.allOptions.ns.forEach(function(m){a.read(h,m,"read",null,null,function(b,y){b&&i.warn("loading namespace ".concat(m," for language ").concat(h," failed"),b),!b&&y&&i.log("loaded namespace ".concat(m," for language ").concat(h),y),a.loaded("".concat(h,"|").concat(m),b,y)})})})}}}])})();QA.type="backend";const{slice:kD,forEach:SD}=[];function CD(n){return SD.call(kD.call(arguments,1),e=>{if(e)for(const t in e)n[t]===void 0&&(n[t]=e[t])}),n}function AD(n){return typeof n!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(t=>t.test(n))}const ok=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,jD=function(n,e){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let r=`${n}=${a}`;if(s.maxAge>0){const i=s.maxAge-0;if(Number.isNaN(i))throw new Error("maxAge should be a Number");r+=`; Max-Age=${Math.floor(i)}`}if(s.domain){if(!ok.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!ok.test(s.path))throw new TypeError("option path is invalid");r+=`; Path=${s.path}`}if(s.expires){if(typeof s.expires.toUTCString!="function")throw new TypeError("option expires is invalid");r+=`; Expires=${s.expires.toUTCString()}`}if(s.httpOnly&&(r+="; HttpOnly"),s.secure&&(r+="; Secure"),s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:r+="; SameSite=Strict";break;case"lax":r+="; SameSite=Lax";break;case"strict":r+="; SameSite=Strict";break;case"none":r+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s.partitioned&&(r+="; Partitioned"),r},lk={create(n,e,t,s){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+t*60*1e3)),s&&(a.domain=s),document.cookie=jD(n,e,a)},read(n){const e=`${n}=`,t=document.cookie.split(";");for(let s=0;s<t.length;s++){let a=t[s];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(e)===0)return a.substring(e.length,a.length)}return null},remove(n,e){this.create(n,"",-1,e)}};var ND={name:"cookie",lookup(n){let{lookupCookie:e}=n;if(e&&typeof document<"u")return lk.read(e)||void 0},cacheUserLanguage(n,e){let{lookupCookie:t,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;t&&typeof document<"u"&&lk.create(t,n,s,a,r)}},TD={name:"querystring",lookup(n){var s;let{lookupQuerystring:e}=n,t;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&((s=window.location.hash)==null?void 0:s.indexOf("?"))>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const i=a.substring(1).split("&");for(let c=0;c<i.length;c++){const d=i[c].indexOf("=");d>0&&i[c].substring(0,d)===e&&(t=i[c].substring(d+1))}}return t}},_D={name:"hash",lookup(n){var a;let{lookupHash:e,lookupFromHashIndex:t}=n,s;if(typeof window<"u"){const{hash:r}=window.location;if(r&&r.length>2){const i=r.substring(1);if(e){const c=i.split("&");for(let d=0;d<c.length;d++){const f=c[d].indexOf("=");f>0&&c[d].substring(0,f)===e&&(s=c[d].substring(f+1))}}if(s)return s;if(!s&&t>-1){const c=r.match(/\/([a-zA-Z-]*)/g);return Array.isArray(c)?(a=c[typeof t=="number"?t:0])==null?void 0:a.replace("/",""):void 0}}}return s}};let tl=null;const ck=()=>{if(tl!==null)return tl;try{if(tl=typeof window<"u"&&window.localStorage!==null,!tl)return!1;const n="i18next.translate.boo";window.localStorage.setItem(n,"foo"),window.localStorage.removeItem(n)}catch{tl=!1}return tl};var ED={name:"localStorage",lookup(n){let{lookupLocalStorage:e}=n;if(e&&ck())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupLocalStorage:t}=e;t&&ck()&&window.localStorage.setItem(t,n)}};let nl=null;const uk=()=>{if(nl!==null)return nl;try{if(nl=typeof window<"u"&&window.sessionStorage!==null,!nl)return!1;const n="i18next.translate.boo";window.sessionStorage.setItem(n,"foo"),window.sessionStorage.removeItem(n)}catch{nl=!1}return nl};var MD={name:"sessionStorage",lookup(n){let{lookupSessionStorage:e}=n;if(e&&uk())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupSessionStorage:t}=e;t&&uk()&&window.sessionStorage.setItem(t,n)}},DD={name:"navigator",lookup(n){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:s,language:a}=navigator;if(t)for(let r=0;r<t.length;r++)e.push(t[r]);s&&e.push(s),a&&e.push(a)}return e.length>0?e:void 0}},RD={name:"htmlTag",lookup(n){let{htmlTag:e}=n,t;const s=e||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(t=s.getAttribute("lang")),t}},OD={name:"path",lookup(n){var a;let{lookupFromPathIndex:e}=n;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(a=t[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},LD={name:"subdomain",lookup(n){var a,r;let{lookupFromSubdomainIndex:e}=n;const t=typeof e=="number"?e+1:1,s=typeof window<"u"&&((r=(a=window.location)==null?void 0:a.hostname)==null?void 0:r.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(s)return s[t]}};let XA=!1;try{document.cookie,XA=!0}catch{}const JA=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];XA||JA.splice(1,1);const PD=()=>({order:JA,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:n=>n});class ZA{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=CD(t,this.options||{},PD()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=s,this.addDetector(ND),this.addDetector(TD),this.addDetector(ED),this.addDetector(MD),this.addDetector(DD),this.addDetector(RD),this.addDetector(OD),this.addDetector(LD),this.addDetector(_D)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(s=>{if(this.detectors[s]){let a=this.detectors[s].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(t=t.concat(a))}}),t=t.filter(s=>s!=null&&!AD(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(e,this.options)}))}}ZA.type="languageDetector";const Lf={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},ob={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},WV=["#4a9eff","#4aff9e","#ff9e4a","#ff4a9e","#9e4aff","#ff4a4a","#4affff","#ffff4a","#4ad7ff","#00e6a8","#ff6b4a","#ff66cc","#b84aff","#ff4a7a","#00d9ff","#e6ff4a","#1a3a6e","#1a5e3a","#6e3a1a","#6e1a4a","#4a1a6e","#6e1a1a","#1a5e5e","#5e5e1a","#1a4a6e","#145a47","#6e2c1a","#6e1a5e","#3b1a6e","#6e1a33","#14566e","#4f5e1a"],Wd={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function Vb(n){const t=Math.floor((Date.now()-n)/1e3)/60;return t<1?Wd.recent:t<5?Wd.short:t<30?Wd.medium:Wd.long}function qb(n){return Lf[n]??Lf.default}let xf=null;function ej(){if(!xf)try{xf=globalThis.__i18n}catch{}return xf}function ID(n){xf=n}function BD(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":n.toString()}function FD(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":n.toString()}function zD(n){var a;const e=ej(),t=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),s=Math.floor((Date.now()-n)/1e3);return s<60?t?t("common:time.seconds",{count:s}):`${s}s`:s<3600?t?t("common:time.minutes",{count:Math.floor(s/60)}):`${Math.floor(s/60)}m`:s<86400?t?t("common:time.hours",{count:Math.floor(s/3600)}):`${Math.floor(s/3600)}h`:t?t("common:time.days",{count:Math.floor(s/86400)}):`${Math.floor(s/86400)}d`}function fp(n){var f;const e=ej(),t=(f=e==null?void 0:e.t)==null?void 0:f.bind(e),s=Math.floor((Date.now()-n)/1e3);if(s<5)return t?t("common:time.justNow"):"just now";if(s<60)return t?t("common:time.secondsAgo",{count:s}):`${s}s ago`;const a=Math.floor(s/60);if(a<60){const h=s%60;return h>0?t?t("common:time.minutesSecondsAgo",{minutes:a,seconds:h}):`${a}m ${h}s ago`:t?t("common:time.minutesAgo",{count:a}):`${a}m ago`}const r=Math.floor(a/60),i=a%60;if(r<24)return i>0?t?t("common:time.hoursMinutesAgo",{hours:r,minutes:i}):`${r}h ${i}m ago`:t?t("common:time.hoursAgo",{count:r}):`${r}h ago`;const c=Math.floor(r/24),d=r%24;return d>0?t?t("common:time.daysHoursAgo",{days:c,hours:d}):`${c}d ${d}h ago`:t?t("common:time.daysAgo",{count:c}):`${c}d ago`}function tj(n,e){return n?e?n.replace(/\s*\(?\s*~?\$[\d,.]+\s*\)?/g,"").replace(/\s*cost[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*price[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*\(~?\$[\d,.]+\s*(?:USD|cost|spent)?\)/gi,"").replace(/\s*-\s*~?\$[\d,.]+\s*$/g,"").replace(/[^\S\n]+/g," ").trim():n:""}const $D=Date.now();Sn.use(QA).use(ZA).use(XM).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:`/locales/{{lng}}/{{ns}}.json?v=${$D}`},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{ID(Sn)});const dt={CONFIG:"tide-commander-config",SHOW_FPS:"tide-show-fps",SETTINGS:"tide-settings",SHORTCUTS:"tide-shortcuts",MOUSE_CONTROLS:"tide-mouse-controls",BACKEND_URL:"tide-backend-url",AUTH_TOKEN:"tide-auth-token",SCENE_VIEW_MODE:"tide-scene-view-mode",CAMERA_STATE:"tide-camera-state",CAMERA_STATE_2D:"tide-camera-state-2d",VIEW_MODE:"guake-view-mode",ADVANCED_VIEW:"guake-advanced-view",TERMINAL_HEIGHT:"guake-terminal-height",TERMINAL_FULLSCREEN:"guake-terminal-fullscreen",INPUT_TEXT_PREFIX:"guake-input-",PASTED_TEXTS_PREFIX:"guake-pasted-",COMMANDER_TAB:"commander-active-tab",COMMANDER_FILTERS:"commander-filters",LAST_CWD:"tide-last-cwd",MOBILE_VIEW:"tide-mobile-view",TREE_PANEL_WIDTH:"tide-tree-panel-width",MOBILE_TREE_PANEL_HEIGHT:"tide-mobile-tree-panel-height",AGENT_ORDER:"tide-agent-order",AOP_CONFIG:"tide-aop-config",AOP_OPEN:"tide-aop-open",AOP_TRACKING_BOARD_VISIBLE:"tide-aop-tracking-board-visible",MOBILE_OVERVIEW_HEIGHT:"tide-mobile-overview-height",SPLIT_PANE_AGENT_IDS:"tide-split-pane-agent-ids",SPLIT_PANE_ORIENTATION:"tide-split-pane-orientation",GIT_PANEL_OPEN:"guake-git-panel-open",GIT_PANEL_MODE:"guake-git-panel-mode",GIT_PANEL_VIEW_MODE:"guake-git-view-mode",GIT_PANEL_FOLDER_IDX:"guake-git-folder-idx",BUILDINGS_PANEL_OPEN:"guake-buildings-panel-open",WORKFLOW_PANEL_OPEN:"guake-workflow-panel-open",SIDE_PANEL_WIDTH:"guake-side-panel-width",UNSEEN_AGENTS:"tide-unseen-agents",PENDING_MESSAGES:"tide-pending-messages"},lb="tide-backend-url-change";function ea(n,e){try{const t=localStorage.getItem(n);return t===null?e:JSON.parse(t)}catch{return e}}function ka(n,e=""){try{return localStorage.getItem(n)??e}catch{return e}}function hl(n,e=!1){try{const t=localStorage.getItem(n);return t===null?e:t==="true"}catch{return e}}function Gb(n,e){try{const t=localStorage.getItem(n);if(t===null)return e;const s=Number(t);return isNaN(s)?e:s}catch{return e}}function wa(n,e){try{localStorage.setItem(n,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function er(n,e){try{localStorage.setItem(n,e)}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function to(n,e){try{localStorage.setItem(n,String(e))}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function Yb(n,e){try{localStorage.setItem(n,String(e))}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function dk(n){try{localStorage.removeItem(n)}catch(e){console.error(`Failed to remove from localStorage: ${n}`,e)}}function ra(){const n=Kb();return n?n.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ir(){return ka(dt.AUTH_TOKEN,"")}function Kb(){return ka(dt.BACKEND_URL,"")}function HD(n){const e=n.trim();er(dt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(lb,{detail:e}))}function UD(n){if(typeof window>"u")return()=>{};const e=s=>{n(s.detail)},t=s=>{s.key===dt.BACKEND_URL&&n(s.newValue??"")};return window.addEventListener(lb,e),window.addEventListener("storage",t),()=>{window.removeEventListener(lb,e),window.removeEventListener("storage",t)}}function Et(n){return`${ra()}${n}`}async function Lt(n,e){const t=Ir(),s=new Headers(e==null?void 0:e.headers);return t&&s.set("X-Auth-Token",t),fetch(n,{...e,headers:s,cache:"no-store"})}function fu(n){const e=Ir();if(!e)return n;try{const t=!n.startsWith("http://")&&!n.startsWith("https://"),s=t?"http://dummy":void 0,a=new URL(n,s);return a.searchParams.set("token",e),t?a.pathname+a.search:a.toString()}catch{const t=n.includes("?")?"&":"?";return`${n}${t}token=${encodeURIComponent(e)}`}}function xs(n=!1,e){const[t,s]=x.useState(n),[a,r]=x.useState(e),i=x.useCallback(f=>{f!==void 0&&r(f),s(!0)},[]),c=x.useCallback(()=>{s(!1)},[]),d=x.useCallback(()=>{s(f=>!f)},[]);return{isOpen:t,data:a,open:i,close:c,toggle:d,setData:r}}function WD(){const[n,e]=x.useState(null),t=x.useCallback(a=>{e(a)},[]),s=x.useCallback(()=>{e(null)},[]);return{isOpen:n!==null,id:n,open:t,close:s}}function VD(){const[n,e]=x.useState(!1),[t,s]=x.useState({x:0,y:0}),[a,r]=x.useState({x:0,z:0}),[i,c]=x.useState({type:"ground"}),d=x.useCallback((h,m,b)=>{s(h),r(m),c(b),e(!0)},[]),f=x.useCallback(()=>{e(!1)},[]);return{isOpen:n,screenPosition:t,worldPosition:a,target:i,open:d,close:f}}const ta=[],qD=new Set;function Pf(){qD.forEach(n=>n())}function GD(n,e){const t=ta.findIndex(s=>s.id===n);return t!==-1&&ta.splice(t,1),ta.push({id:n,close:e}),Pf(),()=>{const s=ta.findIndex(a=>a.id===n);s!==-1&&(ta.splice(s,1),Pf())}}function yf(){return ta.length===0?!1:(ta.pop().close(),Pf(),!0)}function YD(n){const e=ta.findIndex(t=>t.id===n);return e===-1?!1:e<ta.length-1}function KD(...n){const e=new Set(n);for(;ta.length>0;){const t=ta[ta.length-1];if(e.has(t.id))break;ta.pop().close()}Pf()}function Jt(n,e,t){const s=x.useRef(t);s.current=t,x.useEffect(()=>e?GD(n,()=>s.current()):void 0,[n,e])}const pu=5,Vm={0:0,1:4,2:8,3:14,4:25,5:50};let eu=null,fk=!1;async function QD(){if(fk)return eu;fk=!0;try{const n=await gt(()=>import("./index-iyddtr0v.js"),__vite__mapDeps([2,3,1,4]));eu={Haptics:n.Haptics,ImpactStyle:n.ImpactStyle}}catch{}return eu}QD();function If(n){const e=Math.round(n),t=e<=0?0:e>=pu?pu:e;if(t!==0){if(eu){const{Haptics:s,ImpactStyle:a}=eu;if(t<=2&&typeof s.selectionChanged=="function"){s.selectionChanged().catch(()=>{navigator.vibrate&&navigator.vibrate(Vm[t])});return}const i={3:"Light",4:"Medium",5:"Heavy"}[t];if(i&&a[i]){s.impact({style:a[i]}).catch(()=>{navigator.vibrate&&navigator.vibrate(Vm[t])});return}}navigator.vibrate&&navigator.vibrate(Vm[t])}}function pk(n,e){const{threshold:t=80,maxVerticalMovement:s=50,enabled:a=!0,onSwipeLeft:r,onSwipeRight:i,onSwipeMove:c,onSwipeCancel:d,vibrationIntensity:f=1}=e,h=x.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=x.useCallback(S=>{if(S.touches.length!==1)return;const N=S.touches[0];h.current={startX:N.clientX,startY:N.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),b=x.useCallback(S=>{if(!h.current.isTracking||S.touches.length!==1)return;const N=S.touches[0],k=N.clientX-h.current.startX;if(Math.abs(N.clientY-h.current.startY)>s){h.current.isTracking=!1,h.current.hasMovedEnough&&(d==null||d());return}const E=window.innerWidth*.4,D=Math.max(-1,Math.min(1,k/E));Math.abs(k)>=12&&(h.current.hasMovedEnough=!0,c==null||c(D))},[s,c,d]),y=x.useCallback(S=>{const N=h.current.isTracking,k=h.current.hasMovedEnough;if(!N)return;const C=S.changedTouches[0],A=C.clientX-h.current.startX,E=Math.abs(C.clientY-h.current.startY),D=Date.now()-h.current.startTime;h.current.isTracking=!1,h.current.hasMovedEnough=!1,Math.abs(A)>=t&&E<=s&&D<500?(If(f),A>0?i==null||i():r==null||r()):k&&(d==null||d())},[t,s,f,r,i,d]),v=x.useCallback(()=>{const S=h.current.hasMovedEnough;h.current.isTracking=!1,h.current.hasMovedEnough=!1,S&&(d==null||d())},[d]);x.useEffect(()=>{const S=n.current;if(!(!S||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return S.addEventListener("touchstart",m,{passive:!0}),S.addEventListener("touchmove",b,{passive:!0}),S.addEventListener("touchend",y,{passive:!0}),S.addEventListener("touchcancel",v,{passive:!0}),()=>{S.removeEventListener("touchstart",m),S.removeEventListener("touchmove",b),S.removeEventListener("touchend",y),S.removeEventListener("touchcancel",v)}},[n,a,m,b,y,v])}const hk=8,XD=.93,mk=.4;function JD(n){const{gestureRef:e,agentListRef:t,enabled:s,onSelect:a}=n,[r,i]=x.useState(!1),[c,d]=x.useState(null),f=x.useRef(!1),h=x.useRef(null),m=x.useRef(a);m.current=a;const b=x.useCallback(()=>{if(f.current)return;f.current=!0,i(!0);const N=t.current;if(N){const k=Math.round(N.clientHeight/2);N.style.paddingTop=`${k}px`,N.style.paddingBottom=`${k}px`}},[t]),y=x.useCallback(()=>{f.current=!1,h.current=null,i(!1),d(null);const N=t.current;N&&(N.style.paddingTop="",N.style.paddingBottom="")},[t]),v=x.useCallback(N=>{const k=t.current;if(!k)return;k.scrollTop+=N;const C=k.getBoundingClientRect(),A=C.top+C.height/2,E=C.left+C.width/2,D=document.elementFromPoint(E,A);let _=null;if(D){const F=D.closest("[data-agent-id]");F&&k.contains(F)&&(_=F.dataset.agentId)}if(_!==h.current&&(h.current=_,d(_),_)){const F=W.getState().settings.vibrationIntensity??1;If(F)}},[t]),S=x.useCallback(()=>{const N=h.current;if(N){const k=W.getState().settings.vibrationIntensity??1,C=k<=0?0:Math.min(k+1,pu);If(C),m.current(N)}y()},[y]);return x.useEffect(()=>{const N=e.current;if(!N||!s)return;const k=N.style.touchAction;N.style.touchAction="none";let C=!1,A=!1,E=0,D=0,_=0,F=0,P=0,T=0,M=0,R=0;const O=()=>{M&&(cancelAnimationFrame(M),M=0)},U=()=>{if(Math.abs(T)<mk){T=0;return}N.scrollTop+=T,T*=XD,M=requestAnimationFrame(U)},H=q=>{if(O(),q.touches.length>=2){q.preventDefault(),C=!1,A=!1,R=(q.touches[0].clientY+q.touches[1].clientY)/2,b(),v(0);return}C=!0,A=!1,E=q.touches[0].clientX,D=q.touches[0].clientY,_=N.scrollTop,F=D,P=performance.now(),T=0},I=q=>{if(q.touches.length>=2){if(q.preventDefault(),(A||C)&&(A=!1,C=!1),!f.current){R=(q.touches[0].clientY+q.touches[1].clientY)/2,b(),v(0);return}const G=(q.touches[0].clientY+q.touches[1].clientY)/2,te=R-G;R=G,v(te);return}if(f.current&&q.touches.length===1){q.preventDefault();const G=q.touches[0].clientY,te=R-G;R=G,v(te);return}if(!C&&!A)return;const Y=q.touches[0].clientX,B=q.touches[0].clientY;if(C&&!A){const G=Math.abs(Y-E),te=Math.abs(B-D);if(G<hk&&te<hk)return;if(te>=G)A=!0,C=!1,q.preventDefault();else{C=!1;return}}if(A){q.preventDefault();const G=performance.now(),te=G-P;N.scrollTop=_+(D-B),te>0&&(T=(F-B)/te*16),F=B,P=G}},$=q=>{if(f.current&&q.touches.length===0){S();return}f.current||(A||C)&&q.touches.length===0&&(A&&Math.abs(T)>mk&&(M=requestAnimationFrame(U)),A=!1,C=!1)},z=()=>{A=!1,C=!1,O(),f.current&&y()};return N.addEventListener("touchstart",H,{passive:!1}),N.addEventListener("touchmove",I,{passive:!1}),N.addEventListener("touchend",$,{passive:!0}),N.addEventListener("touchcancel",z,{passive:!0}),()=>{N.removeEventListener("touchstart",H),N.removeEventListener("touchmove",I),N.removeEventListener("touchend",$),N.removeEventListener("touchcancel",z),N.style.touchAction=k,O();const q=t.current;q&&(q.style.paddingTop="",q.style.paddingBottom="")}},[e,t,s,b,y,v,S]),{isActive:r,hoveredAgentId:c}}function Tc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class ZD{constructor(){et(this,"messages",new Map);et(this,"logs",[]);et(this,"maxMessagesPerAgent",200);et(this,"maxLogs",500);et(this,"enabled",!0);et(this,"listeners",new Set);et(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,t){try{const s=JSON.parse(t);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${t.length}B`),this.addMessage(e,{id:Tc(),agentId:e,direction:"sent",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:t.length,raw:t})}catch(s){console.error("[AgentDebugger] Failed to parse SENT message:",String(s).slice(0,80)),this.addMessage(e,{id:Tc(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:t.length,raw:t})}}captureReceived(e,t){try{const s=JSON.parse(t);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${t.length}B`),this.addMessage(e,{id:Tc(),agentId:e,direction:"received",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:t.length,raw:t})}catch(s){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(s).slice(0,80)),this.addMessage(e,{id:Tc(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:t.length,raw:t})}}addMessage(e,t){let s=this.messages.get(e);s||(s=[],this.messages.set(e,s)),s.push(t),console.log(`[AgentDebugger] Added message for ${e}, total: ${s.length}, type: ${t.type}, direction: ${t.direction}`),s.length>this.maxMessagesPerAgent&&s.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const t=this.getMessages(e),s=t.filter(i=>i.direction==="sent").length,a=t.filter(i=>i.direction==="received").length,r=[...new Set(t.map(i=>i.type))];return{total:t.length,sent:s,received:a,messageTypes:r}}clearMessages(e){this.messages.delete(e),this.notifyListeners(e)}clearAllMessages(){this.messages.clear(),this.notifyListeners("all")}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){this.listeners.forEach(t=>t(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,t,s,a){const r={id:Tc(),level:e,message:t,data:s,timestamp:Date.now(),source:a};this.logs.push(r),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,t,s){this.log("debug",e,t,s)}info(e,t,s){this.log("info",e,t,s)}warn(e,t,s){this.log("warn",e,t,s)}error(e,t,s){this.log("error",e,t,s)}getLogs(){return this.logs}clearLogs(){this.logs=[],this.notifyLogListeners()}subscribeLogs(e){return this.logListeners.add(e),()=>this.logListeners.delete(e)}notifyLogListeners(){this.logListeners.forEach(e=>e())}}const ps=new ZD,hu={debug:(n,e,t)=>ps.debug(n,e,t),info:(n,e,t)=>ps.info(n,e,t),warn:(n,e,t)=>ps.warn(n,e,t),error:(n,e,t)=>ps.error(n,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var kl;(function(n){n.Unimplemented="UNIMPLEMENTED",n.Unavailable="UNAVAILABLE"})(kl||(kl={}));class qm extends Error{constructor(e,t,s){super(e),this.message=e,this.code=t,this.data=s}}const eR=n=>{var e,t;return n!=null&&n.androidBridge?"android":!((t=(e=n==null?void 0:n.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},tR=n=>{const e=n.CapacitorCustomPlatform||null,t=n.Capacitor||{},s=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:eR(n),r=()=>a()!=="web",i=m=>{const b=f.get(m);return!!(b!=null&&b.platforms.has(a())||c(m))},c=m=>{var b;return(b=t.PluginHeaders)===null||b===void 0?void 0:b.find(y=>y.name===m)},d=m=>n.console.error(m),f=new Map,h=(m,b={})=>{const y=f.get(m);if(y)return console.warn(`Capacitor plugin "${m}" already registered. Cannot register plugins twice.`),y.proxy;const v=a(),S=c(m);let N;const k=async()=>(!N&&v in b?N=typeof b[v]=="function"?N=await b[v]():N=b[v]:e!==null&&!N&&"web"in b&&(N=typeof b.web=="function"?N=await b.web():N=b.web),N),C=(P,T)=>{var M,R;if(S){const O=S==null?void 0:S.methods.find(U=>T===U.name);if(O)return O.rtype==="promise"?U=>t.nativePromise(m,T.toString(),U):(U,H)=>t.nativeCallback(m,T.toString(),U,H);if(P)return(M=P[T])===null||M===void 0?void 0:M.bind(P)}else{if(P)return(R=P[T])===null||R===void 0?void 0:R.bind(P);throw new qm(`"${m}" plugin is not implemented on ${v}`,kl.Unimplemented)}},A=P=>{let T;const M=(...R)=>{const O=k().then(U=>{const H=C(U,P);if(H){const I=H(...R);return T=I==null?void 0:I.remove,I}else throw new qm(`"${m}.${P}()" is not implemented on ${v}`,kl.Unimplemented)});return P==="addListener"&&(O.remove=async()=>T()),O};return M.toString=()=>`${P.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:P,writable:!1,configurable:!1}),M},E=A("addListener"),D=A("removeListener"),_=(P,T)=>{const M=E({eventName:P},T),R=async()=>{const U=await M;D({eventName:P,callbackId:U},T)},O=new Promise(U=>M.then(()=>U({remove:R})));return O.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},O},F=new Proxy({},{get(P,T){switch(T){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return S?_:E;case"removeListener":return D;default:return A(T)}}});return s[m]=F,f.set(m,{name:m,proxy:F,platforms:new Set([...Object.keys(b),...S?[v]:[]])}),F};return t.convertFileSrc||(t.convertFileSrc=m=>m),t.getPlatform=a,t.handleError=d,t.isNativePlatform=r,t.isPluginAvailable=i,t.registerPlugin=h,t.Exception=qm,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},nR=n=>n.Capacitor=tR(n),Bf=nR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Au=Bf.registerPlugin;class Qb{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let s=!1;this.listeners[e]||(this.listeners[e]=[],s=!0),this.listeners[e].push(t);const r=this.windowListeners[e];r&&!r.registered&&this.addWindowListener(r),s&&this.sendRetainedArgumentsForEvent(e);const i=async()=>this.removeListener(e,t);return Promise.resolve({remove:i})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,s){const a=this.listeners[e];if(!a){if(s){let r=this.retainedEventArguments[e];r||(r=[]),r.push(t),this.retainedEventArguments[e]=r}return}a.forEach(r=>r(t))}hasListeners(e){var t;return!!(!((t=this.listeners[e])===null||t===void 0)&&t.length)}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:s=>{this.notifyListeners(t,s)}}}unimplemented(e="not implemented"){return new Bf.Exception(e,kl.Unimplemented)}unavailable(e="not available"){return new Bf.Exception(e,kl.Unavailable)}async removeListener(e,t){const s=this.listeners[e];if(!s)return;const a=s.indexOf(t);this.listeners[e].splice(a,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(s=>{this.notifyListeners(e,s)}))}}const gk=n=>encodeURIComponent(n).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),bk=n=>n.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class sR extends Qb{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach(s=>{if(s.length<=0)return;let[a,r]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=bk(a).trim(),r=bk(r).trim(),t[a]=r}),t}async setCookie(e){try{const t=gk(e.key),s=gk(e.value),a=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",r=(e.path||"/").replace("path=",""),i=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${s||""}${a}; path=${r}; ${i};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}Au("CapacitorCookies",{web:()=>new sR});const aR=async n=>new Promise((e,t)=>{const s=new FileReader;s.onload=()=>{const a=s.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},s.onerror=a=>t(a),s.readAsDataURL(n)}),rR=(n={})=>{const e=Object.keys(n);return Object.keys(n).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=n[e[i]],a),{})},iR=(n,e=!0)=>n?Object.entries(n).reduce((s,a)=>{const[r,i]=a;let c,d;return Array.isArray(i)?(d="",i.forEach(f=>{c=e?encodeURIComponent(f):f,d+=`${r}=${c}&`}),d.slice(0,-1)):(c=e?encodeURIComponent(i):i,d=`${r}=${c}`),`${s}&${d}`},"").substr(1):null,oR=(n,e={})=>{const t=Object.assign({method:n.method||"GET",headers:n.headers},e),a=rR(n.headers)["content-type"]||"";if(typeof n.data=="string")t.body=n.data;else if(a.includes("application/x-www-form-urlencoded")){const r=new URLSearchParams;for(const[i,c]of Object.entries(n.data||{}))r.set(i,c);t.body=r.toString()}else if(a.includes("multipart/form-data")||n.data instanceof FormData){const r=new FormData;if(n.data instanceof FormData)n.data.forEach((c,d)=>{r.append(d,c)});else for(const c of Object.keys(n.data))r.append(c,n.data[c]);t.body=r;const i=new Headers(t.headers);i.delete("content-type"),t.headers=i}else(a.includes("application/json")||typeof n.data=="object")&&(t.body=JSON.stringify(n.data));return t};class lR extends Qb{async request(e){const t=oR(e,e.webFetchExtra),s=iR(e.params,e.shouldEncodeUrlParams),a=s?`${e.url}?${s}`:e.url,r=await fetch(a,t),i=r.headers.get("content-type")||"";let{responseType:c="text"}=r.ok?e:{};i.includes("application/json")&&(c="json");let d,f;switch(c){case"arraybuffer":case"blob":f=await r.blob(),d=await aR(f);break;case"json":d=await r.json();break;case"document":case"text":default:d=await r.text()}const h={};return r.headers.forEach((m,b)=>{h[b]=m}),{data:d,headers:h,status:r.status,url:r.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}const VV=Au("CapacitorHttp",{web:()=>new lR});var xk;(function(n){n.Dark="DARK",n.Light="LIGHT",n.Default="DEFAULT"})(xk||(xk={}));var yk;(function(n){n.StatusBar="StatusBar",n.NavigationBar="NavigationBar"})(yk||(yk={}));class cR extends Qb{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}Au("SystemBars",{web:()=>new cR});var vk;(function(n){n[n.Sunday=1]="Sunday",n[n.Monday=2]="Monday",n[n.Tuesday=3]="Tuesday",n[n.Wednesday=4]="Wednesday",n[n.Thursday=5]="Thursday",n[n.Friday=6]="Friday",n[n.Saturday=7]="Saturday"})(vk||(vk={}));const Xb=Au("LocalNotifications",{web:()=>gt(()=>import("./web-DYkyfUtH.js"),__vite__mapDeps([5,3,1,4])).then(n=>new n.LocalNotificationsWeb)}),uR=Au("ServerConfig");let dR=100;const fR="agent_alerts",cb="tide-notification-tap";function pR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function nj(n){if(pR()){W.openTerminalOnMobile(n);return}if(document.querySelector(".commander-overlay")){W.requestCommanderExpand(n);return}W.selectAgent(n),W.setTerminalOpen(!0)}function ju(){try{return Bf.isNativePlatform()}catch{return!1}}async function hR(){if(ju())try{const n=await Xb.requestPermissions();return console.log("[Notifications] Permission result:",n.display),n.display==="granted"}catch(n){return console.error("[Notifications] Failed to request permissions:",n),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function mR(n){const{title:e,body:t,icon:s,data:a}=n;if(ju())try{const r=dR++;console.log("[Notifications] Scheduling native notification id="+r,e),await Xb.schedule({notifications:[{id:r,title:e,body:t,extra:a,channelId:fR,smallIcon:"ic_launcher",autoCancel:!0}]}),console.log("[Notifications] Notification scheduled successfully")}catch(r){console.error("[Notifications] Failed to schedule notification:",r)}else if("Notification"in window&&Notification.permission==="granted"){const r=new Notification(e,{body:t,icon:s,data:a});r.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(cb,{detail:a}))}}}let Gm=!1;async function gR(n){const e=[];if(Gm)return()=>{};if(Gm=!0,n){const t=s=>{const a=s;a.detail&&n(a.detail)};window.addEventListener(cb,t),e.push(()=>window.removeEventListener(cb,t))}if(ju())try{const t=await Xb.addListener("localNotificationActionPerformed",s=>{n&&s.notification.extra&&n(s.notification.extra)});e.push(()=>t.remove())}catch(t){console.error("[Notifications] Failed to add tap listener:",t)}return()=>{e.forEach(t=>t()),Gm=!1}}function bR(n,e){ju()&&uR.syncConfig({url:n,token:e}).catch(t=>{console.warn("[Notifications] Failed to sync config to native service:",t)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const pp=()=>window.__tideWsState.ws,wk=n=>{window.__tideWsState.ws=n},xR=()=>window.__tideWsState.isConnecting,_c=n=>{window.__tideWsState.isConnecting=n},ub=()=>window.__tideWsState.reconnectAttempts,db=n=>{window.__tideWsState.reconnectAttempts=n},sj=()=>window.__tideWsState.reconnectTimeout,aj=n=>{window.__tideWsState.reconnectTimeout=n},kk=10,Jb="tide_ws_has_connected";function Sk(){return sessionStorage.getItem(Jb)==="true"}function yR(n){sessionStorage.setItem(Jb,"true")}function vR(){sessionStorage.removeItem(Jb)}let rj=null;const wR=n=>{rj=n},Ck=()=>rj,Pe={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function ij(n){n.onToast&&(Pe.onToast=n.onToast),n.onAgentCreated&&(Pe.onAgentCreated=n.onAgentCreated),n.onAgentUpdated&&(Pe.onAgentUpdated=n.onAgentUpdated),n.onAgentDeleted&&(Pe.onAgentDeleted=n.onAgentDeleted),n.onAgentsSync&&(Pe.onAgentsSync=n.onAgentsSync),n.onAreasSync&&(Pe.onAreasSync=n.onAreasSync),n.onSpawnError&&(Pe.onSpawnError=n.onSpawnError),n.onSpawnSuccess&&(Pe.onSpawnSuccess=n.onSpawnSuccess),n.onToolUse&&(Pe.onToolUse=n.onToolUse),n.onDirectoryNotFound&&(Pe.onDirectoryNotFound=n.onDirectoryNotFound),n.onDelegation&&(Pe.onDelegation=n.onDelegation),n.onCustomClassesSync&&(Pe.onCustomClassesSync=n.onCustomClassesSync),n.onReconnect&&(Pe.onReconnect=n.onReconnect),n.onAgentNotification&&(Pe.onAgentNotification=n.onAgentNotification),n.onBuildingUpdated&&(Pe.onBuildingUpdated=n.onBuildingUpdated),n.onSubagentStarted&&(Pe.onSubagentStarted=n.onSubagentStarted),n.onSubagentCompleted&&(Pe.onSubagentCompleted=n.onSubagentCompleted)}function kR(){Pe.onToast=null,Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onSpawnError=null,Pe.onSpawnSuccess=null,Pe.onToolUse=null,Pe.onDirectoryNotFound=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onReconnect=null,Pe.onAgentNotification=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}function SR(){Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onToolUse=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onBuildingUpdated=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}const Vd=new Map,CR=new Map,fb={start(n){},end(n){},async measure(n,e){this.start(n);try{return await e()}finally{this.end(n)}},measureSync(n,e){this.start(n);try{return e()}finally{this.end(n)}},getMetrics(n){const e={},t=n?Vd.has(n)?[[n,Vd.get(n)]]:[]:Array.from(Vd.entries());for(const[s,a]of t){const r=[...a.samples].sort((f,h)=>f-h),i=Math.floor(r.length*.5),c=Math.floor(r.length*.95),d=Math.floor(r.length*.99);e[s]={count:a.count,avgMs:a.totalMs/a.count,minMs:a.minMs,maxMs:a.maxMs,lastMs:a.lastMs,p50Ms:r[i]||0,p95Ms:r[c]||0,p99Ms:r[d]||0}}return e},clear(){Vd.clear(),CR.clear()},report(){}};class AR{constructor(){et(this,"frames",[]);et(this,"lastFrameTime",0);et(this,"frameCount",0);et(this,"fps",0);et(this,"minFps",1/0);et(this,"maxFps",0);et(this,"fpsHistory",[]);et(this,"maxHistorySize",60)}tick(e=200){const t=performance.now();if(this.lastFrameTime>0){const s=t-this.lastFrameTime;s<e&&(this.frames.push(s),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=t,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((t,s)=>t+s,0)/this.frames.length;this.fps=1e3/e,this.minFps=Math.min(this.minFps,this.fps),this.maxFps=Math.max(this.maxFps,this.fps),this.fpsHistory.push(this.fps),this.fpsHistory.length>this.maxHistorySize&&this.fpsHistory.shift()}getFPS(){return Math.round(this.fps)}getStats(){const e=this.fpsHistory.length>0?this.fpsHistory.reduce((t,s)=>t+s,0)/this.fpsHistory.length:this.fps;return{current:Math.round(this.fps),min:Math.round(this.minFps===1/0?0:this.minFps),max:Math.round(this.maxFps),avg:Math.round(e)}}reset(){this.frames=[],this.lastFrameTime=0,this.frameCount=0,this.fps=0,this.minFps=1/0,this.maxFps=0,this.fpsHistory=[]}}const qd=new AR;class jR{constructor(){et(this,"snapshots",[]);et(this,"maxSnapshots",120);et(this,"intervalId",null);et(this,"leakThresholdMB",50);et(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const t=this.getUsage();t&&(this.baselineUsedMB=t.usedMB),this.intervalId=setInterval(()=>{this.takeSnapshot()},e),console.log("[Memory] Monitoring started. Use memory.report() to see analysis.")}stopMonitoring(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.log("[Memory] Monitoring stopped."))}takeSnapshot(){const e=this.getUsage();if(!e)return;const t={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(t),this.snapshots.length>this.maxSnapshots&&this.snapshots.shift();const s=e.usedMB-this.baselineUsedMB;s>this.leakThresholdMB&&console.warn(`[Memory] Warning: Heap grew by ${s}MB since monitoring started (baseline: ${this.baselineUsedMB}MB, current: ${e.usedMB}MB)`)}getGrowthRate(){if(this.snapshots.length<10)return null;const e=this.snapshots[0],t=this.snapshots[this.snapshots.length-1],s=(t.timestamp-e.timestamp)/1e3/60;return s<.1?null:(t.heapUsedMB-e.heapUsedMB)/s}report(){const e=this.getUsage();if(!e){console.log("[Memory] Memory API not available (Chrome only)");return}console.group("%c[Memory Report]","color: #ff6600; font-weight: bold"),console.log(`Current: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`),console.log(`Baseline: ${this.baselineUsedMB}MB`),console.log(`Growth: ${e.usedMB-this.baselineUsedMB}MB since monitoring started`);const t=this.getGrowthRate();if(t!==null&&(console.log(`Growth Rate: ${t.toFixed(2)}MB/min`),t>5&&console.warn("POTENTIAL MEMORY LEAK: Growth rate exceeds 5MB/min")),this.snapshots.length>1){const s=Math.min(...this.snapshots.map(r=>r.heapUsedMB)),a=Math.max(...this.snapshots.map(r=>r.heapUsedMB));console.log(`Range: ${s}MB - ${a}MB (${a-s}MB variance)`)}console.groupEnd()}getThreeJsInfo(e){var t;return(t=e==null?void 0:e.info)!=null&&t.memory?{geometries:e.info.memory.geometries,textures:e.info.memory.textures}:null}reset(){this.snapshots=[];const e=this.getUsage();e&&(this.baselineUsedMB=e.usedMB),console.log("[Memory] Reset. New baseline:",this.baselineUsedMB,"MB")}}const Ec=new jR;function pb(n,e,t,s,a,r){}function oj(n,e){x.useRef(0),x.useEffect(()=>{},[n,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}const hb=dt.PENDING_MESSAGES,NR=300*1e3;function lj(){try{const n=localStorage.getItem(hb);if(!n)return[];const e=JSON.parse(n),t=Date.now();return e.filter(s=>t-s.queuedAt<NR)}catch{return[]}}function cj(n){try{n.length===0?localStorage.removeItem(hb):localStorage.setItem(hb,JSON.stringify(n))}catch{}}function Gd(n){const e=lj();e.push({message:n,queuedAt:Date.now()}),cj(e)}function TR(){var s;const n=lj();if(n.length===0)return 0;let e=0;const t=[];for(const a of n)_R(a.message)?e++:t.push(a);if(cj(t),e>0){const a=e===1?"queued message":"queued messages";(s=Pe.onToast)==null||s.call(Pe,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function Zb(n){if(n.payload&&typeof n.payload=="object"){const e=n.payload;if(e.agentId)return e.agentId;if(e.parentAgentId)return e.parentAgentId;if(e.bossId)return e.bossId;if(e.id)return e.id}return null}function _R(n){const e=pp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const t=JSON.stringify(n),s=Zb(n);return console.log("[AgentDebugger] SENT - type:",n.type,"agentId:",s,"payload:",n.payload),s&&ps.captureSent(s,t),e.send(t),!0}catch{return!1}}function ex(n){var t,s,a,r,i,c,d,f,h,m;const e=pp();if(!e)return(t=Ck())==null||t(),n.type==="send_command"?(Gd(n),(s=Pe.onToast)==null||s.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=Pe.onToast)==null||a.call(Pe,"error","Not Connected","Connecting to server... Please try again in a moment."),!1;if(e.readyState!==WebSocket.OPEN)return e.readyState===WebSocket.CONNECTING?n.type==="send_command"?(Gd(n),(r=Pe.onToast)==null||r.call(Pe,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=Pe.onToast)==null||i.call(Pe,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Ck())==null||c(),n.type==="send_command"?(Gd(n),(d=Pe.onToast)==null||d.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=Pe.onToast)==null||f.call(Pe,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const b=JSON.stringify(n),y=Zb(n);return console.log("[AgentDebugger] SENT - type:",n.type,"agentId:",y,"payload:",n.payload),y&&ps.captureSent(y,b),e.send(b),!0}catch(b){return n.type==="send_command"?(Gd(n),(h=Pe.onToast)==null||h.call(Pe,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=Pe.onToast)==null||m.call(Pe,"error","Send Failed",`Failed to send message: ${b}`),!1}}const qc=new Set,ER=5e3;function Ak(n){if(!n.isDetached||!n.sessionId){qc.delete(n.id);return}qc.has(n.id)||(qc.add(n.id),ex({type:"reattach_agent",payload:{agentId:n.id}}),setTimeout(()=>{qc.delete(n.id)},ER))}function MR(n){var e,t,s,a,r,i,c,d,f,h,m,b,y,v,S,N,k,C,A,E,D,_,F,P;switch(fb.start(`ws:${n.type}`),n.type){case"agents_update":{const T=n.payload,M=T.filter(R=>R.class==="boss"||R.isBoss);M.length>0&&console.log("[WS agents_update] Boss agents received:",M.map(R=>({id:R.id,name:R.name,subordinateIds:R.subordinateIds}))),W.setAgents(T),(e=Pe.onAgentsSync)==null||e.call(Pe,T),W.loadToolHistory();for(const R of T)Ak(R);break}case"agent_created":{const T=n.payload;console.log("[WebSocket] Agent created:",T),W.addAgent(T);const M=(t=window.__spawnModalAreaContext)==null?void 0:t.areaId;M&&(W.assignAgentToArea(T.id,M),window.__spawnModalAreaContext=null),W.selectAgent(T.id),(s=Pe.onAgentCreated)==null||s.call(Pe,T),(a=Pe.onSpawnSuccess)==null||a.call(Pe),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=Pe.onToast)==null||r.call(Pe,"success","Agent Deployed",`${T.name} is ready for commands`);break}case"agent_updated":{const T=n.payload,R=W.getState().agents.get(T.id),O=(R==null?void 0:R.status)!==T.status;console.log(`[Tide] Agent updated: ${T.name} (${T.id}) status=${T.status} (was ${R==null?void 0:R.status})${O?" ⚡ STATUS CHANGED":""}`),O&&console.log(`[Tide] 🔔 Status change for ${T.name}: ${R==null?void 0:R.status} → ${T.status}`),O&&(R==null?void 0:R.status)==="working"&&T.status==="idle"&&W.triggerHistoryRefresh(T.id);const U=R?R.position.x!==T.position.x||R.position.z!==T.position.z:!1;W.updateAgent(T),Ak(T),(i=Pe.onAgentUpdated)==null||i.call(Pe,T,U);break}case"agent_deleted":{const{id:T}=n.payload;qc.delete(T),W.removeAgent(T),(c=Pe.onAgentDeleted)==null||c.call(Pe,T);break}case"activity":{const T=n.payload;W.addActivity(T);break}case"event":{const T=n.payload;if(hu.debug(`Event: ${T.type}`,{agentId:T.agentId,toolName:T.toolName},"ws:event"),T.type==="tool_start"&&T.toolName&&((d=Pe.onToolUse)==null||d.call(Pe,T.agentId,T.toolName,T.toolInput),W.addToolExecution(T.agentId,T.toolName,T.toolInput),T.toolInput)){const M=T.toolInput.file_path||T.toolInput.path;M&&(T.toolName==="Write"?W.addFileChange(T.agentId,"created",M):T.toolName==="Edit"?W.addFileChange(T.agentId,"modified",M):T.toolName==="Read"&&W.addFileChange(T.agentId,"read",M))}break}case"output":{const T=n.payload;hu.debug(`Output: "${T.text.slice(0,80)}..."`,{agentId:T.agentId,isStreaming:T.isStreaming,length:T.text.length,hasSkillUpdate:!!T.skillUpdate,uuid:T.uuid,toolName:T.toolName},"ws:output"),W.addOutput(T.agentId,{text:T.text,isStreaming:T.isStreaming,timestamp:T.timestamp,isDelegation:T.isDelegation,skillUpdate:T.skillUpdate,subagentName:T.subagentName,uuid:T.uuid,toolName:T.toolName,toolInput:T.toolInput,toolOutput:T.toolOutput});break}case"context_stats":{const{agentId:T,stats:M}=n.payload;console.log(`[Tide] Received context stats for agent ${T}: ${M.usedPercent}% used`),W.updateAgentContextStats(T,M);break}case"context_update":{const{agentId:T,contextUsed:M,contextLimit:R}=n.payload;W.updateAgentContext(T,M,R);break}case"compacting_status":{const{agentId:T,active:M}=n.payload;W.setAgentCompacting(T,M);break}case"error":{const T=n.payload;console.error("[WebSocket] Error from server:",T.message),(f=Pe.onToast)==null||f.call(Pe,"error","Error",T.message),(h=Pe.onSpawnError)==null||h.call(Pe),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:T}=n.payload;console.log("[WebSocket] Directory not found:",T),(m=Pe.onDirectoryNotFound)==null||m.call(Pe,T),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(T));break}case"command_started":{const{agentId:T,command:M}=n.payload,R=M.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;W.addUserPromptToOutput(T,M);break}case"session_updated":{const{agentId:T}=n.payload;W.loadToolHistory(),W.triggerHistoryRefresh(T);const M=W.getState().agents.get(T);M&&W.updateAgent({...M});break}case"areas_update":{const T=n.payload;W.setAreasFromServer(T),(b=Pe.onAreasSync)==null||b.call(Pe);break}case"buildings_update":{const T=n.payload;W.setBuildingsFromServer(T);break}case"building_created":{const T=n.payload;W.addBuilding(T);break}case"building_updated":{const T=n.payload;W.updateBuildingFromServer(T),(y=Pe.onBuildingUpdated)==null||y.call(Pe,T);break}case"building_deleted":{const{id:T}=n.payload;W.removeBuildingFromServer(T);break}case"building_logs":{const{buildingId:T,logs:M}=n.payload;W.addBuildingLogs(T,M);break}case"pm2_logs_chunk":{const{buildingId:T,chunk:M}=n.payload;W.appendStreamingLogChunk(T,M);break}case"pm2_logs_streaming":{const{buildingId:T,streaming:M}=n.payload;W.setStreamingStatus(T,M);break}case"docker_logs_chunk":{const{buildingId:T,chunk:M}=n.payload;W.appendStreamingLogChunk(T,M);break}case"docker_logs_streaming":{const{buildingId:T,streaming:M}=n.payload;W.setStreamingStatus(T,M);break}case"docker_containers_list":{const{containers:T,composeProjects:M}=n.payload;console.log(`[WebSocket] Received ${T.length} containers, ${M.length} compose projects`),W.setDockerContainersList(T,M);break}case"boss_building_logs_chunk":{const{bossBuildingId:T,subordinateBuildingId:M,subordinateBuildingName:R,chunk:O,isError:U}=n.payload;W.appendBossStreamingLogChunk(T,M,R,O,U);break}case"boss_building_subordinates_updated":{const{bossBuildingId:T,subordinateBuildingIds:M}=n.payload;W.updateBuilding(T,{subordinateBuildingIds:M});break}case"permission_request":{const T=n.payload;W.addPermissionRequest(T);break}case"permission_resolved":{const{requestId:T,approved:M}=n.payload;W.resolvePermissionRequest(T,M);break}case"delegation_decision":{const T=n.payload;W.handleDelegationDecision(T),T.status==="sent"&&((v=Pe.onToast)==null||v.call(Pe,"info","Task Delegated",`Delegated to ${T.selectedAgentName}: ${T.reasoning.slice(0,80)}...`),T.bossId&&T.selectedAgentId&&((S=Pe.onDelegation)==null||S.call(Pe,T.bossId,T.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:T,subordinateIds:M}=n.payload;W.updateBossSubordinates(T,M);break}case"delegation_history":{const{bossId:T,decisions:M}=n.payload;W.setDelegationHistory(T,M);break}case"session_history":{const{agentId:T,entries:M}=n.payload;W.setSessionHistory(T,M);break}case"boss_spawned_agent":{const{agent:T,bossPosition:M}=n.payload;console.log("[WebSocket] Boss spawned agent:",T.name,"- walking to boss at",M),W.addAgent(T),(N=Pe.onAgentCreated)==null||N.call(Pe,T),ex({type:"move_agent",payload:{agentId:T.id,position:M}}),(k=Pe.onToast)==null||k.call(Pe,"success","Agent Deployed",`${T.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:T,subordinateId:M,subordinateName:R,taskDescription:O}=n.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${T}: ${O.slice(0,50)}...`),W.handleAgentTaskStarted(T,M,R,O);break}case"agent_task_output":{const{bossId:T,subordinateId:M,output:R,isStreaming:O,timestamp:U,subagentName:H,toolName:I,toolInput:$,toolOutput:z}=n.payload;W.handleAgentTaskOutput(T,M,{text:R,isStreaming:O||!1,timestamp:U||Date.now(),subagentName:H,toolName:I,toolInput:$,toolOutput:z});break}case"agent_task_completed":{const{bossId:T,subordinateId:M,success:R}=n.payload;console.log(`[WebSocket] Agent task completed for boss ${T}, subordinate ${M}, success: ${R}`),W.handleAgentTaskCompleted(T,M,R);break}case"skills_update":{const T=n.payload;W.setSkillsFromServer(T);break}case"skill_created":{const T=n.payload;W.addSkillFromServer(T),console.log(`[WebSocket] Skill created: ${T.name}`);break}case"skill_updated":{const T=n.payload;W.updateSkillFromServer(T),console.log(`[WebSocket] Skill updated: ${T.name}`);break}case"skill_deleted":{const{id:T}=n.payload;W.removeSkillFromServer(T),console.log(`[WebSocket] Skill deleted: ${T}`);break}case"agent_skills":{const{agentId:T,skills:M}=n.payload;console.log(`[WebSocket] Agent ${T} has ${M.length} skills`);break}case"custom_agent_classes_update":{const T=n.payload;W.setCustomAgentClassesFromServer(T),console.log(`[WebSocket] Received ${T.length} custom agent classes`);const M=new Map;for(const R of T)M.set(R.id,R);(C=Pe.onCustomClassesSync)==null||C.call(Pe,M);break}case"custom_agent_class_created":{const T=n.payload;W.addCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class created: ${T.name}`),(A=Pe.onCustomClassesSync)==null||A.call(Pe,W.getState().customAgentClasses);break}case"custom_agent_class_updated":{const T=n.payload;W.updateCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class updated: ${T.name}`),(E=Pe.onCustomClassesSync)==null||E.call(Pe,W.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:T}=n.payload;W.removeCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class deleted: ${T}`),(D=Pe.onCustomClassesSync)==null||D.call(Pe,W.getState().customAgentClasses);break}case"agent_notification":{const T=n.payload;console.log(`[WebSocket] Agent notification from ${T.agentName}: ${T.title}`),(_=Pe.onAgentNotification)==null||_.call(Pe,T);break}case"focus_agent":{const{agentId:T,openTerminal:M}=n.payload;if(!W.getState().agents.get(T)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${T}`);break}W.selectAgent(T),M&&W.setTerminalOpen(!0);const O=[0,80,220,500,1e3];for(const U of O)window.setTimeout(()=>{window.focus()},U);break}case"exec_task_started":{const{taskId:T,agentId:M,agentName:R,command:O,cwd:U}=n.payload;console.log(`[WebSocket] Exec task started: ${T} for agent ${R}: ${O.slice(0,50)}...`),W.handleExecTaskStarted(T,M,R,O,U);break}case"exec_task_output":{const{taskId:T,agentId:M,output:R,isError:O}=n.payload;W.handleExecTaskOutput(T,M,R,O);break}case"exec_task_completed":{const{taskId:T,agentId:M,exitCode:R,success:O}=n.payload;console.log(`[WebSocket] Exec task completed: ${T} for agent ${M}, success: ${O}`),W.handleExecTaskCompleted(T,M,R,O);break}case"subagent_started":{const T=n.payload;console.log(`[WebSocket] Subagent started: ${T.name} (${T.id}) for agent ${T.parentAgentId}`),W.addSubagent(T),(F=Pe.onSubagentStarted)==null||F.call(Pe,T);break}case"subagent_output":{const{subagentId:T,parentAgentId:M,text:R,timestamp:O}=n.payload,U=R.indexOf(":");if(U>0){const H=R.slice(0,U).trim(),I=R.slice(U+1).trim();W.addSubagentActivity(T,M,{toolName:H,description:I,timestamp:O})}else R.startsWith("Using ")&&W.addSubagentActivity(T,M,{toolName:R.slice(6).trim(),description:"",timestamp:O});break}case"subagent_completed":{const{subagentId:T,parentAgentId:M,success:R,resultPreview:O,subagentName:U,durationMs:H,tokensUsed:I,toolUseCount:$}=n.payload;console.log(`[WebSocket] Subagent completed: ${T} for agent ${M}, success: ${R}`),(H||I||$)&&W.updateSubagentStats(T,M,{durationMs:H||0,tokensUsed:I||0,toolUseCount:$||0}),W.completeSubagent(T,M,R),(P=Pe.onSubagentCompleted)==null||P.call(Pe,T);const z=W.getSubagent(T)||W.getSubagentByToolUseId(T),q=U||(z==null?void 0:z.name)||T,Y=R?"✅":"❌",B=H?` (${(H/1e3).toFixed(0)}s · ${((I||0)/1e3).toFixed(1)}K tokens · ${$||0} tools)`:"";W.addOutput(M,{text:`${Y} Subagent ${q} ${R?"completed":"failed"}${B}`,isStreaming:!1,timestamp:Date.now(),subagentName:q,toolOutput:O});break}case"subagent_stream":{const{toolUseId:T,parentAgentId:M,entries:R}=n.payload;W.addSubagentStreamEntries(T,M,R);break}case"secrets_update":{const T=n.payload;W.setSecretsFromServer(T),console.log(`[WebSocket] Received ${T.length} secrets`);break}case"secret_created":{const T=n.payload;W.addSecretFromServer(T),console.log(`[WebSocket] Secret created: ${T.name}`);break}case"secret_updated":{const T=n.payload;W.updateSecretFromServer(T),console.log(`[WebSocket] Secret updated: ${T.name}`);break}case"secret_deleted":{const{id:T}=n.payload;W.removeSecretFromServer(T),console.log(`[WebSocket] Secret deleted: ${T}`);break}case"database_connection_result":{const{buildingId:T,connectionId:M,success:R,error:O,serverVersion:U}=n.payload;W.setConnectionStatus(T,M,{connected:R,error:O,serverVersion:U}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${M}`);break}case"databases_list":{const{buildingId:T,connectionId:M,databases:R}=n.payload;W.setDatabases(T,M,R),console.log(`[WebSocket] Received ${R.length} databases for ${M}`);break}case"tables_list":{const{buildingId:T,connectionId:M,database:R,tables:O}=n.payload;W.setTables(T,M,R,O),console.log(`[WebSocket] Received ${O.length} tables for ${R}`);break}case"table_schema":{const{buildingId:T,connectionId:M,database:R,table:O,columns:U,indexes:H,foreignKeys:I}=n.payload;W.setTableSchema(T,M,R,O,{columns:U,indexes:H||[],foreignKeys:I||[]}),console.log(`[WebSocket] Received schema for ${O}`);break}case"query_result":{const{buildingId:T,result:M}=n.payload;W.setQueryResult(T,M),console.log(`[WebSocket] Query ${M.status}: ${M.rowCount??M.affectedRows??0} rows in ${M.duration}ms`);break}case"silent_query_result":{const{buildingId:T,query:M,requestId:R,success:O,affectedRows:U,error:H}=n.payload;W.setSilentQueryResult(T,{query:M,requestId:R,success:O,affectedRows:U,error:H}),console.log(`[WebSocket] Silent query ${O?"succeeded":"failed"}: ${U??0} affected rows`);break}case"query_history_update":{const{buildingId:T,history:M}=n.payload;W.setQueryHistory(T,M),console.log(`[WebSocket] Received ${M.length} query history entries for ${T}`);break}}fb.end(`ws:${n.type}`)}wR(()=>mu());let jk=!1;function uj(){const n=pp();n&&n.readyState===WebSocket.OPEN&&n.close(1e3,"Page unloading");const e=sj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),vR()}function DR(){jk||(window.addEventListener("beforeunload",uj),jk=!0)}function dj(){uj(),W.setConnected(!1),W.stopStatusPolling()}function RR(){dj(),db(0),setTimeout(()=>mu(),100)}function mu(){DR();const n=sj();n&&(clearTimeout(n),aj(null));const e=pp();if(xR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Sk()&&Pe.onReconnect&&Pe.onReconnect();return}db(ub()+1),_c(!0);const t=Kb(),s=Ir(),a=6200;let r;if(t){const c=t.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://");r=c.endsWith("/ws")?c:`${c.replace(/\/$/,"")}/ws`}else r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let i=null;try{s?i=new WebSocket(r,[`auth-${s}`]):i=new WebSocket(r)}catch{_c(!1),Nk();return}wk(i),i.onopen=()=>{var d,f,h;const c=Sk();_c(!1),db(0),yR(),W.setConnected(!0),W.startStatusPolling(),W.clearAllPermissions(),c?((d=Pe.onToast)==null||d.call(Pe,"success","Reconnected","Connection restored - refreshing data..."),(f=Pe.onReconnect)==null||f.call(Pe)):(h=Pe.onToast)==null||h.call(Pe,"success","Connected","Connected to Tide Commander server"),bR(t,s),TR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=Zb(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&ps.captureReceived(f,c.data),MR(d)}catch(d){const f=c.data.substring(0,200);console.error("[WS] Failed to parse message:",d),console.error("[WS] Raw data (first 200 chars):",f),console.error("[WS] Full data length:",c.data.length),c.data.length<5e3&&console.error("[WS] Full malformed message:",c.data)}},i.onclose=()=>{var d,f;_c(!1),wk(null),W.setConnected(!1),W.stopStatusPolling();const c=ub();c<kk?((d=Pe.onToast)==null||d.call(Pe,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${kk})`),Nk()):(f=Pe.onToast)==null||f.call(Pe,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{_c(!1)},W.setSendMessage(ex)}function Nk(){const n=ub(),e=Math.min(1e3*Math.pow(2,n-1),3e4);aj(setTimeout(mu,e))}function OR(n,e){const t={position:n,target:e};wa(dt.CAMERA_STATE,t)}function LR(){return ea(dt.CAMERA_STATE,null)}function qV(n,e,t){const s={posX:n,posZ:e,zoom:t};wa(dt.CAMERA_STATE_2D,s)}function GV(){return ea(dt.CAMERA_STATE_2D,null)}function Dl(){return{Authorization:`Bearer ${Ir()}`,"Content-Type":"application/json"}}async function PR(){const n=await fetch(`${ra()}/api/workspaces`,{headers:Dl()});if(!n.ok)throw new Error(`Failed to fetch workspaces: ${n.statusText}`);return n.json()}async function IR(n,e){const t=await fetch(`${ra()}/api/workspaces`,{method:"POST",headers:Dl(),body:JSON.stringify({name:n,areaIds:e})});if(!t.ok)throw new Error(`Failed to create workspace: ${t.statusText}`);return t.json()}async function Tk(n,e){const t=await fetch(`${ra()}/api/workspaces/${n}`,{method:"PUT",headers:Dl(),body:JSON.stringify(e)});if(!t.ok)throw new Error(`Failed to update workspace: ${t.statusText}`);return t.json()}async function BR(n){const e=await fetch(`${ra()}/api/workspaces/${n}`,{method:"DELETE",headers:Dl()});if(!e.ok)throw new Error(`Failed to delete workspace: ${e.statusText}`)}async function FR(){const n=await fetch(`${ra()}/api/workspaces/active`,{headers:Dl()});if(!n.ok)throw new Error(`Failed to get active workspace: ${n.statusText}`);return(await n.json()).activeWorkspaceId??null}async function _k(n){const e=await fetch(`${ra()}/api/workspaces/active`,{method:"PUT",headers:Dl(),body:JSON.stringify({workspaceId:n})});if(!e.ok)throw new Error(`Failed to set active workspace: ${e.statusText}`)}const gu=new Set;let Xa=null,Xi=[],fj=!1;const mb=new Set;function Ym(n){fj=n,mb.forEach(e=>e(n))}const pj="tide-commander-active-workspace";function Ek(){return typeof window>"u"?null:localStorage.getItem(pj)||null}function Km(n){typeof window>"u"||localStorage.setItem(pj,n||"")}function Mc(){gu.forEach(n=>n())}function zR(){return Xa}function hp(n){return Xa?n?Xa.areaIds.includes(n):!1:!0}function YV(n){return Xa?Xa.areaIds.includes(n):!0}function tx(){const[,n]=x.useState(0);return x.useEffect(()=>{const e=()=>n(t=>t+1);return gu.add(e),()=>{gu.delete(e)}},[]),[Xa,Xi]}function $R(n){return gu.add(n),()=>{gu.delete(n)}}function HR(){const[n,e]=x.useState(fj);return x.useEffect(()=>{const t=s=>e(s);return mb.add(t),()=>{mb.delete(t)}},[]),n}const Qm=new Map,hj=Ce.memo(function(){const{t:e}=ut("common"),t=Pa(),[s,a]=x.useState([]),[r,i]=x.useState(()=>Ek()),[c,d]=x.useState(!1),[f,h]=x.useState(!1),[m,b]=x.useState(!0),[y,v]=x.useState(null),[S,N]=x.useState(""),[k,C]=x.useState([]),[A,E]=x.useState(!1),D=x.useRef(null);x.useEffect(()=>{let I=!1;return(async()=>{try{const $=Ek(),[z,q]=await Promise.all([PR(),FR()]);if(I)return;const Y=$&&z.some(B=>B.id===$)?$:q&&z.some(B=>B.id===q)?q:null;a(z),Xi=z,i(Y),Km(Y),Xa=z.find(B=>B.id===Y)??null,Mc()}catch($){console.error("workspace error:",$)}finally{I||b(!1)}})(),()=>{I=!0}},[]),x.useEffect(()=>{if(!c&&!f)return;const I=$=>{D.current&&!D.current.contains($.target)&&(d(!1),h(!1))};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[c,f]);const _=x.useMemo(()=>s.find(I=>I.id===r)??null,[s,r]),F=x.useCallback(async I=>{Ym(!0);const $=Date.now();if(r){const B=LR();B&&(Qm.set(r,B),Tk(r,{cameraState:B}).then(G=>{a(te=>{const V=te.map(ge=>ge.id===r?G:ge);return Xi=V,V})}).catch(G=>console.error("workspace error:",G)))}i(I),Km(I),d(!1);const z=I?s.find(B=>B.id===I)??null:null;if(Xa=z,Xi=s,Mc(),I){const G=(z==null?void 0:z.cameraState)??Qm.get(I);G&&(OR(G.position,G.target),Qm.set(I,G))}_k(I).catch(B=>console.error("workspace error:",B));const q=Date.now()-$,Y=400;q<Y?setTimeout(()=>Ym(!1),Y-q):Ym(!1)},[r,s]),P=x.useMemo(()=>Array.from(t.values()).filter(I=>!I.archived),[t]),T=x.useCallback(async()=>{if(S.trim())try{const I=await IR(S.trim(),k),$=[...s,I];a($),Xi=$,Mc(),N(""),C([]),E(!1)}catch(I){console.error("workspace error:",I)}},[S,k,s]),M=x.useCallback(async()=>{if(!(!y||!S.trim()))try{const I=await Tk(y,{name:S.trim(),areaIds:k}),$=s.map(z=>z.id===y?I:z);a($),Xi=$,y===r&&(Xa=I),Mc(),v(null),N(""),C([])}catch(I){console.error("workspace error:",I)}},[y,S,k,s,r]),R=x.useCallback(async I=>{try{await BR(I);const $=s.filter(z=>z.id!==I);a($),Xi=$,r===I&&(i(null),Km(null),Xa=null,await _k(null).catch(z=>console.error("workspace error:",z))),Mc()}catch($){console.error("workspace error:",$)}},[s,r]),O=x.useCallback(I=>{v(I.id),N(I.name),C([...I.areaIds]),E(!1)},[]),U=x.useCallback(()=>{v(null),N(""),C([]),E(!0)},[]),H=x.useCallback(I=>{C($=>$.includes(I)?$.filter(z=>z!==I):[...$,I])},[]);return m?null:o.jsxs("div",{className:"workspace-switcher",ref:D,children:[o.jsxs("button",{className:"workspace-switcher-trigger",onClick:()=>{d(!c),h(!1)},title:"Workspaces",children:[o.jsx("span",{className:"workspace-switcher-icon",children:"📂"}),o.jsx("span",{className:"workspace-switcher-label",children:_?_.name:e("agentBar.allWorkspaces",{defaultValue:"All"})}),o.jsx("span",{className:"workspace-switcher-arrow",children:c?"▲":"▼"})]}),c&&!f&&o.jsxs("div",{className:"workspace-switcher-dropdown",children:[o.jsx("button",{className:`workspace-switcher-option ${r?"":"active"}`,onClick:()=>F(null),children:e("agentBar.allWorkspaces",{defaultValue:"All"})}),s.map(I=>o.jsxs("button",{className:`workspace-switcher-option ${I.id===r?"active":""}`,onClick:()=>F(I.id),children:[I.name,o.jsx("span",{className:"workspace-switcher-option-count",children:I.areaIds.length})]},I.id)),o.jsx("div",{className:"workspace-switcher-divider"}),o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-manage",onClick:()=>h(!0),children:["⚙ ",e("agentBar.manageWorkspaces",{defaultValue:"Manage"})]})]}),f&&o.jsxs("div",{className:"workspace-switcher-dropdown workspace-switcher-manager",children:[o.jsxs("div",{className:"workspace-switcher-manager-header",children:[o.jsx("span",{children:e("agentBar.workspaces",{defaultValue:"Workspaces"})}),o.jsx("button",{className:"workspace-switcher-close",onClick:()=>h(!1),children:"×"})]}),o.jsx("div",{className:"workspace-switcher-manager-list",children:s.map(I=>o.jsx("div",{className:"workspace-switcher-manager-item",children:y===I.id?o.jsxs("div",{className:"workspace-switcher-editor",children:[o.jsx("input",{type:"text",value:S,onChange:$=>N($.target.value),className:"workspace-switcher-input",placeholder:"Workspace name",autoFocus:!0,onKeyDown:$=>{$.key==="Enter"&&M(),$.key==="Escape"&&v(null)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[P.map($=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes($.id),onChange:()=>H($.id)}),o.jsx("span",{style:{color:$.color},children:$.name})]},$.id)),P.length===0&&o.jsx("span",{className:"workspace-switcher-empty",children:"No areas"})]}),o.jsxs("div",{className:"workspace-switcher-editor-actions",children:[o.jsx("button",{className:"workspace-switcher-btn-save",onClick:M,children:"Save"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>v(null),children:"Cancel"})]})]}):o.jsxs("div",{className:"workspace-switcher-manager-row",children:[o.jsx("span",{className:"workspace-switcher-manager-name",children:I.name}),o.jsxs("span",{className:"workspace-switcher-manager-count",children:[I.areaIds.length," areas"]}),o.jsx("button",{className:"workspace-switcher-btn-edit",onClick:()=>O(I),title:"Edit",children:"✏"}),o.jsx("button",{className:"workspace-switcher-btn-delete",onClick:()=>R(I.id),title:"Delete",children:"🗑"})]})},I.id))}),A?o.jsxs("div",{className:"workspace-switcher-editor workspace-switcher-create-form",children:[o.jsx("input",{type:"text",value:S,onChange:I=>N(I.target.value),className:"workspace-switcher-input",placeholder:"New workspace name",autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&T(),I.key==="Escape"&&E(!1)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[P.map(I=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(I.id),onChange:()=>H(I.id)}),o.jsx("span",{style:{color:I.color},children:I.name})]},I.id)),P.length===0&&o.jsx("span",{className:"workspace-switcher-empty",children:"No areas"})]}),o.jsxs("div",{className:"workspace-switcher-editor-actions",children:[o.jsx("button",{className:"workspace-switcher-btn-save",onClick:T,children:"Create"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>E(!1),children:"Cancel"})]})]}):o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-add",onClick:U,children:["+ ",e("agentBar.newWorkspace",{defaultValue:"New Workspace"})]})]})]})}),Ff="tide_webgl_active";typeof window<"u"&&(window.__tidePersistedScene===void 0&&(window.__tidePersistedScene=null),window.__tidePersistedCanvas===void 0&&(window.__tidePersistedCanvas=null),window.__tideWsConnected===void 0&&(window.__tideWsConnected=!1),window.__tideIsPageUnloading===void 0&&(window.__tideIsPageUnloading=!1));function mp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function mj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function UR(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function bu(n){typeof window<"u"&&(window.__tidePersistedScene=n)}function tu(n){typeof window<"u"&&(window.__tidePersistedCanvas=n)}function gj(n){typeof window<"u"&&(window.__tideWsConnected=n)}function WR(n){typeof window<"u"&&(window.__tideIsPageUnloading=n)}function VR(){sessionStorage.setItem(Ff,"true")}function Yd(n){WR(!0),sessionStorage.removeItem(Ff),dj(),kR(),window.__tideScene&&(window.__tideScene=null);const e=mp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),bu(null)):console.log("[App] No persistedScene to dispose"),tu(null),gj(!1);const t=document.getElementById("battlefield");t&&t.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function qR(){var a,r;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Ff)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(r=(a=window.__tideScene).dispose)==null||r.call(a)}catch{}window.__tideScene=null}const e=mp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}bu(null)}const t=document.getElementById("battlefield"),s=mj();t&&t!==s&&t.remove(),sessionStorage.removeItem(Ff)}function GR(){typeof window>"u"||(qR(),window.addEventListener("pageshow",n=>{n.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Yd(),window.location.reload())}),window.onunload=()=>Yd(),window.onbeforeunload=n=>{Yd()},window.addEventListener("pagehide",n=>{Yd(`pagehide (persisted=${n.persisted})`)}))}GR();const Mk={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},Dk={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Rk={idleAnimation:"sit",workingAnimation:"sprint"},YR=0;function bj(){const n={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:Mk,modelStyle:Dk,animations:Rk,fpsLimit:YR},e=ea(dt.CONFIG,null);if(e){const t=e.indicatorScale;return{characterScale:e.characterScale??n.characterScale,scale2d:e.scale2d??t??n.scale2d,scale3d:e.scale3d??t??n.scale3d,show2DTaskLabels:e.show2DTaskLabels??n.show2DTaskLabels,gridVisible:e.gridVisible??n.gridVisible,timeMode:e.timeMode??n.timeMode,terrain:{...Mk,...e.terrain},modelStyle:{...Dk,...e.modelStyle},animations:{...Rk,...e.animations},fpsLimit:e.fpsLimit??n.fpsLimit}}return n}function KR(n){wa(dt.CONFIG,n)}function QR(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function xj(){console.log("[Tide HMR] Manual scene refresh triggered");const n=mp();if(n){try{n.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}bu(null)}tu(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const t=e.getContext("webgl2")||e.getContext("webgl");if(t){const s=t.getExtension("WEBGL_lose_context");s&&s.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=xj);function XR({canvasRef:n,selectionBoxRef:e,viewMode:t,sceneMountKey:s=0,showToast:a,showAgentNotification:r,toolboxModal:i,contextMenu:c,setHoveredAgentPopup:d,setBuildingPopup:f,getBuildingPopup:h,openBuildingModal:m,openPM2LogsModal:b,openBossLogsModal:y,openDatabasePanel:v,onSceneLoadingChange:S}){const N=x.useRef(null),k=x.useRef(null),C=x.useRef(null),A=x.useRef(null),E=x.useRef(null);return x.useEffect(()=>{if(t!=="3d"){S==null||S(!1);return}if(!n.current||!e.current)return;let D=!1;S==null||S(!0);const _=mp(),P=mj()===n.current;function T(){var R,O,U,H,I,$,z,q;(R=N.current)==null||R.setOnToast(a),(O=N.current)==null||O.setOnBuildingClick((Y,B)=>{W.selectBuilding(Y);const G=W.getState().buildings.get(Y);(G==null?void 0:G.type)==="folder"&&G.folderPath?W.openFileExplorer(G.folderPath):(G==null?void 0:G.type)==="server"||(G==null?void 0:G.type)==="boss"||(G==null?void 0:G.type)==="database"?(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{f({buildingId:Y,screenPos:B,fromClick:!0}),k.current=null},150)):m(Y)}),(U=N.current)==null||U.setOnContextMenu((Y,B,G)=>{c.open(Y,B,G)}),(H=N.current)==null||H.setOnAgentHover(()=>{}),(I=N.current)==null||I.setOnBuildingHover((Y,B)=>{const G=h();if(Y&&B){const te=W.getState().buildings.get(Y);((te==null?void 0:te.type)==="server"||(te==null?void 0:te.type)==="boss"||(te==null?void 0:te.type)==="database")&&!(G!=null&&G.fromClick)&&f({buildingId:Y,screenPos:B,fromClick:!1})}else G!=null&&G.fromClick||f(null)}),($=N.current)==null||$.setOnGroundClick(()=>{f(null)}),(z=N.current)==null||z.setOnAreaDoubleClick(Y=>{W.selectArea(Y),i.open()}),(q=N.current)==null||q.setOnBuildingDoubleClick(Y=>{var G;k.current&&(clearTimeout(k.current),k.current=null),f(null);const B=W.getState().buildings.get(Y);(B==null?void 0:B.type)==="server"&&((G=B.pm2)!=null&&G.enabled)?b==null||b(Y):(B==null?void 0:B.type)==="boss"?y==null||y(Y):(B==null?void 0:B.type)==="database"?v==null||v(Y):(B==null?void 0:B.type)==="folder"&&B.folderPath?W.openFileExplorer(B.folderPath):m(Y)})}if(_)try{N.current=_,P?(console.log("[Tide] Reusing existing scene (StrictMode remount)"),_.ensureRenderLoopRunning()):(console.log("[Tide] Reattaching persisted scene to new canvas"),_.reattach(n.current,e.current),tu(n.current));const R=W.getState();_.syncAreas(),_.syncBuildings(),R.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",R.agents.size),_.syncAgents(Array.from(R.agents.values()))),T()}catch(R){console.error("[Tide] Failed to reattach persisted 3D scene:",R),S==null||S(!1)}finally{A.current=requestAnimationFrame(()=>{E.current=requestAnimationFrame(()=>{S==null||S(!1),E.current=null}),A.current=null})}else{const R=n.current,O=e.current,U=async()=>{if(D){console.log("[Tide] Effect cleaned up before scene init, skipping"),S==null||S(!1);return}if(!R.isConnected||!O.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),S==null||S(!1);return}(!R.clientWidth||!R.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),R.style.width="100%",R.style.height="100%",R.offsetHeight),(!R.clientWidth||!R.clientHeight)&&(R.width=window.innerWidth,R.height=window.innerHeight),VR();try{const{SceneManager:H}=await gt(async()=>{const{SceneManager:z}=await import("./SceneManager-CeqztySP.js");return{SceneManager:z}},__vite__mapDeps([6,4,3,1]));if(D){S==null||S(!1);return}const I=new H(R,O);N.current=I,bu(I),tu(R);const $=bj();I.setCharacterScale($.characterScale),I.setScale3D($.scale3d),I.setTimeMode($.timeMode),I.setTerrainConfig($.terrain),I.setFloorStyle($.terrain.floorStyle,!0),I.setGridVisible($.gridVisible),I.setAgentModelStyle($.modelStyle),I.setIdleAnimation($.animations.idleAnimation),I.setWorkingAnimation($.animations.workingAnimation),I.setFpsLimit($.fpsLimit),I.syncAreas(),I.syncBuildings(),I.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const z=W.getState();z.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",z.customAgentClasses.size),I.setCustomAgentClasses(z.customAgentClasses)),z.agents.size>0&&(console.log("[Tide] Syncing agents from store:",z.agents.size),I.syncAgents(Array.from(z.agents.values()))),I.upgradeAgentModels()}).catch(z=>{console.warn("[Tide] Some models failed to load, using fallback:",z)}).finally(()=>{S==null||S(!1)}),T()}catch(H){console.error("[Tide] Failed to initialize 3D scene:",H),S==null||S(!1)}};C.current=requestAnimationFrame(()=>void U())}ij({onAgentCreated:R=>{var O,U,H;(O=N.current)==null||O.addAgent(R),(U=N.current)==null||U.refreshSelectionVisuals(),(H=window.__spawnModalSuccess)==null||H.call(window)},onAgentUpdated:(R,O)=>{var H;const U=W.getState().agents.get(R.id)||R;(H=N.current)==null||H.updateAgent(U,O)},onAgentDeleted:R=>{var O;(O=N.current)==null||O.removeAgent(R)},onAgentsSync:R=>{var U;const O=Array.from(W.getState().agents.values());(U=N.current)==null||U.syncAgents(O)},onAreasSync:()=>{var O,U;(O=N.current)==null||O.syncAreas();const R=Array.from(W.getState().agents.values());(U=N.current)==null||U.syncAgents(R)},onSpawnError:()=>{var R;(R=window.__spawnModalError)==null||R.call(window)},onSpawnSuccess:()=>{var R;(R=window.__spawnModalSuccess)==null||R.call(window)},onDirectoryNotFound:R=>{var O;(O=window.__spawnModalDirNotFound)==null||O.call(window,R)},onToolUse:(R,O,U)=>{var H;(H=N.current)==null||H.showToolBubble(R,O,U)},onDelegation:(R,O)=>{var U;(U=N.current)==null||U.showDelegationEffect(R,O)},onCustomClassesSync:R=>{var O,U;(O=N.current)==null||O.setCustomAgentClasses(R),(U=N.current)==null||U.upgradeAgentModels()},onBuildingUpdated:R=>{var O;(O=N.current)==null||O.updateBuilding(R)},onSubagentStarted:R=>{var O;(O=N.current)==null||O.addSubagentEffect(R.id,R.parentAgentId,R.name,R.subagentType)},onSubagentCompleted:R=>{var H;const O=W.getSubagent(R)||W.getSubagentByToolUseId(R),U=(O==null?void 0:O.id)||R;(H=N.current)==null||H.completeSubagentEffect(U),setTimeout(()=>{var I;(I=N.current)==null||I.removeSubagentEffect(U)},3e4)}});const M=$R(()=>{if(N.current){N.current.syncAreas(),N.current.syncBuildings();const R=Array.from(W.getState().agents.values());N.current.syncAgents(R)}});return()=>{M(),D=!0,C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),W.getState().viewMode!=="3d"&&QR()&&N.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),SR(),N.current.dispose(),N.current=null,bu(null),tu(null))}},[t,s]),N}function JR({showToast:n,showAgentNotification:e}){x.useEffect(()=>{ij({onToast:n,onReconnect:()=>{W.triggerReconnect()},onAgentNotification:a=>{e(a)}}),UR()||(mu(),gj(!0)),hR();let t;gR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&nj(a.agentId)}).then(a=>{t=a});const s=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>mu(),100)};return window.addEventListener("tideAppResume",s),()=>{window.removeEventListener("tideAppResume",s),t==null||t()}},[n,e])}function ZR(n){x.useEffect(()=>{let e="",t="",s=new Map;const a=r=>{var d;let i=!1;const c=new Map;for(const[f,h]of r){const b=`${h.position.x.toFixed(2)},${h.position.z.toFixed(2)},${h.status},${h.class},${h.isBoss},${((d=h.subordinateIds)==null?void 0:d.length)??0}`.split("").reduce((y,v)=>(y<<5)-y+v.charCodeAt(0),0);c.set(f,b),s.get(f)!==b&&(i=!0)}return c.size!==s.size&&(i=!0),{newVersion:c,changed:i}};return W.subscribe(()=>{var b;const r=W.getState(),i=Array.from(r.selectedAgentIds).sort().join(","),c=Array.from(r.selectedBuildingIds).sort().join(","),d=i!==e,f=c!==t,{newVersion:h,changed:m}=a(r.agents);(d||f||m)&&(e=i,t=c,s=h,(b=n.current)==null||b.refreshSelectionVisuals())})},[n])}function eO(n){x.useEffect(()=>{var s;(s=n.current)==null||s.syncAreas();let e=0,t=0;return W.subscribe(()=>{var c,d;const r=W.getState().areas;if(r.size!==e){e=r.size,t=Date.now(),(c=n.current)==null||c.syncAreas();return}let i=0;for(const[f,h]of r){let m=f.charCodeAt(0);m+=(h.width??0)+(h.height??0)+(h.radius??0),m+=Math.floor(h.center.x*100)+Math.floor(h.center.z*100),m+=(h.zIndex??0)*1e3;for(let b=0;b<h.name.length;b++)m+=h.name.charCodeAt(b);for(let b=0;b<h.color.length;b++)m+=h.color.charCodeAt(b);if(h.directoryGitCounts)for(const b of h.directoryGitCounts)m+=(b+1)*7;if(h.logo){m+=Math.floor((h.logo.opacity??.8)*1e3),m+=Math.floor(h.logo.width*100)+Math.floor(h.logo.height*100);for(let b=0;b<h.logo.position.length;b++)m+=h.logo.position.charCodeAt(b);if(h.logo.filename)for(let b=0;b<h.logo.filename.length;b++)m+=h.logo.filename.charCodeAt(b)}i^=m|0}i!==t&&(t=i,(d=n.current)==null||d.syncAreas())})},[n])}function tO(n){x.useEffect(()=>{var s;(s=n.current)==null||s.syncBuildings();let e=0,t=0;return W.subscribe(()=>{var c,d;const r=W.getState().buildings;if(r.size!==e){e=r.size,t=Date.now(),(c=n.current)==null||c.syncBuildings();return}let i=0;for(const[f,h]of r){i^=h.position.x*1e3+h.position.z|0,i^=(h.scale||1)*1e4|0;const m=`${h.style||""}${h.name}${h.status}${h.gitChangesCount||0}`;for(let b=0;b<m.length;b++)i=(i<<5)-i+m.charCodeAt(b)|0}i!==t&&(t=i,(d=n.current)==null||d.syncBuildings())})},[n])}function nO(n,e){x.useEffect(()=>{var t;(t=n.current)==null||t.highlightArea(e)},[n,e])}function sO(n,e){x.useEffect(()=>{var t;(t=n.current)==null||t.setPowerSaving(e)},[n,e])}function Dt(n,e,t,s,a={},r="global"){return{id:n,name:e,description:t,key:s,modifiers:a,enabled:!0,context:r}}const Xm=[Dt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Dt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Dt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Dt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Dt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Dt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Dt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Dt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Dt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Dt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Dt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Dt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Dt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Dt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Dt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Dt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Dt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Dt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Dt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Dt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Dt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Dt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Dt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Dt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Dt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Dt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Dt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Dt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Dt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Dt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Dt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Dt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Dt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Dt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Dt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Dt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Dt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Dt("clear-context","Clear Context","Clear context of the selected agent","c",{alt:!0,shift:!0}),Dt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Dt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Dt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Dt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Dt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Dt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Dt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Dt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Dt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Dt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function xn(n,e){if(!e||!e.enabled)return!1;const{ctrl:t,alt:s,shift:a}=e.modifiers,r=t?n.ctrlKey||n.metaKey:!n.ctrlKey&&!n.metaKey,i=s?n.altKey:!n.altKey,c=a?n.shiftKey:!n.shiftKey;let d;if(t?d=(n.ctrlKey||n.metaKey)&&i&&c:d=r&&i&&c,!d)return!1;const f=e.key;if(f.length===1&&/^[a-zA-Z]$/.test(f)){const m=`Key${f.toUpperCase()}`;return n.code===m}if(f.length===1&&/^[0-9]$/.test(f)){const m=`Digit${f}`;return n.code===m}return f==="Space"||f===" "?n.code==="Space":n.key===f}function aO(n){return n===" "||n==="Space"?"space":(n.length===1,n.toLowerCase())}function rO(n){const e=n.trim().toLowerCase();if(e==="space")return"Space";if(e==="esc")return"Escape";if(e==="return")return"Enter";const t={escape:"Escape",enter:"Enter",tab:"Tab",backspace:"Backspace",delete:"Delete",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown"};return t[e]?t[e]:e}function iO(n){if(!(n!=null&&n.key))return"";const e=[];return n.modifiers.ctrl&&e.push("ctrl"),n.modifiers.alt&&e.push("alt"),n.modifiers.shift&&e.push("shift"),n.modifiers.meta&&e.push("meta"),e.push(aO(n.key)),e.join("+")}function nx(n){if(!n)return null;const e=n.split("+").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return null;const t=e[e.length-1],s={};for(const r of e.slice(0,-1))r==="ctrl"||r==="control"?s.ctrl=!0:r==="alt"||r==="option"?s.alt=!0:r==="shift"?s.shift=!0:(r==="meta"||r==="cmd"||r==="command")&&(s.meta=!0);const a=rO(t);return a?{key:a,modifiers:s}:null}function oO(n){const e=nx(n);return e?gb({key:e.key,modifiers:e.modifiers}):""}function lO(n,e){const t=nx(e);return t?xn(n,{key:t.key,modifiers:t.modifiers,enabled:!0}):!1}function gb(n){const e=[];if(n.modifiers.ctrl){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌘":"Ctrl")}if(n.modifiers.alt){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌥":"Alt")}n.modifiers.shift&&e.push("Shift"),n.modifiers.meta&&e.push("⌘");let t=n.key;return t===" "?t="Space":t.length===1&&(t=t.toUpperCase()),e.push(t),e.join("+")}function cO(n,e,t,s){return n.filter(a=>{if(a.id===t||!a.enabled||s&&a.context!=="global"&&a.context!==s)return!1;const r=h=>h===" "||h==="Space"?"Space":h.length===1?h.toLowerCase():h,i=r(a.key),c=r(e.key);if(i!==c)return!1;const d=a.modifiers,f=e.modifiers;return(d.ctrl||!1)===(f.ctrl||!1)&&(d.alt||!1)===(f.alt||!1)&&(d.shift||!1)===(f.shift||!1)&&(d.meta||!1)===(f.meta||!1)})}function uO({sceneRef:n,spawnModal:e,commanderModal:t,explorerModal:s,spotlightModal:a,deleteConfirmModal:r,onRequestBuildingDelete:i,onOpenDatabasePanel:c,onCloseDatabasePanel:d,databasePanelOpen:f}){x.useEffect(()=>{const h=m=>{var O,U,H,I,$;const b=W.getShortcuts(),y=m.target,v=y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true"||!!y.closest(".cm-editor"),S=W.getState(),N=b.find(z=>z.id==="deselect-all");if(xn(m,N)){if(y.closest(".guake-bottom-terminal-embed"))return;if(yf()){m.preventDefault();return}if(S.activeTool==="rectangle"||S.activeTool==="circle"){(O=n.current)==null||O.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():S.terminalOpen?(W.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(W.deselectAll(),(U=n.current)==null||U.refreshSelectionVisuals())}for(let z=1;z<=9;z++){const q=b.find(Y=>Y.id===`select-agent-${z}`);if(xn(m,q)){m.preventDefault();const Y=W.getState(),B=z-1,G=Array.from(Y.agents.keys());B<G.length&&(W.selectAgent(G[B]),(H=n.current)==null||H.refreshSelectionVisuals());return}}const k=b.find(z=>z.id==="spawn-agent");if(xn(m,k)){m.preventDefault(),e.open();return}const C=b.find(z=>z.id==="toggle-commander-tab");if(xn(m,C)&&!v){m.preventDefault(),t.toggle();return}const A=b.find(z=>z.id==="toggle-commander");if(xn(m,A)){m.preventDefault(),t.toggle();return}const E=b.find(z=>z.id==="toggle-file-explorer");if(xn(m,E)){m.preventDefault();const z=W.getState();if(s.isOpen||z.explorerFolderPath!==null||z.explorerAreaId!==null)s.close(),W.closeFileExplorer();else{const Y=W.getLastExplorerState();if((Y==null?void 0:Y.type)==="folder")W.openFileExplorer(Y.path);else if((Y==null?void 0:Y.type)==="area")if(z.areas.has(Y.areaId))s.open(Y.areaId);else{const B=Array.from(z.areas.values()).filter(G=>G.directories&&G.directories.length>0);B.length>0&&s.open(B[0].id)}else{const B=Array.from(z.areas.values()).filter(G=>G.directories&&G.directories.length>0);B.length>0&&s.open(B[0].id)}}return}if(m.altKey&&!m.ctrlKey&&!m.shiftKey&&!m.metaKey&&m.code==="KeyD"){if(m.preventDefault(),m.stopPropagation(),f){d();return}const z=localStorage.getItem("tide-commander-last-database-building"),q=W.getState();if(z){const Y=q.buildings.get(z);if((Y==null?void 0:Y.type)==="database"){c(z);return}}for(const[Y,B]of q.buildings)if(B.type==="database"){c(Y);return}return}const D=b.find(z=>z.id==="toggle-spotlight");if(xn(m,D)||m.altKey&&!m.ctrlKey&&!m.metaKey&&m.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:D,altKey:m.altKey,code:m.code}),m.preventDefault(),a.toggle();return}const _=b.find(z=>z.id==="toggle-2d-view");if(xn(m,_)){m.preventDefault();const z=W.getState().viewMode,q=z==="3d"?"2d":z==="2d"?"dashboard":"3d";W.setViewMode(q);return}const F=b.find(z=>z.id==="clear-context");if(xn(m,F)){m.preventDefault();const z=W.getState(),q=z.selectedAgentIds.size===1?Array.from(z.selectedAgentIds)[0]:null;q&&W.clearContext(q);return}const P=b.find(z=>z.id==="next-working-agent"),T=b.find(z=>z.id==="prev-working-agent");if((xn(m,P)||xn(m,T))&&!v){const z=W.getState();if(z.terminalOpen)return;const q=Array.from(z.agents.values());let Y=q.filter(V=>z.agentsWithUnseenOutput.has(V.id));if(Y.length===0&&(Y=q.filter(V=>V.status==="working")),Y.length===0)return;m.preventDefault();const B=z.selectedAgentIds.size===1?Array.from(z.selectedAgentIds)[0]:null,G=B?Y.findIndex(V=>V.id===B):-1;let te;xn(m,P)?te=G===-1?0:(G+1)%Y.length:te=G===-1?Y.length-1:(G-1+Y.length)%Y.length,W.selectAgent(Y[te].id),(I=n.current)==null||I.refreshSelectionVisuals();return}const M=b.find(z=>z.id==="delete-selected"),R=b.find(z=>z.id==="delete-selected-backspace");if((xn(m,M)||xn(m,R))&&!v){const z=W.getState();if(z.selectedAgentIds.size>0){m.preventDefault(),r.open();return}if(z.selectedBuildingIds.size>0){m.preventDefault(),i();return}return}if(!v){const z=Array.from(S.agents.values()).find(q=>{var B;const Y=(B=q.shortcut)==null?void 0:B.trim();return Y?lO(m,Y):!1});if(z){m.preventDefault(),m.stopPropagation(),W.selectAgent(z.id),W.setTerminalOpen(!0),($=n.current)==null||$.refreshSelectionVisuals();return}}};return document.addEventListener("keydown",h,!0),()=>document.removeEventListener("keydown",h,!0)},[n,e,t,s,a,r,i,c,d,f])}function dO(){const[n,e]=x.useState(!1);return window.__tideSetBackNavModal=e,x.useEffect(()=>{if(window.__tideBackNavSetup){window.location.hash.includes("app")||(window.location.hash="#app");return}window.__tideBackNavSetup=!0,window.location.hash.includes("app")||(window.location.hash="#app");const s=()=>window.innerWidth<=768;let a=0;const r=()=>{var c;Date.now()-a<200||window.location.hash.includes("app")||(window.location.hash="#app",s()&&(yf()||(c=window.__tideSetBackNavModal)==null||c.call(window,!0)))},i=()=>{var c;window.location.hash.includes("app")||(window.location.hash="#app"),window.location.hash==="#app"&&setTimeout(()=>{window.location.hash==="#app"&&!window.location.hash.includes("app2")&&(window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"))},50),s()?yf()?a=Date.now():(c=window.__tideSetBackNavModal)==null||c.call(window,!0):(yf(),a=Date.now())};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",r),window.addEventListener("popstate",i)},[]),{showBackNavModal:n,setShowBackNavModal:e,handleLeave:()=>{e(!1);const s=window.__tideHistoryDepth??2;window.history.go(-(s+1))}}}const Jm="agent-order-change";function fO(n){const e=x.useMemo(()=>new Set(n.map(d=>d.id)),[n]),[t,s]=x.useState(()=>ea(dt.AGENT_ORDER,[]));x.useEffect(()=>{const d=f=>{s(f.detail)};return window.addEventListener(Jm,d),()=>{window.removeEventListener(Jm,d)}},[]);const a=x.useMemo(()=>{const d=t.filter(b=>e.has(b)),f=n.filter(b=>!d.includes(b.id)).map(b=>b.id),h=[...d,...f],m=new Map(n.map(b=>[b.id,b]));return h.map(b=>m.get(b)).filter(b=>b!==void 0)},[n,t,e]),r=x.useCallback(d=>{s(d),wa(dt.AGENT_ORDER,d),window.dispatchEvent(new CustomEvent(Jm,{detail:d}))},[]),i=x.useCallback((d,f)=>{const h=a.map(b=>b.id),[m]=h.splice(d,1);h.splice(f,0,m),r(h)},[a,r]),c=x.useCallback(()=>{s([]),wa(dt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const d=t.filter(f=>e.has(f));d.length!==t.length&&r(d)},[e,t,r]),{orderedAgents:a,moveAgent:i,resetOrder:c}}function Sa(n){const e=x.useRef(null),t=x.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),s=x.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),n()),e.current=null},[n]);return{handleMouseDown:t,handleClick:s}}const pO=3e4;function hO(){const n=x.useRef(null);x.useEffect(()=>{const e=async()=>{var i,c;const t=W.getState(),s=new Map,a=new Map;for(const[d,f]of t.buildings){const h=f.folderPath||f.cwd;h&&(a.has(h)||a.set(h,[]),a.get(h).push(d))}for(const[d,f]of a)try{const h=await Lt(Et(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!h.ok)continue;const b=((i=(await h.json()).files)==null?void 0:i.length)||0;s.set(d,b);for(const y of f){const v=W.getState().buildings.get(y);v&&v.gitChangesCount!==b&&W.updateBuildingLocal(y,{gitChangesCount:b})}}catch{}const r=new Map;for(const[d,f]of t.areas)f.archived||!f.directories||f.directories.forEach((h,m)=>{h&&(r.has(h)||r.set(h,[]),r.get(h).push({areaId:d,dirIndex:m}))});if(r.size!==0)for(const[d,f]of r)try{let h;if(s.has(d))h=s.get(d);else{const b=await Lt(Et(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!b.ok)continue;h=((c=(await b.json()).files)==null?void 0:c.length)||0,s.set(d,h)}const m=new Map;for(const b of f)m.has(b.areaId)||m.set(b.areaId,[]),m.get(b.areaId).push({dirIndex:b.dirIndex,count:h});for(const[b,y]of m){const v=W.getState().areas.get(b);if(!v)continue;const S=v.directoryGitCounts?[...v.directoryGitCounts]:new Array(v.directories.length).fill(0);let N=!1;for(const{dirIndex:k,count:C}of y)S[k]!==C&&(S[k]=C,N=!0);N&&W.updateAreaLocal(b,{directoryGitCounts:S})}}catch{}};return e(),n.current=setInterval(e,pO),()=>{n.current&&(clearInterval(n.current),n.current=null)}},[])}function yj(n=3e3){const[e,t]=x.useState(null),s=x.useRef(null);x.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]);const a=x.useCallback(d=>{s.current&&clearTimeout(s.current),t(d),s.current=setTimeout(()=>{t(f=>f===d?null:f),s.current=null},n)},[n]),r=x.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null),t(null)},[]),i=x.useCallback(d=>e===d,[e]),c=x.useCallback((d,f)=>{e===d?(s.current&&(clearTimeout(s.current),s.current=null),t(null),f()):a(d)},[e,a]);return{isPending:i,arm:a,cancel:r,handleClick:c}}const Zm={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:"",vibrationIntensity:1,tabTitle:"",tmuxMode:!1},Ok=90,eg=["simple","chat","advanced"],Lk=55,Pk=20,Ik=95,mO=200,gO=12e4,bO=5,Zs=new Map;function xO(n){const e=Zs.get(n);e&&(Zs.delete(n),Zs.set(n,e))}function yO(){for(;Zs.size>bO;){const n=Zs.keys().next().value;if(n!==void 0)Zs.delete(n);else break}}function vO(n){Zs.delete(n)}function wO(n){return n.trim().replace(/\r\n/g,`
42
+ */var J0;function eD(){if(J0)return Um;J0=1;var n=Ub();function e(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var t=typeof Object.is=="function"?Object.is:e,s=n.useState,a=n.useEffect,r=n.useLayoutEffect,i=n.useDebugValue;function c(m,b){var y=b(),v=s({inst:{value:y,getSnapshot:b}}),S=v[0].inst,N=v[1];return r(function(){S.value=y,S.getSnapshot=b,d(S)&&N({inst:S})},[m,y,b]),a(function(){return d(S)&&N({inst:S}),m(function(){d(S)&&N({inst:S})})},[m]),i(y),y}function d(m){var b=m.getSnapshot;m=m.value;try{var y=b();return!t(m,y)}catch{return!0}}function f(m,b){return b()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return Um.useSyncExternalStore=n.useSyncExternalStore!==void 0?n.useSyncExternalStore:h,Um}var Z0;function tD(){return Z0||(Z0=1,Hm.exports=eD()),Hm.exports}var nD=tD();const sD=(n,e)=>{if(oo(e))return e;if(HM(e)&&oo(e.defaultValue))return e.defaultValue;if(typeof n=="function")return"";if(Array.isArray(n)){const t=n[n.length-1];return typeof t=="function"?"":t}return n},aD={t:sD,ready:!1},rD=()=>()=>{},ut=(n,e={})=>{var T,M,R;const{i18n:t}=e,{i18n:s,defaultNS:a}=x.useContext(JM)||{},r=t||s||QM();r&&!r.reportNamespaces&&(r.reportNamespaces=new ZM),r||nb(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=x.useMemo(()=>{var O;return{...YM(),...(O=r==null?void 0:r.options)==null?void 0:O.react,...e}},[r,e]),{useSuspense:c,keyPrefix:d}=i,f=n||a||((T=r==null?void 0:r.options)==null?void 0:T.defaultNS),h=oo(f)?[f]:f||["translation"],m=x.useMemo(()=>h,h);(R=(M=r==null?void 0:r.reportNamespaces)==null?void 0:M.addUsedNamespaces)==null||R.call(M,m);const b=x.useRef(0),y=x.useCallback(O=>{if(!r)return rD;const{bindI18n:U,bindI18nStore:H}=i,I=()=>{b.current+=1,O()};return U&&r.on(U,I),H&&r.store.on(H,I),()=>{U&&U.split(" ").forEach($=>r.off($,I)),H&&H.split(" ").forEach($=>r.store.off($,I))}},[r,i]),v=x.useRef(),S=x.useCallback(()=>{if(!r)return aD;const O=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(q=>$M(q,r,i)),U=e.lng||r.language,H=b.current,I=v.current;if(I&&I.ready===O&&I.lng===U&&I.keyPrefix===d&&I.revision===H)return I;const z={t:r.getFixedT(U,i.nsMode==="fallback"?m:m[0],d),ready:O,lng:U,keyPrefix:d,revision:H};return v.current=z,z},[r,m,d,i,e.lng]),[N,k]=x.useState(0),{t:C,ready:A}=nD.useSyncExternalStore(y,S,S);x.useEffect(()=>{if(r&&!A&&!c){const O=()=>k(U=>U+1);e.lng?X0(r,e.lng,m,O):sb(r,m,O)}},[r,e.lng,m,A,c,N]);const E=r||{},D=x.useRef(null),_=x.useRef(),F=O=>{const U=Object.getOwnPropertyDescriptors(O);U.__original&&delete U.__original;const H=Object.create(Object.getPrototypeOf(O),U);if(!Object.prototype.hasOwnProperty.call(H,"__original"))try{Object.defineProperty(H,"__original",{value:O,writable:!1,enumerable:!1,configurable:!1})}catch{}return H},P=x.useMemo(()=>{const O=E,U=O==null?void 0:O.language;let H=O;O&&(D.current&&D.current.__original===O?_.current!==U?(H=F(O),D.current=H,_.current=U):H=D.current:(H=F(O),D.current=H,_.current=U));const I=!A&&!c?(...z)=>(nb(r,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),C(...z)):C,$=[I,H,A];return $.t=I,$.i18n=H,$.ready=A,$},[C,E,A,E.resolvedLanguage,E.language,E.languages]);if(r&&c&&!A)throw new Promise(O=>{const U=()=>O();e.lng?X0(r,e.lng,m,U):sb(r,m,U)});return P};function rb(n){"@babel/helpers - typeof";return rb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rb(n)}function GA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":rb(XMLHttpRequest))==="object"}function iD(n){return!!n&&typeof n.then=="function"}function oD(n){return iD(n)?n:Promise.resolve(n)}var lD=/\{\{(.+?)\}\}/g;function ek(n,e){return n.replace(lD,function(t,s){var a=e[s.trim()];return a??t})}const cD="modulepreload",uD=function(n){return"/"+n},tk={},gt=function(e,t,s){let a=Promise.resolve();if(t&&t.length>0){let i=function(f){return Promise.all(f.map(h=>Promise.resolve(h).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=i(t.map(f=>{if(f=uD(f),f in tk)return;tk[f]=!0;const h=f.endsWith(".css"),m=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const b=document.createElement("link");if(b.rel=h?"stylesheet":cD,h||(b.as="script"),b.crossOrigin="",b.href=f,d&&b.setAttribute("nonce",d),document.head.appendChild(b),h)return new Promise((y,v)=>{b.addEventListener("load",y),b.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${f}`)))})}))}function r(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&r(c.reason);return e().catch(r)})};function nk(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(n,a).enumerable})),t.push.apply(t,s)}return t}function sk(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?nk(Object(t),!0).forEach(function(s){dD(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):nk(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function dD(n,e,t){return(e=fD(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function fD(n){var e=pD(n,"string");return lo(e)=="symbol"?e:e+""}function pD(n,e){if(lo(n)!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(lo(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function lo(n){"@babel/helpers - typeof";return lo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lo(n)}var Ci=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Ci=global.fetch:typeof window<"u"&&window.fetch&&(Ci=window.fetch);var du;GA()&&(typeof global<"u"&&global.XMLHttpRequest?du=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(du=window.XMLHttpRequest));var Of;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Of=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Of=window.ActiveXObject));typeof Ci!="function"&&(Ci=void 0);if(!Ci&&!du&&!Of)try{gt(()=>import("./browser-ponyfill-DZOWXZ4K.js").then(n=>n.b),__vite__mapDeps([0,1])).then(function(n){Ci=n.default}).catch(function(){})}catch{}var ib=function(e,t){if(t&&lo(t)==="object"){var s="";for(var a in t)s+="&"+encodeURIComponent(a)+"="+encodeURIComponent(t[a]);if(!s)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+s.slice(1)}return e},ak=function(e,t,s,a){var r=function(d){if(!d.ok)return s(d.statusText||"Error",{status:d.status});d.text().then(function(f){s(null,{status:d.status,data:f})}).catch(s)};if(a){var i=a(e,t);if(i instanceof Promise){i.then(r).catch(s);return}}typeof fetch=="function"?fetch(e,t).then(r).catch(s):Ci(e,t).then(r).catch(s)},rk=!1,hD=function(e,t,s,a){e.queryStringParams&&(t=ib(t,e.queryStringParams));var r=sk({},typeof e.customHeaders=="function"?e.customHeaders():e.customHeaders);typeof window>"u"&&typeof global<"u"&&typeof global.process<"u"&&global.process.versions&&global.process.versions.node&&(r["User-Agent"]="i18next-http-backend (node/".concat(global.process.version,"; ").concat(global.process.platform," ").concat(global.process.arch,")")),s&&(r["Content-Type"]="application/json");var i=typeof e.requestOptions=="function"?e.requestOptions(s):e.requestOptions,c=sk({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},rk?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{ak(t,c,a,d)}catch(f){if(!i||Object.keys(i).length===0||!f.message||f.message.indexOf("not implemented")<0)return a(f);try{Object.keys(i).forEach(function(h){delete c[h]}),ak(t,c,a,d),rk=!0}catch(h){a(h)}}},mD=function(e,t,s,a){s&&lo(s)==="object"&&(s=ib("",s).slice(1)),e.queryStringParams&&(t=ib(t,e.queryStringParams));try{var r=du?new du:new Of("MSXML2.XMLHTTP.3.0");r.open(s?"POST":"GET",t,1),e.crossDomain||r.setRequestHeader("X-Requested-With","XMLHttpRequest"),r.withCredentials=!!e.withCredentials,s&&r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.overrideMimeType&&r.overrideMimeType("application/json");var i=e.customHeaders;if(i=typeof i=="function"?i():i,i)for(var c in i)r.setRequestHeader(c,i[c]);r.onreadystatechange=function(){r.readyState>3&&a(r.status>=400?r.statusText:null,{status:r.status,data:r.responseText})},r.send(s)}catch(d){console&&console.log(d)}},gD=function(e,t,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Ci&&t.indexOf("file:")!==0)return hD(e,t,s,a);if(GA()||typeof ActiveXObject=="function")return mD(e,t,s,a);a(new Error("No fetch and no xhr implementation found!"))};function wl(n){"@babel/helpers - typeof";return wl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wl(n)}function ik(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(n,a).enumerable})),t.push.apply(t,s)}return t}function Wm(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ik(Object(t),!0).forEach(function(s){YA(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):ik(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function bD(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function xD(n,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(n,KA(s.key),s)}}function yD(n,e,t){return e&&xD(n.prototype,e),Object.defineProperty(n,"prototype",{writable:!1}),n}function YA(n,e,t){return(e=KA(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function KA(n){var e=vD(n,"string");return wl(e)=="symbol"?e:e+""}function vD(n,e){if(wl(n)!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(wl(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(n)}var wD=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(t){return JSON.parse(t)},stringify:JSON.stringify,parsePayload:function(t,s,a){return YA({},s,a||"")},parseLoadPayload:function(t,s){},request:gD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},QA=(function(){function n(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};bD(this,n),this.services=e,this.options=t,this.allOptions=s,this.type="backend",this.init(e,t,s)}return yD(n,[{key:"init",value:function(t){var s=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.services=t,this.options=Wm(Wm(Wm({},wD()),this.options||{}),a),this.allOptions=r,this.services&&this.options.reloadInterval){var i=setInterval(function(){return s.reload()},this.options.reloadInterval);wl(i)==="object"&&typeof i.unref=="function"&&i.unref()}}},{key:"readMulti",value:function(t,s,a){this._readAny(t,t,s,s,a)}},{key:"read",value:function(t,s,a){this._readAny([t],t,[s],s,a)}},{key:"_readAny",value:function(t,s,a,r,i){var c=this,d=this.options.loadPath;typeof this.options.loadPath=="function"&&(d=this.options.loadPath(t,a)),d=oD(d),d.then(function(f){if(!f)return i(null,{});var h=ek(f,{lng:t.join("+"),ns:a.join("+")});c.loadUrl(h,i,s,r)})}},{key:"loadUrl",value:function(t,s,a,r){var i=this,c=typeof a=="string"?[a]:a,d=typeof r=="string"?[r]:r,f=this.options.parseLoadPayload(c,d);this.options.request(this.options,t,f,function(h,m){if(m&&(m.status>=500&&m.status<600||!m.status))return s("failed loading "+t+"; status code: "+m.status,!0);if(m&&m.status>=400&&m.status<500)return s("failed loading "+t+"; status code: "+m.status,!1);if(!m&&h&&h.message){var b=h.message.toLowerCase(),y=["failed","fetch","network","load"].find(function(N){return b.indexOf(N)>-1});if(y)return s("failed loading "+t+": "+h.message,!0)}if(h)return s(h,!1);var v,S;try{typeof m.data=="string"?v=i.options.parse(m.data,a,r):v=m.data}catch{S="failed parsing "+t+" to json"}if(S)return s(S,!1);s(null,v)})}},{key:"create",value:function(t,s,a,r,i){var c=this;if(this.options.addPath){typeof t=="string"&&(t=[t]);var d=this.options.parsePayload(s,a,r),f=0,h=[],m=[];t.forEach(function(b){var y=c.options.addPath;typeof c.options.addPath=="function"&&(y=c.options.addPath(b,s));var v=ek(y,{lng:b,ns:s});c.options.request(c.options,v,d,function(S,N){f+=1,h.push(S),m.push(N),f===t.length&&typeof i=="function"&&i(h,m)})})}}},{key:"reload",value:function(){var t=this,s=this.services,a=s.backendConnector,r=s.languageUtils,i=s.logger,c=a.language;if(!(c&&c.toLowerCase()==="cimode")){var d=[],f=function(m){var b=r.toResolveHierarchy(m);b.forEach(function(y){d.indexOf(y)<0&&d.push(y)})};f(c),this.allOptions.preload&&this.allOptions.preload.forEach(function(h){return f(h)}),d.forEach(function(h){t.allOptions.ns.forEach(function(m){a.read(h,m,"read",null,null,function(b,y){b&&i.warn("loading namespace ".concat(m," for language ").concat(h," failed"),b),!b&&y&&i.log("loaded namespace ".concat(m," for language ").concat(h),y),a.loaded("".concat(h,"|").concat(m),b,y)})})})}}}])})();QA.type="backend";const{slice:kD,forEach:SD}=[];function CD(n){return SD.call(kD.call(arguments,1),e=>{if(e)for(const t in e)n[t]===void 0&&(n[t]=e[t])}),n}function AD(n){return typeof n!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(t=>t.test(n))}const ok=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,jD=function(n,e){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let r=`${n}=${a}`;if(s.maxAge>0){const i=s.maxAge-0;if(Number.isNaN(i))throw new Error("maxAge should be a Number");r+=`; Max-Age=${Math.floor(i)}`}if(s.domain){if(!ok.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!ok.test(s.path))throw new TypeError("option path is invalid");r+=`; Path=${s.path}`}if(s.expires){if(typeof s.expires.toUTCString!="function")throw new TypeError("option expires is invalid");r+=`; Expires=${s.expires.toUTCString()}`}if(s.httpOnly&&(r+="; HttpOnly"),s.secure&&(r+="; Secure"),s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:r+="; SameSite=Strict";break;case"lax":r+="; SameSite=Lax";break;case"strict":r+="; SameSite=Strict";break;case"none":r+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s.partitioned&&(r+="; Partitioned"),r},lk={create(n,e,t,s){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+t*60*1e3)),s&&(a.domain=s),document.cookie=jD(n,e,a)},read(n){const e=`${n}=`,t=document.cookie.split(";");for(let s=0;s<t.length;s++){let a=t[s];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(e)===0)return a.substring(e.length,a.length)}return null},remove(n,e){this.create(n,"",-1,e)}};var ND={name:"cookie",lookup(n){let{lookupCookie:e}=n;if(e&&typeof document<"u")return lk.read(e)||void 0},cacheUserLanguage(n,e){let{lookupCookie:t,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;t&&typeof document<"u"&&lk.create(t,n,s,a,r)}},TD={name:"querystring",lookup(n){var s;let{lookupQuerystring:e}=n,t;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&((s=window.location.hash)==null?void 0:s.indexOf("?"))>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const i=a.substring(1).split("&");for(let c=0;c<i.length;c++){const d=i[c].indexOf("=");d>0&&i[c].substring(0,d)===e&&(t=i[c].substring(d+1))}}return t}},_D={name:"hash",lookup(n){var a;let{lookupHash:e,lookupFromHashIndex:t}=n,s;if(typeof window<"u"){const{hash:r}=window.location;if(r&&r.length>2){const i=r.substring(1);if(e){const c=i.split("&");for(let d=0;d<c.length;d++){const f=c[d].indexOf("=");f>0&&c[d].substring(0,f)===e&&(s=c[d].substring(f+1))}}if(s)return s;if(!s&&t>-1){const c=r.match(/\/([a-zA-Z-]*)/g);return Array.isArray(c)?(a=c[typeof t=="number"?t:0])==null?void 0:a.replace("/",""):void 0}}}return s}};let tl=null;const ck=()=>{if(tl!==null)return tl;try{if(tl=typeof window<"u"&&window.localStorage!==null,!tl)return!1;const n="i18next.translate.boo";window.localStorage.setItem(n,"foo"),window.localStorage.removeItem(n)}catch{tl=!1}return tl};var ED={name:"localStorage",lookup(n){let{lookupLocalStorage:e}=n;if(e&&ck())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupLocalStorage:t}=e;t&&ck()&&window.localStorage.setItem(t,n)}};let nl=null;const uk=()=>{if(nl!==null)return nl;try{if(nl=typeof window<"u"&&window.sessionStorage!==null,!nl)return!1;const n="i18next.translate.boo";window.sessionStorage.setItem(n,"foo"),window.sessionStorage.removeItem(n)}catch{nl=!1}return nl};var MD={name:"sessionStorage",lookup(n){let{lookupSessionStorage:e}=n;if(e&&uk())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupSessionStorage:t}=e;t&&uk()&&window.sessionStorage.setItem(t,n)}},DD={name:"navigator",lookup(n){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:s,language:a}=navigator;if(t)for(let r=0;r<t.length;r++)e.push(t[r]);s&&e.push(s),a&&e.push(a)}return e.length>0?e:void 0}},RD={name:"htmlTag",lookup(n){let{htmlTag:e}=n,t;const s=e||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(t=s.getAttribute("lang")),t}},OD={name:"path",lookup(n){var a;let{lookupFromPathIndex:e}=n;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(a=t[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},LD={name:"subdomain",lookup(n){var a,r;let{lookupFromSubdomainIndex:e}=n;const t=typeof e=="number"?e+1:1,s=typeof window<"u"&&((r=(a=window.location)==null?void 0:a.hostname)==null?void 0:r.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(s)return s[t]}};let XA=!1;try{document.cookie,XA=!0}catch{}const JA=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];XA||JA.splice(1,1);const PD=()=>({order:JA,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:n=>n});class ZA{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=CD(t,this.options||{},PD()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=s,this.addDetector(ND),this.addDetector(TD),this.addDetector(ED),this.addDetector(MD),this.addDetector(DD),this.addDetector(RD),this.addDetector(OD),this.addDetector(LD),this.addDetector(_D)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(s=>{if(this.detectors[s]){let a=this.detectors[s].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(t=t.concat(a))}}),t=t.filter(s=>s!=null&&!AD(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(e,this.options)}))}}ZA.type="languageDetector";const Lf={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},ob={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},WV=["#4a9eff","#4aff9e","#ff9e4a","#ff4a9e","#9e4aff","#ff4a4a","#4affff","#ffff4a","#4ad7ff","#00e6a8","#ff6b4a","#ff66cc","#b84aff","#ff4a7a","#00d9ff","#e6ff4a","#1a3a6e","#1a5e3a","#6e3a1a","#6e1a4a","#4a1a6e","#6e1a1a","#1a5e5e","#5e5e1a","#1a4a6e","#145a47","#6e2c1a","#6e1a5e","#3b1a6e","#6e1a33","#14566e","#4f5e1a"],Wd={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function Vb(n){const t=Math.floor((Date.now()-n)/1e3)/60;return t<1?Wd.recent:t<5?Wd.short:t<30?Wd.medium:Wd.long}function qb(n){return Lf[n]??Lf.default}let xf=null;function ej(){if(!xf)try{xf=globalThis.__i18n}catch{}return xf}function ID(n){xf=n}function BD(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":n.toString()}function FD(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":n.toString()}function zD(n){var a;const e=ej(),t=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),s=Math.floor((Date.now()-n)/1e3);return s<60?t?t("common:time.seconds",{count:s}):`${s}s`:s<3600?t?t("common:time.minutes",{count:Math.floor(s/60)}):`${Math.floor(s/60)}m`:s<86400?t?t("common:time.hours",{count:Math.floor(s/3600)}):`${Math.floor(s/3600)}h`:t?t("common:time.days",{count:Math.floor(s/86400)}):`${Math.floor(s/86400)}d`}function fp(n){var f;const e=ej(),t=(f=e==null?void 0:e.t)==null?void 0:f.bind(e),s=Math.floor((Date.now()-n)/1e3);if(s<5)return t?t("common:time.justNow"):"just now";if(s<60)return t?t("common:time.secondsAgo",{count:s}):`${s}s ago`;const a=Math.floor(s/60);if(a<60){const h=s%60;return h>0?t?t("common:time.minutesSecondsAgo",{minutes:a,seconds:h}):`${a}m ${h}s ago`:t?t("common:time.minutesAgo",{count:a}):`${a}m ago`}const r=Math.floor(a/60),i=a%60;if(r<24)return i>0?t?t("common:time.hoursMinutesAgo",{hours:r,minutes:i}):`${r}h ${i}m ago`:t?t("common:time.hoursAgo",{count:r}):`${r}h ago`;const c=Math.floor(r/24),d=r%24;return d>0?t?t("common:time.daysHoursAgo",{days:c,hours:d}):`${c}d ${d}h ago`:t?t("common:time.daysAgo",{count:c}):`${c}d ago`}function tj(n,e){return n?e?n.replace(/\s*\(?\s*~?\$[\d,.]+\s*\)?/g,"").replace(/\s*cost[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*price[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*\(~?\$[\d,.]+\s*(?:USD|cost|spent)?\)/gi,"").replace(/\s*-\s*~?\$[\d,.]+\s*$/g,"").replace(/[^\S\n]+/g," ").trim():n:""}const $D=Date.now();Sn.use(QA).use(ZA).use(XM).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:`/locales/{{lng}}/{{ns}}.json?v=${$D}`},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{ID(Sn)});const dt={CONFIG:"tide-commander-config",SHOW_FPS:"tide-show-fps",SETTINGS:"tide-settings",SHORTCUTS:"tide-shortcuts",MOUSE_CONTROLS:"tide-mouse-controls",BACKEND_URL:"tide-backend-url",AUTH_TOKEN:"tide-auth-token",SCENE_VIEW_MODE:"tide-scene-view-mode",CAMERA_STATE:"tide-camera-state",CAMERA_STATE_2D:"tide-camera-state-2d",VIEW_MODE:"guake-view-mode",ADVANCED_VIEW:"guake-advanced-view",TERMINAL_HEIGHT:"guake-terminal-height",TERMINAL_FULLSCREEN:"guake-terminal-fullscreen",INPUT_TEXT_PREFIX:"guake-input-",PASTED_TEXTS_PREFIX:"guake-pasted-",COMMANDER_TAB:"commander-active-tab",COMMANDER_FILTERS:"commander-filters",LAST_CWD:"tide-last-cwd",MOBILE_VIEW:"tide-mobile-view",TREE_PANEL_WIDTH:"tide-tree-panel-width",MOBILE_TREE_PANEL_HEIGHT:"tide-mobile-tree-panel-height",AGENT_ORDER:"tide-agent-order",AOP_CONFIG:"tide-aop-config",AOP_OPEN:"tide-aop-open",AOP_TRACKING_BOARD_VISIBLE:"tide-aop-tracking-board-visible",MOBILE_OVERVIEW_HEIGHT:"tide-mobile-overview-height",SPLIT_PANE_AGENT_IDS:"tide-split-pane-agent-ids",SPLIT_PANE_ORIENTATION:"tide-split-pane-orientation",GIT_PANEL_OPEN:"guake-git-panel-open",GIT_PANEL_MODE:"guake-git-panel-mode",GIT_PANEL_VIEW_MODE:"guake-git-view-mode",GIT_PANEL_FOLDER_IDX:"guake-git-folder-idx",BUILDINGS_PANEL_OPEN:"guake-buildings-panel-open",WORKFLOW_PANEL_OPEN:"guake-workflow-panel-open",SIDE_PANEL_WIDTH:"guake-side-panel-width",UNSEEN_AGENTS:"tide-unseen-agents",PENDING_MESSAGES:"tide-pending-messages"},lb="tide-backend-url-change";function ea(n,e){try{const t=localStorage.getItem(n);return t===null?e:JSON.parse(t)}catch{return e}}function ka(n,e=""){try{return localStorage.getItem(n)??e}catch{return e}}function hl(n,e=!1){try{const t=localStorage.getItem(n);return t===null?e:t==="true"}catch{return e}}function Gb(n,e){try{const t=localStorage.getItem(n);if(t===null)return e;const s=Number(t);return isNaN(s)?e:s}catch{return e}}function wa(n,e){try{localStorage.setItem(n,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function er(n,e){try{localStorage.setItem(n,e)}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function to(n,e){try{localStorage.setItem(n,String(e))}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function Yb(n,e){try{localStorage.setItem(n,String(e))}catch(t){console.error(`Failed to save to localStorage: ${n}`,t)}}function dk(n){try{localStorage.removeItem(n)}catch(e){console.error(`Failed to remove from localStorage: ${n}`,e)}}function ra(){const n=Kb();return n?n.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ir(){return ka(dt.AUTH_TOKEN,"")}function Kb(){return ka(dt.BACKEND_URL,"")}function HD(n){const e=n.trim();er(dt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(lb,{detail:e}))}function UD(n){if(typeof window>"u")return()=>{};const e=s=>{n(s.detail)},t=s=>{s.key===dt.BACKEND_URL&&n(s.newValue??"")};return window.addEventListener(lb,e),window.addEventListener("storage",t),()=>{window.removeEventListener(lb,e),window.removeEventListener("storage",t)}}function Et(n){return`${ra()}${n}`}async function Lt(n,e){const t=Ir(),s=new Headers(e==null?void 0:e.headers);return t&&s.set("X-Auth-Token",t),fetch(n,{...e,headers:s,cache:"no-store"})}function fu(n){const e=Ir();if(!e)return n;try{const t=!n.startsWith("http://")&&!n.startsWith("https://"),s=t?"http://dummy":void 0,a=new URL(n,s);return a.searchParams.set("token",e),t?a.pathname+a.search:a.toString()}catch{const t=n.includes("?")?"&":"?";return`${n}${t}token=${encodeURIComponent(e)}`}}function xs(n=!1,e){const[t,s]=x.useState(n),[a,r]=x.useState(e),i=x.useCallback(f=>{f!==void 0&&r(f),s(!0)},[]),c=x.useCallback(()=>{s(!1)},[]),d=x.useCallback(()=>{s(f=>!f)},[]);return{isOpen:t,data:a,open:i,close:c,toggle:d,setData:r}}function WD(){const[n,e]=x.useState(null),t=x.useCallback(a=>{e(a)},[]),s=x.useCallback(()=>{e(null)},[]);return{isOpen:n!==null,id:n,open:t,close:s}}function VD(){const[n,e]=x.useState(!1),[t,s]=x.useState({x:0,y:0}),[a,r]=x.useState({x:0,z:0}),[i,c]=x.useState({type:"ground"}),d=x.useCallback((h,m,b)=>{s(h),r(m),c(b),e(!0)},[]),f=x.useCallback(()=>{e(!1)},[]);return{isOpen:n,screenPosition:t,worldPosition:a,target:i,open:d,close:f}}const ta=[],qD=new Set;function Pf(){qD.forEach(n=>n())}function GD(n,e){const t=ta.findIndex(s=>s.id===n);return t!==-1&&ta.splice(t,1),ta.push({id:n,close:e}),Pf(),()=>{const s=ta.findIndex(a=>a.id===n);s!==-1&&(ta.splice(s,1),Pf())}}function yf(){return ta.length===0?!1:(ta.pop().close(),Pf(),!0)}function YD(n){const e=ta.findIndex(t=>t.id===n);return e===-1?!1:e<ta.length-1}function KD(...n){const e=new Set(n);for(;ta.length>0;){const t=ta[ta.length-1];if(e.has(t.id))break;ta.pop().close()}Pf()}function Jt(n,e,t){const s=x.useRef(t);s.current=t,x.useEffect(()=>e?GD(n,()=>s.current()):void 0,[n,e])}const pu=5,Vm={0:0,1:4,2:8,3:14,4:25,5:50};let eu=null,fk=!1;async function QD(){if(fk)return eu;fk=!0;try{const n=await gt(()=>import("./index-BC1k8mon.js"),__vite__mapDeps([2,3,1,4]));eu={Haptics:n.Haptics,ImpactStyle:n.ImpactStyle}}catch{}return eu}QD();function If(n){const e=Math.round(n),t=e<=0?0:e>=pu?pu:e;if(t!==0){if(eu){const{Haptics:s,ImpactStyle:a}=eu;if(t<=2&&typeof s.selectionChanged=="function"){s.selectionChanged().catch(()=>{navigator.vibrate&&navigator.vibrate(Vm[t])});return}const i={3:"Light",4:"Medium",5:"Heavy"}[t];if(i&&a[i]){s.impact({style:a[i]}).catch(()=>{navigator.vibrate&&navigator.vibrate(Vm[t])});return}}navigator.vibrate&&navigator.vibrate(Vm[t])}}function pk(n,e){const{threshold:t=80,maxVerticalMovement:s=50,enabled:a=!0,onSwipeLeft:r,onSwipeRight:i,onSwipeMove:c,onSwipeCancel:d,vibrationIntensity:f=1}=e,h=x.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=x.useCallback(S=>{if(S.touches.length!==1)return;const N=S.touches[0];h.current={startX:N.clientX,startY:N.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),b=x.useCallback(S=>{if(!h.current.isTracking||S.touches.length!==1)return;const N=S.touches[0],k=N.clientX-h.current.startX;if(Math.abs(N.clientY-h.current.startY)>s){h.current.isTracking=!1,h.current.hasMovedEnough&&(d==null||d());return}const E=window.innerWidth*.4,D=Math.max(-1,Math.min(1,k/E));Math.abs(k)>=12&&(h.current.hasMovedEnough=!0,c==null||c(D))},[s,c,d]),y=x.useCallback(S=>{const N=h.current.isTracking,k=h.current.hasMovedEnough;if(!N)return;const C=S.changedTouches[0],A=C.clientX-h.current.startX,E=Math.abs(C.clientY-h.current.startY),D=Date.now()-h.current.startTime;h.current.isTracking=!1,h.current.hasMovedEnough=!1,Math.abs(A)>=t&&E<=s&&D<500?(If(f),A>0?i==null||i():r==null||r()):k&&(d==null||d())},[t,s,f,r,i,d]),v=x.useCallback(()=>{const S=h.current.hasMovedEnough;h.current.isTracking=!1,h.current.hasMovedEnough=!1,S&&(d==null||d())},[d]);x.useEffect(()=>{const S=n.current;if(!(!S||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return S.addEventListener("touchstart",m,{passive:!0}),S.addEventListener("touchmove",b,{passive:!0}),S.addEventListener("touchend",y,{passive:!0}),S.addEventListener("touchcancel",v,{passive:!0}),()=>{S.removeEventListener("touchstart",m),S.removeEventListener("touchmove",b),S.removeEventListener("touchend",y),S.removeEventListener("touchcancel",v)}},[n,a,m,b,y,v])}const hk=8,XD=.93,mk=.4;function JD(n){const{gestureRef:e,agentListRef:t,enabled:s,onSelect:a}=n,[r,i]=x.useState(!1),[c,d]=x.useState(null),f=x.useRef(!1),h=x.useRef(null),m=x.useRef(a);m.current=a;const b=x.useCallback(()=>{if(f.current)return;f.current=!0,i(!0);const N=t.current;if(N){const k=Math.round(N.clientHeight/2);N.style.paddingTop=`${k}px`,N.style.paddingBottom=`${k}px`}},[t]),y=x.useCallback(()=>{f.current=!1,h.current=null,i(!1),d(null);const N=t.current;N&&(N.style.paddingTop="",N.style.paddingBottom="")},[t]),v=x.useCallback(N=>{const k=t.current;if(!k)return;k.scrollTop+=N;const C=k.getBoundingClientRect(),A=C.top+C.height/2,E=C.left+C.width/2,D=document.elementFromPoint(E,A);let _=null;if(D){const F=D.closest("[data-agent-id]");F&&k.contains(F)&&(_=F.dataset.agentId)}if(_!==h.current&&(h.current=_,d(_),_)){const F=W.getState().settings.vibrationIntensity??1;If(F)}},[t]),S=x.useCallback(()=>{const N=h.current;if(N){const k=W.getState().settings.vibrationIntensity??1,C=k<=0?0:Math.min(k+1,pu);If(C),m.current(N)}y()},[y]);return x.useEffect(()=>{const N=e.current;if(!N||!s)return;const k=N.style.touchAction;N.style.touchAction="none";let C=!1,A=!1,E=0,D=0,_=0,F=0,P=0,T=0,M=0,R=0;const O=()=>{M&&(cancelAnimationFrame(M),M=0)},U=()=>{if(Math.abs(T)<mk){T=0;return}N.scrollTop+=T,T*=XD,M=requestAnimationFrame(U)},H=q=>{if(O(),q.touches.length>=2){q.preventDefault(),C=!1,A=!1,R=(q.touches[0].clientY+q.touches[1].clientY)/2,b(),v(0);return}C=!0,A=!1,E=q.touches[0].clientX,D=q.touches[0].clientY,_=N.scrollTop,F=D,P=performance.now(),T=0},I=q=>{if(q.touches.length>=2){if(q.preventDefault(),(A||C)&&(A=!1,C=!1),!f.current){R=(q.touches[0].clientY+q.touches[1].clientY)/2,b(),v(0);return}const G=(q.touches[0].clientY+q.touches[1].clientY)/2,te=R-G;R=G,v(te);return}if(f.current&&q.touches.length===1){q.preventDefault();const G=q.touches[0].clientY,te=R-G;R=G,v(te);return}if(!C&&!A)return;const Y=q.touches[0].clientX,B=q.touches[0].clientY;if(C&&!A){const G=Math.abs(Y-E),te=Math.abs(B-D);if(G<hk&&te<hk)return;if(te>=G)A=!0,C=!1,q.preventDefault();else{C=!1;return}}if(A){q.preventDefault();const G=performance.now(),te=G-P;N.scrollTop=_+(D-B),te>0&&(T=(F-B)/te*16),F=B,P=G}},$=q=>{if(f.current&&q.touches.length===0){S();return}f.current||(A||C)&&q.touches.length===0&&(A&&Math.abs(T)>mk&&(M=requestAnimationFrame(U)),A=!1,C=!1)},z=()=>{A=!1,C=!1,O(),f.current&&y()};return N.addEventListener("touchstart",H,{passive:!1}),N.addEventListener("touchmove",I,{passive:!1}),N.addEventListener("touchend",$,{passive:!0}),N.addEventListener("touchcancel",z,{passive:!0}),()=>{N.removeEventListener("touchstart",H),N.removeEventListener("touchmove",I),N.removeEventListener("touchend",$),N.removeEventListener("touchcancel",z),N.style.touchAction=k,O();const q=t.current;q&&(q.style.paddingTop="",q.style.paddingBottom="")}},[e,t,s,b,y,v,S]),{isActive:r,hoveredAgentId:c}}function Tc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class ZD{constructor(){et(this,"messages",new Map);et(this,"logs",[]);et(this,"maxMessagesPerAgent",200);et(this,"maxLogs",500);et(this,"enabled",!0);et(this,"listeners",new Set);et(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,t){try{const s=JSON.parse(t);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${t.length}B`),this.addMessage(e,{id:Tc(),agentId:e,direction:"sent",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:t.length,raw:t})}catch(s){console.error("[AgentDebugger] Failed to parse SENT message:",String(s).slice(0,80)),this.addMessage(e,{id:Tc(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:t.length,raw:t})}}captureReceived(e,t){try{const s=JSON.parse(t);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${t.length}B`),this.addMessage(e,{id:Tc(),agentId:e,direction:"received",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:t.length,raw:t})}catch(s){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(s).slice(0,80)),this.addMessage(e,{id:Tc(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:t.length,raw:t})}}addMessage(e,t){let s=this.messages.get(e);s||(s=[],this.messages.set(e,s)),s.push(t),console.log(`[AgentDebugger] Added message for ${e}, total: ${s.length}, type: ${t.type}, direction: ${t.direction}`),s.length>this.maxMessagesPerAgent&&s.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const t=this.getMessages(e),s=t.filter(i=>i.direction==="sent").length,a=t.filter(i=>i.direction==="received").length,r=[...new Set(t.map(i=>i.type))];return{total:t.length,sent:s,received:a,messageTypes:r}}clearMessages(e){this.messages.delete(e),this.notifyListeners(e)}clearAllMessages(){this.messages.clear(),this.notifyListeners("all")}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){this.listeners.forEach(t=>t(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,t,s,a){const r={id:Tc(),level:e,message:t,data:s,timestamp:Date.now(),source:a};this.logs.push(r),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,t,s){this.log("debug",e,t,s)}info(e,t,s){this.log("info",e,t,s)}warn(e,t,s){this.log("warn",e,t,s)}error(e,t,s){this.log("error",e,t,s)}getLogs(){return this.logs}clearLogs(){this.logs=[],this.notifyLogListeners()}subscribeLogs(e){return this.logListeners.add(e),()=>this.logListeners.delete(e)}notifyLogListeners(){this.logListeners.forEach(e=>e())}}const ps=new ZD,hu={debug:(n,e,t)=>ps.debug(n,e,t),info:(n,e,t)=>ps.info(n,e,t),warn:(n,e,t)=>ps.warn(n,e,t),error:(n,e,t)=>ps.error(n,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var kl;(function(n){n.Unimplemented="UNIMPLEMENTED",n.Unavailable="UNAVAILABLE"})(kl||(kl={}));class qm extends Error{constructor(e,t,s){super(e),this.message=e,this.code=t,this.data=s}}const eR=n=>{var e,t;return n!=null&&n.androidBridge?"android":!((t=(e=n==null?void 0:n.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},tR=n=>{const e=n.CapacitorCustomPlatform||null,t=n.Capacitor||{},s=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:eR(n),r=()=>a()!=="web",i=m=>{const b=f.get(m);return!!(b!=null&&b.platforms.has(a())||c(m))},c=m=>{var b;return(b=t.PluginHeaders)===null||b===void 0?void 0:b.find(y=>y.name===m)},d=m=>n.console.error(m),f=new Map,h=(m,b={})=>{const y=f.get(m);if(y)return console.warn(`Capacitor plugin "${m}" already registered. Cannot register plugins twice.`),y.proxy;const v=a(),S=c(m);let N;const k=async()=>(!N&&v in b?N=typeof b[v]=="function"?N=await b[v]():N=b[v]:e!==null&&!N&&"web"in b&&(N=typeof b.web=="function"?N=await b.web():N=b.web),N),C=(P,T)=>{var M,R;if(S){const O=S==null?void 0:S.methods.find(U=>T===U.name);if(O)return O.rtype==="promise"?U=>t.nativePromise(m,T.toString(),U):(U,H)=>t.nativeCallback(m,T.toString(),U,H);if(P)return(M=P[T])===null||M===void 0?void 0:M.bind(P)}else{if(P)return(R=P[T])===null||R===void 0?void 0:R.bind(P);throw new qm(`"${m}" plugin is not implemented on ${v}`,kl.Unimplemented)}},A=P=>{let T;const M=(...R)=>{const O=k().then(U=>{const H=C(U,P);if(H){const I=H(...R);return T=I==null?void 0:I.remove,I}else throw new qm(`"${m}.${P}()" is not implemented on ${v}`,kl.Unimplemented)});return P==="addListener"&&(O.remove=async()=>T()),O};return M.toString=()=>`${P.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:P,writable:!1,configurable:!1}),M},E=A("addListener"),D=A("removeListener"),_=(P,T)=>{const M=E({eventName:P},T),R=async()=>{const U=await M;D({eventName:P,callbackId:U},T)},O=new Promise(U=>M.then(()=>U({remove:R})));return O.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},O},F=new Proxy({},{get(P,T){switch(T){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return S?_:E;case"removeListener":return D;default:return A(T)}}});return s[m]=F,f.set(m,{name:m,proxy:F,platforms:new Set([...Object.keys(b),...S?[v]:[]])}),F};return t.convertFileSrc||(t.convertFileSrc=m=>m),t.getPlatform=a,t.handleError=d,t.isNativePlatform=r,t.isPluginAvailable=i,t.registerPlugin=h,t.Exception=qm,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},nR=n=>n.Capacitor=tR(n),Bf=nR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Au=Bf.registerPlugin;class Qb{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let s=!1;this.listeners[e]||(this.listeners[e]=[],s=!0),this.listeners[e].push(t);const r=this.windowListeners[e];r&&!r.registered&&this.addWindowListener(r),s&&this.sendRetainedArgumentsForEvent(e);const i=async()=>this.removeListener(e,t);return Promise.resolve({remove:i})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,s){const a=this.listeners[e];if(!a){if(s){let r=this.retainedEventArguments[e];r||(r=[]),r.push(t),this.retainedEventArguments[e]=r}return}a.forEach(r=>r(t))}hasListeners(e){var t;return!!(!((t=this.listeners[e])===null||t===void 0)&&t.length)}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:s=>{this.notifyListeners(t,s)}}}unimplemented(e="not implemented"){return new Bf.Exception(e,kl.Unimplemented)}unavailable(e="not available"){return new Bf.Exception(e,kl.Unavailable)}async removeListener(e,t){const s=this.listeners[e];if(!s)return;const a=s.indexOf(t);this.listeners[e].splice(a,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(s=>{this.notifyListeners(e,s)}))}}const gk=n=>encodeURIComponent(n).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),bk=n=>n.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class sR extends Qb{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach(s=>{if(s.length<=0)return;let[a,r]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=bk(a).trim(),r=bk(r).trim(),t[a]=r}),t}async setCookie(e){try{const t=gk(e.key),s=gk(e.value),a=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",r=(e.path||"/").replace("path=",""),i=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${s||""}${a}; path=${r}; ${i};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}Au("CapacitorCookies",{web:()=>new sR});const aR=async n=>new Promise((e,t)=>{const s=new FileReader;s.onload=()=>{const a=s.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},s.onerror=a=>t(a),s.readAsDataURL(n)}),rR=(n={})=>{const e=Object.keys(n);return Object.keys(n).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=n[e[i]],a),{})},iR=(n,e=!0)=>n?Object.entries(n).reduce((s,a)=>{const[r,i]=a;let c,d;return Array.isArray(i)?(d="",i.forEach(f=>{c=e?encodeURIComponent(f):f,d+=`${r}=${c}&`}),d.slice(0,-1)):(c=e?encodeURIComponent(i):i,d=`${r}=${c}`),`${s}&${d}`},"").substr(1):null,oR=(n,e={})=>{const t=Object.assign({method:n.method||"GET",headers:n.headers},e),a=rR(n.headers)["content-type"]||"";if(typeof n.data=="string")t.body=n.data;else if(a.includes("application/x-www-form-urlencoded")){const r=new URLSearchParams;for(const[i,c]of Object.entries(n.data||{}))r.set(i,c);t.body=r.toString()}else if(a.includes("multipart/form-data")||n.data instanceof FormData){const r=new FormData;if(n.data instanceof FormData)n.data.forEach((c,d)=>{r.append(d,c)});else for(const c of Object.keys(n.data))r.append(c,n.data[c]);t.body=r;const i=new Headers(t.headers);i.delete("content-type"),t.headers=i}else(a.includes("application/json")||typeof n.data=="object")&&(t.body=JSON.stringify(n.data));return t};class lR extends Qb{async request(e){const t=oR(e,e.webFetchExtra),s=iR(e.params,e.shouldEncodeUrlParams),a=s?`${e.url}?${s}`:e.url,r=await fetch(a,t),i=r.headers.get("content-type")||"";let{responseType:c="text"}=r.ok?e:{};i.includes("application/json")&&(c="json");let d,f;switch(c){case"arraybuffer":case"blob":f=await r.blob(),d=await aR(f);break;case"json":d=await r.json();break;case"document":case"text":default:d=await r.text()}const h={};return r.headers.forEach((m,b)=>{h[b]=m}),{data:d,headers:h,status:r.status,url:r.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}const VV=Au("CapacitorHttp",{web:()=>new lR});var xk;(function(n){n.Dark="DARK",n.Light="LIGHT",n.Default="DEFAULT"})(xk||(xk={}));var yk;(function(n){n.StatusBar="StatusBar",n.NavigationBar="NavigationBar"})(yk||(yk={}));class cR extends Qb{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}Au("SystemBars",{web:()=>new cR});var vk;(function(n){n[n.Sunday=1]="Sunday",n[n.Monday=2]="Monday",n[n.Tuesday=3]="Tuesday",n[n.Wednesday=4]="Wednesday",n[n.Thursday=5]="Thursday",n[n.Friday=6]="Friday",n[n.Saturday=7]="Saturday"})(vk||(vk={}));const Xb=Au("LocalNotifications",{web:()=>gt(()=>import("./web-BaEueqP3.js"),__vite__mapDeps([5,3,1,4])).then(n=>new n.LocalNotificationsWeb)}),uR=Au("ServerConfig");let dR=100;const fR="agent_alerts",cb="tide-notification-tap";function pR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function nj(n){if(pR()){W.openTerminalOnMobile(n);return}if(document.querySelector(".commander-overlay")){W.requestCommanderExpand(n);return}W.selectAgent(n),W.setTerminalOpen(!0)}function ju(){try{return Bf.isNativePlatform()}catch{return!1}}async function hR(){if(ju())try{const n=await Xb.requestPermissions();return console.log("[Notifications] Permission result:",n.display),n.display==="granted"}catch(n){return console.error("[Notifications] Failed to request permissions:",n),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function mR(n){const{title:e,body:t,icon:s,data:a}=n;if(ju())try{const r=dR++;console.log("[Notifications] Scheduling native notification id="+r,e),await Xb.schedule({notifications:[{id:r,title:e,body:t,extra:a,channelId:fR,smallIcon:"ic_launcher",autoCancel:!0}]}),console.log("[Notifications] Notification scheduled successfully")}catch(r){console.error("[Notifications] Failed to schedule notification:",r)}else if("Notification"in window&&Notification.permission==="granted"){const r=new Notification(e,{body:t,icon:s,data:a});r.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(cb,{detail:a}))}}}let Gm=!1;async function gR(n){const e=[];if(Gm)return()=>{};if(Gm=!0,n){const t=s=>{const a=s;a.detail&&n(a.detail)};window.addEventListener(cb,t),e.push(()=>window.removeEventListener(cb,t))}if(ju())try{const t=await Xb.addListener("localNotificationActionPerformed",s=>{n&&s.notification.extra&&n(s.notification.extra)});e.push(()=>t.remove())}catch(t){console.error("[Notifications] Failed to add tap listener:",t)}return()=>{e.forEach(t=>t()),Gm=!1}}function bR(n,e){ju()&&uR.syncConfig({url:n,token:e}).catch(t=>{console.warn("[Notifications] Failed to sync config to native service:",t)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const pp=()=>window.__tideWsState.ws,wk=n=>{window.__tideWsState.ws=n},xR=()=>window.__tideWsState.isConnecting,_c=n=>{window.__tideWsState.isConnecting=n},ub=()=>window.__tideWsState.reconnectAttempts,db=n=>{window.__tideWsState.reconnectAttempts=n},sj=()=>window.__tideWsState.reconnectTimeout,aj=n=>{window.__tideWsState.reconnectTimeout=n},kk=10,Jb="tide_ws_has_connected";function Sk(){return sessionStorage.getItem(Jb)==="true"}function yR(n){sessionStorage.setItem(Jb,"true")}function vR(){sessionStorage.removeItem(Jb)}let rj=null;const wR=n=>{rj=n},Ck=()=>rj,Pe={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function ij(n){n.onToast&&(Pe.onToast=n.onToast),n.onAgentCreated&&(Pe.onAgentCreated=n.onAgentCreated),n.onAgentUpdated&&(Pe.onAgentUpdated=n.onAgentUpdated),n.onAgentDeleted&&(Pe.onAgentDeleted=n.onAgentDeleted),n.onAgentsSync&&(Pe.onAgentsSync=n.onAgentsSync),n.onAreasSync&&(Pe.onAreasSync=n.onAreasSync),n.onSpawnError&&(Pe.onSpawnError=n.onSpawnError),n.onSpawnSuccess&&(Pe.onSpawnSuccess=n.onSpawnSuccess),n.onToolUse&&(Pe.onToolUse=n.onToolUse),n.onDirectoryNotFound&&(Pe.onDirectoryNotFound=n.onDirectoryNotFound),n.onDelegation&&(Pe.onDelegation=n.onDelegation),n.onCustomClassesSync&&(Pe.onCustomClassesSync=n.onCustomClassesSync),n.onReconnect&&(Pe.onReconnect=n.onReconnect),n.onAgentNotification&&(Pe.onAgentNotification=n.onAgentNotification),n.onBuildingUpdated&&(Pe.onBuildingUpdated=n.onBuildingUpdated),n.onSubagentStarted&&(Pe.onSubagentStarted=n.onSubagentStarted),n.onSubagentCompleted&&(Pe.onSubagentCompleted=n.onSubagentCompleted)}function kR(){Pe.onToast=null,Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onSpawnError=null,Pe.onSpawnSuccess=null,Pe.onToolUse=null,Pe.onDirectoryNotFound=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onReconnect=null,Pe.onAgentNotification=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}function SR(){Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onToolUse=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onBuildingUpdated=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}const Vd=new Map,CR=new Map,fb={start(n){},end(n){},async measure(n,e){this.start(n);try{return await e()}finally{this.end(n)}},measureSync(n,e){this.start(n);try{return e()}finally{this.end(n)}},getMetrics(n){const e={},t=n?Vd.has(n)?[[n,Vd.get(n)]]:[]:Array.from(Vd.entries());for(const[s,a]of t){const r=[...a.samples].sort((f,h)=>f-h),i=Math.floor(r.length*.5),c=Math.floor(r.length*.95),d=Math.floor(r.length*.99);e[s]={count:a.count,avgMs:a.totalMs/a.count,minMs:a.minMs,maxMs:a.maxMs,lastMs:a.lastMs,p50Ms:r[i]||0,p95Ms:r[c]||0,p99Ms:r[d]||0}}return e},clear(){Vd.clear(),CR.clear()},report(){}};class AR{constructor(){et(this,"frames",[]);et(this,"lastFrameTime",0);et(this,"frameCount",0);et(this,"fps",0);et(this,"minFps",1/0);et(this,"maxFps",0);et(this,"fpsHistory",[]);et(this,"maxHistorySize",60)}tick(e=200){const t=performance.now();if(this.lastFrameTime>0){const s=t-this.lastFrameTime;s<e&&(this.frames.push(s),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=t,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((t,s)=>t+s,0)/this.frames.length;this.fps=1e3/e,this.minFps=Math.min(this.minFps,this.fps),this.maxFps=Math.max(this.maxFps,this.fps),this.fpsHistory.push(this.fps),this.fpsHistory.length>this.maxHistorySize&&this.fpsHistory.shift()}getFPS(){return Math.round(this.fps)}getStats(){const e=this.fpsHistory.length>0?this.fpsHistory.reduce((t,s)=>t+s,0)/this.fpsHistory.length:this.fps;return{current:Math.round(this.fps),min:Math.round(this.minFps===1/0?0:this.minFps),max:Math.round(this.maxFps),avg:Math.round(e)}}reset(){this.frames=[],this.lastFrameTime=0,this.frameCount=0,this.fps=0,this.minFps=1/0,this.maxFps=0,this.fpsHistory=[]}}const qd=new AR;class jR{constructor(){et(this,"snapshots",[]);et(this,"maxSnapshots",120);et(this,"intervalId",null);et(this,"leakThresholdMB",50);et(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const t=this.getUsage();t&&(this.baselineUsedMB=t.usedMB),this.intervalId=setInterval(()=>{this.takeSnapshot()},e),console.log("[Memory] Monitoring started. Use memory.report() to see analysis.")}stopMonitoring(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.log("[Memory] Monitoring stopped."))}takeSnapshot(){const e=this.getUsage();if(!e)return;const t={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(t),this.snapshots.length>this.maxSnapshots&&this.snapshots.shift();const s=e.usedMB-this.baselineUsedMB;s>this.leakThresholdMB&&console.warn(`[Memory] Warning: Heap grew by ${s}MB since monitoring started (baseline: ${this.baselineUsedMB}MB, current: ${e.usedMB}MB)`)}getGrowthRate(){if(this.snapshots.length<10)return null;const e=this.snapshots[0],t=this.snapshots[this.snapshots.length-1],s=(t.timestamp-e.timestamp)/1e3/60;return s<.1?null:(t.heapUsedMB-e.heapUsedMB)/s}report(){const e=this.getUsage();if(!e){console.log("[Memory] Memory API not available (Chrome only)");return}console.group("%c[Memory Report]","color: #ff6600; font-weight: bold"),console.log(`Current: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`),console.log(`Baseline: ${this.baselineUsedMB}MB`),console.log(`Growth: ${e.usedMB-this.baselineUsedMB}MB since monitoring started`);const t=this.getGrowthRate();if(t!==null&&(console.log(`Growth Rate: ${t.toFixed(2)}MB/min`),t>5&&console.warn("POTENTIAL MEMORY LEAK: Growth rate exceeds 5MB/min")),this.snapshots.length>1){const s=Math.min(...this.snapshots.map(r=>r.heapUsedMB)),a=Math.max(...this.snapshots.map(r=>r.heapUsedMB));console.log(`Range: ${s}MB - ${a}MB (${a-s}MB variance)`)}console.groupEnd()}getThreeJsInfo(e){var t;return(t=e==null?void 0:e.info)!=null&&t.memory?{geometries:e.info.memory.geometries,textures:e.info.memory.textures}:null}reset(){this.snapshots=[];const e=this.getUsage();e&&(this.baselineUsedMB=e.usedMB),console.log("[Memory] Reset. New baseline:",this.baselineUsedMB,"MB")}}const Ec=new jR;function pb(n,e,t,s,a,r){}function oj(n,e){x.useRef(0),x.useEffect(()=>{},[n,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}const hb=dt.PENDING_MESSAGES,NR=300*1e3;function lj(){try{const n=localStorage.getItem(hb);if(!n)return[];const e=JSON.parse(n),t=Date.now();return e.filter(s=>t-s.queuedAt<NR)}catch{return[]}}function cj(n){try{n.length===0?localStorage.removeItem(hb):localStorage.setItem(hb,JSON.stringify(n))}catch{}}function Gd(n){const e=lj();e.push({message:n,queuedAt:Date.now()}),cj(e)}function TR(){var s;const n=lj();if(n.length===0)return 0;let e=0;const t=[];for(const a of n)_R(a.message)?e++:t.push(a);if(cj(t),e>0){const a=e===1?"queued message":"queued messages";(s=Pe.onToast)==null||s.call(Pe,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function Zb(n){if(n.payload&&typeof n.payload=="object"){const e=n.payload;if(e.agentId)return e.agentId;if(e.parentAgentId)return e.parentAgentId;if(e.bossId)return e.bossId;if(e.id)return e.id}return null}function _R(n){const e=pp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const t=JSON.stringify(n),s=Zb(n);return console.log("[AgentDebugger] SENT - type:",n.type,"agentId:",s,"payload:",n.payload),s&&ps.captureSent(s,t),e.send(t),!0}catch{return!1}}function ex(n){var t,s,a,r,i,c,d,f,h,m;const e=pp();if(!e)return(t=Ck())==null||t(),n.type==="send_command"?(Gd(n),(s=Pe.onToast)==null||s.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=Pe.onToast)==null||a.call(Pe,"error","Not Connected","Connecting to server... Please try again in a moment."),!1;if(e.readyState!==WebSocket.OPEN)return e.readyState===WebSocket.CONNECTING?n.type==="send_command"?(Gd(n),(r=Pe.onToast)==null||r.call(Pe,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=Pe.onToast)==null||i.call(Pe,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Ck())==null||c(),n.type==="send_command"?(Gd(n),(d=Pe.onToast)==null||d.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=Pe.onToast)==null||f.call(Pe,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const b=JSON.stringify(n),y=Zb(n);return console.log("[AgentDebugger] SENT - type:",n.type,"agentId:",y,"payload:",n.payload),y&&ps.captureSent(y,b),e.send(b),!0}catch(b){return n.type==="send_command"?(Gd(n),(h=Pe.onToast)==null||h.call(Pe,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=Pe.onToast)==null||m.call(Pe,"error","Send Failed",`Failed to send message: ${b}`),!1}}const qc=new Set,ER=5e3;function Ak(n){if(!n.isDetached||!n.sessionId){qc.delete(n.id);return}qc.has(n.id)||(qc.add(n.id),ex({type:"reattach_agent",payload:{agentId:n.id}}),setTimeout(()=>{qc.delete(n.id)},ER))}function MR(n){var e,t,s,a,r,i,c,d,f,h,m,b,y,v,S,N,k,C,A,E,D,_,F,P;switch(fb.start(`ws:${n.type}`),n.type){case"agents_update":{const T=n.payload,M=T.filter(R=>R.class==="boss"||R.isBoss);M.length>0&&console.log("[WS agents_update] Boss agents received:",M.map(R=>({id:R.id,name:R.name,subordinateIds:R.subordinateIds}))),W.setAgents(T),(e=Pe.onAgentsSync)==null||e.call(Pe,T),W.loadToolHistory();for(const R of T)Ak(R);break}case"agent_created":{const T=n.payload;console.log("[WebSocket] Agent created:",T),W.addAgent(T);const M=(t=window.__spawnModalAreaContext)==null?void 0:t.areaId;M&&(W.assignAgentToArea(T.id,M),window.__spawnModalAreaContext=null),W.selectAgent(T.id),(s=Pe.onAgentCreated)==null||s.call(Pe,T),(a=Pe.onSpawnSuccess)==null||a.call(Pe),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=Pe.onToast)==null||r.call(Pe,"success","Agent Deployed",`${T.name} is ready for commands`);break}case"agent_updated":{const T=n.payload,R=W.getState().agents.get(T.id),O=(R==null?void 0:R.status)!==T.status;console.log(`[Tide] Agent updated: ${T.name} (${T.id}) status=${T.status} (was ${R==null?void 0:R.status})${O?" ⚡ STATUS CHANGED":""}`),O&&console.log(`[Tide] 🔔 Status change for ${T.name}: ${R==null?void 0:R.status} → ${T.status}`),O&&(R==null?void 0:R.status)==="working"&&T.status==="idle"&&W.triggerHistoryRefresh(T.id);const U=R?R.position.x!==T.position.x||R.position.z!==T.position.z:!1;W.updateAgent(T),Ak(T),(i=Pe.onAgentUpdated)==null||i.call(Pe,T,U);break}case"agent_deleted":{const{id:T}=n.payload;qc.delete(T),W.removeAgent(T),(c=Pe.onAgentDeleted)==null||c.call(Pe,T);break}case"activity":{const T=n.payload;W.addActivity(T);break}case"event":{const T=n.payload;if(hu.debug(`Event: ${T.type}`,{agentId:T.agentId,toolName:T.toolName},"ws:event"),T.type==="tool_start"&&T.toolName&&((d=Pe.onToolUse)==null||d.call(Pe,T.agentId,T.toolName,T.toolInput),W.addToolExecution(T.agentId,T.toolName,T.toolInput),T.toolInput)){const M=T.toolInput.file_path||T.toolInput.path;M&&(T.toolName==="Write"?W.addFileChange(T.agentId,"created",M):T.toolName==="Edit"?W.addFileChange(T.agentId,"modified",M):T.toolName==="Read"&&W.addFileChange(T.agentId,"read",M))}break}case"output":{const T=n.payload;hu.debug(`Output: "${T.text.slice(0,80)}..."`,{agentId:T.agentId,isStreaming:T.isStreaming,length:T.text.length,hasSkillUpdate:!!T.skillUpdate,uuid:T.uuid,toolName:T.toolName},"ws:output"),W.addOutput(T.agentId,{text:T.text,isStreaming:T.isStreaming,timestamp:T.timestamp,isDelegation:T.isDelegation,skillUpdate:T.skillUpdate,subagentName:T.subagentName,uuid:T.uuid,toolName:T.toolName,toolInput:T.toolInput,toolOutput:T.toolOutput});break}case"context_stats":{const{agentId:T,stats:M}=n.payload;console.log(`[Tide] Received context stats for agent ${T}: ${M.usedPercent}% used`),W.updateAgentContextStats(T,M);break}case"context_update":{const{agentId:T,contextUsed:M,contextLimit:R}=n.payload;W.updateAgentContext(T,M,R);break}case"compacting_status":{const{agentId:T,active:M}=n.payload;W.setAgentCompacting(T,M);break}case"error":{const T=n.payload;console.error("[WebSocket] Error from server:",T.message),(f=Pe.onToast)==null||f.call(Pe,"error","Error",T.message),(h=Pe.onSpawnError)==null||h.call(Pe),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:T}=n.payload;console.log("[WebSocket] Directory not found:",T),(m=Pe.onDirectoryNotFound)==null||m.call(Pe,T),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(T));break}case"command_started":{const{agentId:T,command:M}=n.payload,R=M.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;W.addUserPromptToOutput(T,M);break}case"session_updated":{const{agentId:T}=n.payload;W.loadToolHistory(),W.triggerHistoryRefresh(T);const M=W.getState().agents.get(T);M&&W.updateAgent({...M});break}case"areas_update":{const T=n.payload;W.setAreasFromServer(T),(b=Pe.onAreasSync)==null||b.call(Pe);break}case"buildings_update":{const T=n.payload;W.setBuildingsFromServer(T);break}case"building_created":{const T=n.payload;W.addBuilding(T);break}case"building_updated":{const T=n.payload;W.updateBuildingFromServer(T),(y=Pe.onBuildingUpdated)==null||y.call(Pe,T);break}case"building_deleted":{const{id:T}=n.payload;W.removeBuildingFromServer(T);break}case"building_logs":{const{buildingId:T,logs:M}=n.payload;W.addBuildingLogs(T,M);break}case"pm2_logs_chunk":{const{buildingId:T,chunk:M}=n.payload;W.appendStreamingLogChunk(T,M);break}case"pm2_logs_streaming":{const{buildingId:T,streaming:M}=n.payload;W.setStreamingStatus(T,M);break}case"docker_logs_chunk":{const{buildingId:T,chunk:M}=n.payload;W.appendStreamingLogChunk(T,M);break}case"docker_logs_streaming":{const{buildingId:T,streaming:M}=n.payload;W.setStreamingStatus(T,M);break}case"docker_containers_list":{const{containers:T,composeProjects:M}=n.payload;console.log(`[WebSocket] Received ${T.length} containers, ${M.length} compose projects`),W.setDockerContainersList(T,M);break}case"boss_building_logs_chunk":{const{bossBuildingId:T,subordinateBuildingId:M,subordinateBuildingName:R,chunk:O,isError:U}=n.payload;W.appendBossStreamingLogChunk(T,M,R,O,U);break}case"boss_building_subordinates_updated":{const{bossBuildingId:T,subordinateBuildingIds:M}=n.payload;W.updateBuilding(T,{subordinateBuildingIds:M});break}case"permission_request":{const T=n.payload;W.addPermissionRequest(T);break}case"permission_resolved":{const{requestId:T,approved:M}=n.payload;W.resolvePermissionRequest(T,M);break}case"delegation_decision":{const T=n.payload;W.handleDelegationDecision(T),T.status==="sent"&&((v=Pe.onToast)==null||v.call(Pe,"info","Task Delegated",`Delegated to ${T.selectedAgentName}: ${T.reasoning.slice(0,80)}...`),T.bossId&&T.selectedAgentId&&((S=Pe.onDelegation)==null||S.call(Pe,T.bossId,T.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:T,subordinateIds:M}=n.payload;W.updateBossSubordinates(T,M);break}case"delegation_history":{const{bossId:T,decisions:M}=n.payload;W.setDelegationHistory(T,M);break}case"session_history":{const{agentId:T,entries:M}=n.payload;W.setSessionHistory(T,M);break}case"boss_spawned_agent":{const{agent:T,bossPosition:M}=n.payload;console.log("[WebSocket] Boss spawned agent:",T.name,"- walking to boss at",M),W.addAgent(T),(N=Pe.onAgentCreated)==null||N.call(Pe,T),ex({type:"move_agent",payload:{agentId:T.id,position:M}}),(k=Pe.onToast)==null||k.call(Pe,"success","Agent Deployed",`${T.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:T,subordinateId:M,subordinateName:R,taskDescription:O}=n.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${T}: ${O.slice(0,50)}...`),W.handleAgentTaskStarted(T,M,R,O);break}case"agent_task_output":{const{bossId:T,subordinateId:M,output:R,isStreaming:O,timestamp:U,subagentName:H,toolName:I,toolInput:$,toolOutput:z}=n.payload;W.handleAgentTaskOutput(T,M,{text:R,isStreaming:O||!1,timestamp:U||Date.now(),subagentName:H,toolName:I,toolInput:$,toolOutput:z});break}case"agent_task_completed":{const{bossId:T,subordinateId:M,success:R}=n.payload;console.log(`[WebSocket] Agent task completed for boss ${T}, subordinate ${M}, success: ${R}`),W.handleAgentTaskCompleted(T,M,R);break}case"skills_update":{const T=n.payload;W.setSkillsFromServer(T);break}case"skill_created":{const T=n.payload;W.addSkillFromServer(T),console.log(`[WebSocket] Skill created: ${T.name}`);break}case"skill_updated":{const T=n.payload;W.updateSkillFromServer(T),console.log(`[WebSocket] Skill updated: ${T.name}`);break}case"skill_deleted":{const{id:T}=n.payload;W.removeSkillFromServer(T),console.log(`[WebSocket] Skill deleted: ${T}`);break}case"agent_skills":{const{agentId:T,skills:M}=n.payload;console.log(`[WebSocket] Agent ${T} has ${M.length} skills`);break}case"custom_agent_classes_update":{const T=n.payload;W.setCustomAgentClassesFromServer(T),console.log(`[WebSocket] Received ${T.length} custom agent classes`);const M=new Map;for(const R of T)M.set(R.id,R);(C=Pe.onCustomClassesSync)==null||C.call(Pe,M);break}case"custom_agent_class_created":{const T=n.payload;W.addCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class created: ${T.name}`),(A=Pe.onCustomClassesSync)==null||A.call(Pe,W.getState().customAgentClasses);break}case"custom_agent_class_updated":{const T=n.payload;W.updateCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class updated: ${T.name}`),(E=Pe.onCustomClassesSync)==null||E.call(Pe,W.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:T}=n.payload;W.removeCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class deleted: ${T}`),(D=Pe.onCustomClassesSync)==null||D.call(Pe,W.getState().customAgentClasses);break}case"agent_notification":{const T=n.payload;console.log(`[WebSocket] Agent notification from ${T.agentName}: ${T.title}`),(_=Pe.onAgentNotification)==null||_.call(Pe,T);break}case"focus_agent":{const{agentId:T,openTerminal:M}=n.payload;if(!W.getState().agents.get(T)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${T}`);break}W.selectAgent(T),M&&W.setTerminalOpen(!0);const O=[0,80,220,500,1e3];for(const U of O)window.setTimeout(()=>{window.focus()},U);break}case"exec_task_started":{const{taskId:T,agentId:M,agentName:R,command:O,cwd:U}=n.payload;console.log(`[WebSocket] Exec task started: ${T} for agent ${R}: ${O.slice(0,50)}...`),W.handleExecTaskStarted(T,M,R,O,U);break}case"exec_task_output":{const{taskId:T,agentId:M,output:R,isError:O}=n.payload;W.handleExecTaskOutput(T,M,R,O);break}case"exec_task_completed":{const{taskId:T,agentId:M,exitCode:R,success:O}=n.payload;console.log(`[WebSocket] Exec task completed: ${T} for agent ${M}, success: ${O}`),W.handleExecTaskCompleted(T,M,R,O);break}case"subagent_started":{const T=n.payload;console.log(`[WebSocket] Subagent started: ${T.name} (${T.id}) for agent ${T.parentAgentId}`),W.addSubagent(T),(F=Pe.onSubagentStarted)==null||F.call(Pe,T);break}case"subagent_output":{const{subagentId:T,parentAgentId:M,text:R,timestamp:O}=n.payload,U=R.indexOf(":");if(U>0){const H=R.slice(0,U).trim(),I=R.slice(U+1).trim();W.addSubagentActivity(T,M,{toolName:H,description:I,timestamp:O})}else R.startsWith("Using ")&&W.addSubagentActivity(T,M,{toolName:R.slice(6).trim(),description:"",timestamp:O});break}case"subagent_completed":{const{subagentId:T,parentAgentId:M,success:R,resultPreview:O,subagentName:U,durationMs:H,tokensUsed:I,toolUseCount:$}=n.payload;console.log(`[WebSocket] Subagent completed: ${T} for agent ${M}, success: ${R}`),(H||I||$)&&W.updateSubagentStats(T,M,{durationMs:H||0,tokensUsed:I||0,toolUseCount:$||0}),W.completeSubagent(T,M,R),(P=Pe.onSubagentCompleted)==null||P.call(Pe,T);const z=W.getSubagent(T)||W.getSubagentByToolUseId(T),q=U||(z==null?void 0:z.name)||T,Y=R?"✅":"❌",B=H?` (${(H/1e3).toFixed(0)}s · ${((I||0)/1e3).toFixed(1)}K tokens · ${$||0} tools)`:"";W.addOutput(M,{text:`${Y} Subagent ${q} ${R?"completed":"failed"}${B}`,isStreaming:!1,timestamp:Date.now(),subagentName:q,toolOutput:O});break}case"subagent_stream":{const{toolUseId:T,parentAgentId:M,entries:R}=n.payload;W.addSubagentStreamEntries(T,M,R);break}case"secrets_update":{const T=n.payload;W.setSecretsFromServer(T),console.log(`[WebSocket] Received ${T.length} secrets`);break}case"secret_created":{const T=n.payload;W.addSecretFromServer(T),console.log(`[WebSocket] Secret created: ${T.name}`);break}case"secret_updated":{const T=n.payload;W.updateSecretFromServer(T),console.log(`[WebSocket] Secret updated: ${T.name}`);break}case"secret_deleted":{const{id:T}=n.payload;W.removeSecretFromServer(T),console.log(`[WebSocket] Secret deleted: ${T}`);break}case"database_connection_result":{const{buildingId:T,connectionId:M,success:R,error:O,serverVersion:U}=n.payload;W.setConnectionStatus(T,M,{connected:R,error:O,serverVersion:U}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${M}`);break}case"databases_list":{const{buildingId:T,connectionId:M,databases:R}=n.payload;W.setDatabases(T,M,R),console.log(`[WebSocket] Received ${R.length} databases for ${M}`);break}case"tables_list":{const{buildingId:T,connectionId:M,database:R,tables:O}=n.payload;W.setTables(T,M,R,O),console.log(`[WebSocket] Received ${O.length} tables for ${R}`);break}case"table_schema":{const{buildingId:T,connectionId:M,database:R,table:O,columns:U,indexes:H,foreignKeys:I}=n.payload;W.setTableSchema(T,M,R,O,{columns:U,indexes:H||[],foreignKeys:I||[]}),console.log(`[WebSocket] Received schema for ${O}`);break}case"query_result":{const{buildingId:T,result:M}=n.payload;W.setQueryResult(T,M),console.log(`[WebSocket] Query ${M.status}: ${M.rowCount??M.affectedRows??0} rows in ${M.duration}ms`);break}case"silent_query_result":{const{buildingId:T,query:M,requestId:R,success:O,affectedRows:U,error:H}=n.payload;W.setSilentQueryResult(T,{query:M,requestId:R,success:O,affectedRows:U,error:H}),console.log(`[WebSocket] Silent query ${O?"succeeded":"failed"}: ${U??0} affected rows`);break}case"query_history_update":{const{buildingId:T,history:M}=n.payload;W.setQueryHistory(T,M),console.log(`[WebSocket] Received ${M.length} query history entries for ${T}`);break}}fb.end(`ws:${n.type}`)}wR(()=>mu());let jk=!1;function uj(){const n=pp();n&&n.readyState===WebSocket.OPEN&&n.close(1e3,"Page unloading");const e=sj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),vR()}function DR(){jk||(window.addEventListener("beforeunload",uj),jk=!0)}function dj(){uj(),W.setConnected(!1),W.stopStatusPolling()}function RR(){dj(),db(0),setTimeout(()=>mu(),100)}function mu(){DR();const n=sj();n&&(clearTimeout(n),aj(null));const e=pp();if(xR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Sk()&&Pe.onReconnect&&Pe.onReconnect();return}db(ub()+1),_c(!0);const t=Kb(),s=Ir(),a=6200;let r;if(t){const c=t.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://");r=c.endsWith("/ws")?c:`${c.replace(/\/$/,"")}/ws`}else r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let i=null;try{s?i=new WebSocket(r,[`auth-${s}`]):i=new WebSocket(r)}catch{_c(!1),Nk();return}wk(i),i.onopen=()=>{var d,f,h;const c=Sk();_c(!1),db(0),yR(),W.setConnected(!0),W.startStatusPolling(),W.clearAllPermissions(),c?((d=Pe.onToast)==null||d.call(Pe,"success","Reconnected","Connection restored - refreshing data..."),(f=Pe.onReconnect)==null||f.call(Pe)):(h=Pe.onToast)==null||h.call(Pe,"success","Connected","Connected to Tide Commander server"),bR(t,s),TR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=Zb(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&ps.captureReceived(f,c.data),MR(d)}catch(d){const f=c.data.substring(0,200);console.error("[WS] Failed to parse message:",d),console.error("[WS] Raw data (first 200 chars):",f),console.error("[WS] Full data length:",c.data.length),c.data.length<5e3&&console.error("[WS] Full malformed message:",c.data)}},i.onclose=()=>{var d,f;_c(!1),wk(null),W.setConnected(!1),W.stopStatusPolling();const c=ub();c<kk?((d=Pe.onToast)==null||d.call(Pe,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${kk})`),Nk()):(f=Pe.onToast)==null||f.call(Pe,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{_c(!1)},W.setSendMessage(ex)}function Nk(){const n=ub(),e=Math.min(1e3*Math.pow(2,n-1),3e4);aj(setTimeout(mu,e))}function OR(n,e){const t={position:n,target:e};wa(dt.CAMERA_STATE,t)}function LR(){return ea(dt.CAMERA_STATE,null)}function qV(n,e,t){const s={posX:n,posZ:e,zoom:t};wa(dt.CAMERA_STATE_2D,s)}function GV(){return ea(dt.CAMERA_STATE_2D,null)}function Dl(){return{Authorization:`Bearer ${Ir()}`,"Content-Type":"application/json"}}async function PR(){const n=await fetch(`${ra()}/api/workspaces`,{headers:Dl()});if(!n.ok)throw new Error(`Failed to fetch workspaces: ${n.statusText}`);return n.json()}async function IR(n,e){const t=await fetch(`${ra()}/api/workspaces`,{method:"POST",headers:Dl(),body:JSON.stringify({name:n,areaIds:e})});if(!t.ok)throw new Error(`Failed to create workspace: ${t.statusText}`);return t.json()}async function Tk(n,e){const t=await fetch(`${ra()}/api/workspaces/${n}`,{method:"PUT",headers:Dl(),body:JSON.stringify(e)});if(!t.ok)throw new Error(`Failed to update workspace: ${t.statusText}`);return t.json()}async function BR(n){const e=await fetch(`${ra()}/api/workspaces/${n}`,{method:"DELETE",headers:Dl()});if(!e.ok)throw new Error(`Failed to delete workspace: ${e.statusText}`)}async function FR(){const n=await fetch(`${ra()}/api/workspaces/active`,{headers:Dl()});if(!n.ok)throw new Error(`Failed to get active workspace: ${n.statusText}`);return(await n.json()).activeWorkspaceId??null}async function _k(n){const e=await fetch(`${ra()}/api/workspaces/active`,{method:"PUT",headers:Dl(),body:JSON.stringify({workspaceId:n})});if(!e.ok)throw new Error(`Failed to set active workspace: ${e.statusText}`)}const gu=new Set;let Xa=null,Xi=[],fj=!1;const mb=new Set;function Ym(n){fj=n,mb.forEach(e=>e(n))}const pj="tide-commander-active-workspace";function Ek(){return typeof window>"u"?null:localStorage.getItem(pj)||null}function Km(n){typeof window>"u"||localStorage.setItem(pj,n||"")}function Mc(){gu.forEach(n=>n())}function zR(){return Xa}function hp(n){return Xa?n?Xa.areaIds.includes(n):!1:!0}function YV(n){return Xa?Xa.areaIds.includes(n):!0}function tx(){const[,n]=x.useState(0);return x.useEffect(()=>{const e=()=>n(t=>t+1);return gu.add(e),()=>{gu.delete(e)}},[]),[Xa,Xi]}function $R(n){return gu.add(n),()=>{gu.delete(n)}}function HR(){const[n,e]=x.useState(fj);return x.useEffect(()=>{const t=s=>e(s);return mb.add(t),()=>{mb.delete(t)}},[]),n}const Qm=new Map,hj=Ce.memo(function(){const{t:e}=ut("common"),t=Pa(),[s,a]=x.useState([]),[r,i]=x.useState(()=>Ek()),[c,d]=x.useState(!1),[f,h]=x.useState(!1),[m,b]=x.useState(!0),[y,v]=x.useState(null),[S,N]=x.useState(""),[k,C]=x.useState([]),[A,E]=x.useState(!1),D=x.useRef(null);x.useEffect(()=>{let I=!1;return(async()=>{try{const $=Ek(),[z,q]=await Promise.all([PR(),FR()]);if(I)return;const Y=$&&z.some(B=>B.id===$)?$:q&&z.some(B=>B.id===q)?q:null;a(z),Xi=z,i(Y),Km(Y),Xa=z.find(B=>B.id===Y)??null,Mc()}catch($){console.error("workspace error:",$)}finally{I||b(!1)}})(),()=>{I=!0}},[]),x.useEffect(()=>{if(!c&&!f)return;const I=$=>{D.current&&!D.current.contains($.target)&&(d(!1),h(!1))};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[c,f]);const _=x.useMemo(()=>s.find(I=>I.id===r)??null,[s,r]),F=x.useCallback(async I=>{Ym(!0);const $=Date.now();if(r){const B=LR();B&&(Qm.set(r,B),Tk(r,{cameraState:B}).then(G=>{a(te=>{const V=te.map(ge=>ge.id===r?G:ge);return Xi=V,V})}).catch(G=>console.error("workspace error:",G)))}i(I),Km(I),d(!1);const z=I?s.find(B=>B.id===I)??null:null;if(Xa=z,Xi=s,Mc(),I){const G=(z==null?void 0:z.cameraState)??Qm.get(I);G&&(OR(G.position,G.target),Qm.set(I,G))}_k(I).catch(B=>console.error("workspace error:",B));const q=Date.now()-$,Y=400;q<Y?setTimeout(()=>Ym(!1),Y-q):Ym(!1)},[r,s]),P=x.useMemo(()=>Array.from(t.values()).filter(I=>!I.archived),[t]),T=x.useCallback(async()=>{if(S.trim())try{const I=await IR(S.trim(),k),$=[...s,I];a($),Xi=$,Mc(),N(""),C([]),E(!1)}catch(I){console.error("workspace error:",I)}},[S,k,s]),M=x.useCallback(async()=>{if(!(!y||!S.trim()))try{const I=await Tk(y,{name:S.trim(),areaIds:k}),$=s.map(z=>z.id===y?I:z);a($),Xi=$,y===r&&(Xa=I),Mc(),v(null),N(""),C([])}catch(I){console.error("workspace error:",I)}},[y,S,k,s,r]),R=x.useCallback(async I=>{try{await BR(I);const $=s.filter(z=>z.id!==I);a($),Xi=$,r===I&&(i(null),Km(null),Xa=null,await _k(null).catch(z=>console.error("workspace error:",z))),Mc()}catch($){console.error("workspace error:",$)}},[s,r]),O=x.useCallback(I=>{v(I.id),N(I.name),C([...I.areaIds]),E(!1)},[]),U=x.useCallback(()=>{v(null),N(""),C([]),E(!0)},[]),H=x.useCallback(I=>{C($=>$.includes(I)?$.filter(z=>z!==I):[...$,I])},[]);return m?null:o.jsxs("div",{className:"workspace-switcher",ref:D,children:[o.jsxs("button",{className:"workspace-switcher-trigger",onClick:()=>{d(!c),h(!1)},title:"Workspaces",children:[o.jsx("span",{className:"workspace-switcher-icon",children:"📂"}),o.jsx("span",{className:"workspace-switcher-label",children:_?_.name:e("agentBar.allWorkspaces",{defaultValue:"All"})}),o.jsx("span",{className:"workspace-switcher-arrow",children:c?"▲":"▼"})]}),c&&!f&&o.jsxs("div",{className:"workspace-switcher-dropdown",children:[o.jsx("button",{className:`workspace-switcher-option ${r?"":"active"}`,onClick:()=>F(null),children:e("agentBar.allWorkspaces",{defaultValue:"All"})}),s.map(I=>o.jsxs("button",{className:`workspace-switcher-option ${I.id===r?"active":""}`,onClick:()=>F(I.id),children:[I.name,o.jsx("span",{className:"workspace-switcher-option-count",children:I.areaIds.length})]},I.id)),o.jsx("div",{className:"workspace-switcher-divider"}),o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-manage",onClick:()=>h(!0),children:["⚙ ",e("agentBar.manageWorkspaces",{defaultValue:"Manage"})]})]}),f&&o.jsxs("div",{className:"workspace-switcher-dropdown workspace-switcher-manager",children:[o.jsxs("div",{className:"workspace-switcher-manager-header",children:[o.jsx("span",{children:e("agentBar.workspaces",{defaultValue:"Workspaces"})}),o.jsx("button",{className:"workspace-switcher-close",onClick:()=>h(!1),children:"×"})]}),o.jsx("div",{className:"workspace-switcher-manager-list",children:s.map(I=>o.jsx("div",{className:"workspace-switcher-manager-item",children:y===I.id?o.jsxs("div",{className:"workspace-switcher-editor",children:[o.jsx("input",{type:"text",value:S,onChange:$=>N($.target.value),className:"workspace-switcher-input",placeholder:"Workspace name",autoFocus:!0,onKeyDown:$=>{$.key==="Enter"&&M(),$.key==="Escape"&&v(null)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[P.map($=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes($.id),onChange:()=>H($.id)}),o.jsx("span",{style:{color:$.color},children:$.name})]},$.id)),P.length===0&&o.jsx("span",{className:"workspace-switcher-empty",children:"No areas"})]}),o.jsxs("div",{className:"workspace-switcher-editor-actions",children:[o.jsx("button",{className:"workspace-switcher-btn-save",onClick:M,children:"Save"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>v(null),children:"Cancel"})]})]}):o.jsxs("div",{className:"workspace-switcher-manager-row",children:[o.jsx("span",{className:"workspace-switcher-manager-name",children:I.name}),o.jsxs("span",{className:"workspace-switcher-manager-count",children:[I.areaIds.length," areas"]}),o.jsx("button",{className:"workspace-switcher-btn-edit",onClick:()=>O(I),title:"Edit",children:"✏"}),o.jsx("button",{className:"workspace-switcher-btn-delete",onClick:()=>R(I.id),title:"Delete",children:"🗑"})]})},I.id))}),A?o.jsxs("div",{className:"workspace-switcher-editor workspace-switcher-create-form",children:[o.jsx("input",{type:"text",value:S,onChange:I=>N(I.target.value),className:"workspace-switcher-input",placeholder:"New workspace name",autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&T(),I.key==="Escape"&&E(!1)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[P.map(I=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(I.id),onChange:()=>H(I.id)}),o.jsx("span",{style:{color:I.color},children:I.name})]},I.id)),P.length===0&&o.jsx("span",{className:"workspace-switcher-empty",children:"No areas"})]}),o.jsxs("div",{className:"workspace-switcher-editor-actions",children:[o.jsx("button",{className:"workspace-switcher-btn-save",onClick:T,children:"Create"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>E(!1),children:"Cancel"})]})]}):o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-add",onClick:U,children:["+ ",e("agentBar.newWorkspace",{defaultValue:"New Workspace"})]})]})]})}),Ff="tide_webgl_active";typeof window<"u"&&(window.__tidePersistedScene===void 0&&(window.__tidePersistedScene=null),window.__tidePersistedCanvas===void 0&&(window.__tidePersistedCanvas=null),window.__tideWsConnected===void 0&&(window.__tideWsConnected=!1),window.__tideIsPageUnloading===void 0&&(window.__tideIsPageUnloading=!1));function mp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function mj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function UR(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function bu(n){typeof window<"u"&&(window.__tidePersistedScene=n)}function tu(n){typeof window<"u"&&(window.__tidePersistedCanvas=n)}function gj(n){typeof window<"u"&&(window.__tideWsConnected=n)}function WR(n){typeof window<"u"&&(window.__tideIsPageUnloading=n)}function VR(){sessionStorage.setItem(Ff,"true")}function Yd(n){WR(!0),sessionStorage.removeItem(Ff),dj(),kR(),window.__tideScene&&(window.__tideScene=null);const e=mp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),bu(null)):console.log("[App] No persistedScene to dispose"),tu(null),gj(!1);const t=document.getElementById("battlefield");t&&t.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function qR(){var a,r;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Ff)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(r=(a=window.__tideScene).dispose)==null||r.call(a)}catch{}window.__tideScene=null}const e=mp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}bu(null)}const t=document.getElementById("battlefield"),s=mj();t&&t!==s&&t.remove(),sessionStorage.removeItem(Ff)}function GR(){typeof window>"u"||(qR(),window.addEventListener("pageshow",n=>{n.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Yd(),window.location.reload())}),window.onunload=()=>Yd(),window.onbeforeunload=n=>{Yd()},window.addEventListener("pagehide",n=>{Yd(`pagehide (persisted=${n.persisted})`)}))}GR();const Mk={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},Dk={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Rk={idleAnimation:"sit",workingAnimation:"sprint"},YR=0;function bj(){const n={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:Mk,modelStyle:Dk,animations:Rk,fpsLimit:YR},e=ea(dt.CONFIG,null);if(e){const t=e.indicatorScale;return{characterScale:e.characterScale??n.characterScale,scale2d:e.scale2d??t??n.scale2d,scale3d:e.scale3d??t??n.scale3d,show2DTaskLabels:e.show2DTaskLabels??n.show2DTaskLabels,gridVisible:e.gridVisible??n.gridVisible,timeMode:e.timeMode??n.timeMode,terrain:{...Mk,...e.terrain},modelStyle:{...Dk,...e.modelStyle},animations:{...Rk,...e.animations},fpsLimit:e.fpsLimit??n.fpsLimit}}return n}function KR(n){wa(dt.CONFIG,n)}function QR(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function xj(){console.log("[Tide HMR] Manual scene refresh triggered");const n=mp();if(n){try{n.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}bu(null)}tu(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const t=e.getContext("webgl2")||e.getContext("webgl");if(t){const s=t.getExtension("WEBGL_lose_context");s&&s.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=xj);function XR({canvasRef:n,selectionBoxRef:e,viewMode:t,sceneMountKey:s=0,showToast:a,showAgentNotification:r,toolboxModal:i,contextMenu:c,setHoveredAgentPopup:d,setBuildingPopup:f,getBuildingPopup:h,openBuildingModal:m,openPM2LogsModal:b,openBossLogsModal:y,openDatabasePanel:v,onSceneLoadingChange:S}){const N=x.useRef(null),k=x.useRef(null),C=x.useRef(null),A=x.useRef(null),E=x.useRef(null);return x.useEffect(()=>{if(t!=="3d"){S==null||S(!1);return}if(!n.current||!e.current)return;let D=!1;S==null||S(!0);const _=mp(),P=mj()===n.current;function T(){var R,O,U,H,I,$,z,q;(R=N.current)==null||R.setOnToast(a),(O=N.current)==null||O.setOnBuildingClick((Y,B)=>{W.selectBuilding(Y);const G=W.getState().buildings.get(Y);(G==null?void 0:G.type)==="folder"&&G.folderPath?W.openFileExplorer(G.folderPath):(G==null?void 0:G.type)==="server"||(G==null?void 0:G.type)==="boss"||(G==null?void 0:G.type)==="database"?(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{f({buildingId:Y,screenPos:B,fromClick:!0}),k.current=null},150)):m(Y)}),(U=N.current)==null||U.setOnContextMenu((Y,B,G)=>{c.open(Y,B,G)}),(H=N.current)==null||H.setOnAgentHover(()=>{}),(I=N.current)==null||I.setOnBuildingHover((Y,B)=>{const G=h();if(Y&&B){const te=W.getState().buildings.get(Y);((te==null?void 0:te.type)==="server"||(te==null?void 0:te.type)==="boss"||(te==null?void 0:te.type)==="database")&&!(G!=null&&G.fromClick)&&f({buildingId:Y,screenPos:B,fromClick:!1})}else G!=null&&G.fromClick||f(null)}),($=N.current)==null||$.setOnGroundClick(()=>{f(null)}),(z=N.current)==null||z.setOnAreaDoubleClick(Y=>{W.selectArea(Y),i.open()}),(q=N.current)==null||q.setOnBuildingDoubleClick(Y=>{var G;k.current&&(clearTimeout(k.current),k.current=null),f(null);const B=W.getState().buildings.get(Y);(B==null?void 0:B.type)==="server"&&((G=B.pm2)!=null&&G.enabled)?b==null||b(Y):(B==null?void 0:B.type)==="boss"?y==null||y(Y):(B==null?void 0:B.type)==="database"?v==null||v(Y):(B==null?void 0:B.type)==="folder"&&B.folderPath?W.openFileExplorer(B.folderPath):m(Y)})}if(_)try{N.current=_,P?(console.log("[Tide] Reusing existing scene (StrictMode remount)"),_.ensureRenderLoopRunning()):(console.log("[Tide] Reattaching persisted scene to new canvas"),_.reattach(n.current,e.current),tu(n.current));const R=W.getState();_.syncAreas(),_.syncBuildings(),R.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",R.agents.size),_.syncAgents(Array.from(R.agents.values()))),T()}catch(R){console.error("[Tide] Failed to reattach persisted 3D scene:",R),S==null||S(!1)}finally{A.current=requestAnimationFrame(()=>{E.current=requestAnimationFrame(()=>{S==null||S(!1),E.current=null}),A.current=null})}else{const R=n.current,O=e.current,U=async()=>{if(D){console.log("[Tide] Effect cleaned up before scene init, skipping"),S==null||S(!1);return}if(!R.isConnected||!O.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),S==null||S(!1);return}(!R.clientWidth||!R.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),R.style.width="100%",R.style.height="100%",R.offsetHeight),(!R.clientWidth||!R.clientHeight)&&(R.width=window.innerWidth,R.height=window.innerHeight),VR();try{const{SceneManager:H}=await gt(async()=>{const{SceneManager:z}=await import("./SceneManager-BXqFLaeT.js");return{SceneManager:z}},__vite__mapDeps([6,4,3,1]));if(D){S==null||S(!1);return}const I=new H(R,O);N.current=I,bu(I),tu(R);const $=bj();I.setCharacterScale($.characterScale),I.setScale3D($.scale3d),I.setTimeMode($.timeMode),I.setTerrainConfig($.terrain),I.setFloorStyle($.terrain.floorStyle,!0),I.setGridVisible($.gridVisible),I.setAgentModelStyle($.modelStyle),I.setIdleAnimation($.animations.idleAnimation),I.setWorkingAnimation($.animations.workingAnimation),I.setFpsLimit($.fpsLimit),I.syncAreas(),I.syncBuildings(),I.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const z=W.getState();z.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",z.customAgentClasses.size),I.setCustomAgentClasses(z.customAgentClasses)),z.agents.size>0&&(console.log("[Tide] Syncing agents from store:",z.agents.size),I.syncAgents(Array.from(z.agents.values()))),I.upgradeAgentModels()}).catch(z=>{console.warn("[Tide] Some models failed to load, using fallback:",z)}).finally(()=>{S==null||S(!1)}),T()}catch(H){console.error("[Tide] Failed to initialize 3D scene:",H),S==null||S(!1)}};C.current=requestAnimationFrame(()=>void U())}ij({onAgentCreated:R=>{var O,U,H;(O=N.current)==null||O.addAgent(R),(U=N.current)==null||U.refreshSelectionVisuals(),(H=window.__spawnModalSuccess)==null||H.call(window)},onAgentUpdated:(R,O)=>{var H;const U=W.getState().agents.get(R.id)||R;(H=N.current)==null||H.updateAgent(U,O)},onAgentDeleted:R=>{var O;(O=N.current)==null||O.removeAgent(R)},onAgentsSync:R=>{var U;const O=Array.from(W.getState().agents.values());(U=N.current)==null||U.syncAgents(O)},onAreasSync:()=>{var O,U;(O=N.current)==null||O.syncAreas();const R=Array.from(W.getState().agents.values());(U=N.current)==null||U.syncAgents(R)},onSpawnError:()=>{var R;(R=window.__spawnModalError)==null||R.call(window)},onSpawnSuccess:()=>{var R;(R=window.__spawnModalSuccess)==null||R.call(window)},onDirectoryNotFound:R=>{var O;(O=window.__spawnModalDirNotFound)==null||O.call(window,R)},onToolUse:(R,O,U)=>{var H;(H=N.current)==null||H.showToolBubble(R,O,U)},onDelegation:(R,O)=>{var U;(U=N.current)==null||U.showDelegationEffect(R,O)},onCustomClassesSync:R=>{var O,U;(O=N.current)==null||O.setCustomAgentClasses(R),(U=N.current)==null||U.upgradeAgentModels()},onBuildingUpdated:R=>{var O;(O=N.current)==null||O.updateBuilding(R)},onSubagentStarted:R=>{var O;(O=N.current)==null||O.addSubagentEffect(R.id,R.parentAgentId,R.name,R.subagentType)},onSubagentCompleted:R=>{var H;const O=W.getSubagent(R)||W.getSubagentByToolUseId(R),U=(O==null?void 0:O.id)||R;(H=N.current)==null||H.completeSubagentEffect(U),setTimeout(()=>{var I;(I=N.current)==null||I.removeSubagentEffect(U)},3e4)}});const M=$R(()=>{if(N.current){N.current.syncAreas(),N.current.syncBuildings();const R=Array.from(W.getState().agents.values());N.current.syncAgents(R)}});return()=>{M(),D=!0,C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),W.getState().viewMode!=="3d"&&QR()&&N.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),SR(),N.current.dispose(),N.current=null,bu(null),tu(null))}},[t,s]),N}function JR({showToast:n,showAgentNotification:e}){x.useEffect(()=>{ij({onToast:n,onReconnect:()=>{W.triggerReconnect()},onAgentNotification:a=>{e(a)}}),UR()||(mu(),gj(!0)),hR();let t;gR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&nj(a.agentId)}).then(a=>{t=a});const s=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>mu(),100)};return window.addEventListener("tideAppResume",s),()=>{window.removeEventListener("tideAppResume",s),t==null||t()}},[n,e])}function ZR(n){x.useEffect(()=>{let e="",t="",s=new Map;const a=r=>{var d;let i=!1;const c=new Map;for(const[f,h]of r){const b=`${h.position.x.toFixed(2)},${h.position.z.toFixed(2)},${h.status},${h.class},${h.isBoss},${((d=h.subordinateIds)==null?void 0:d.length)??0}`.split("").reduce((y,v)=>(y<<5)-y+v.charCodeAt(0),0);c.set(f,b),s.get(f)!==b&&(i=!0)}return c.size!==s.size&&(i=!0),{newVersion:c,changed:i}};return W.subscribe(()=>{var b;const r=W.getState(),i=Array.from(r.selectedAgentIds).sort().join(","),c=Array.from(r.selectedBuildingIds).sort().join(","),d=i!==e,f=c!==t,{newVersion:h,changed:m}=a(r.agents);(d||f||m)&&(e=i,t=c,s=h,(b=n.current)==null||b.refreshSelectionVisuals())})},[n])}function eO(n){x.useEffect(()=>{var s;(s=n.current)==null||s.syncAreas();let e=0,t=0;return W.subscribe(()=>{var c,d;const r=W.getState().areas;if(r.size!==e){e=r.size,t=Date.now(),(c=n.current)==null||c.syncAreas();return}let i=0;for(const[f,h]of r){let m=f.charCodeAt(0);m+=(h.width??0)+(h.height??0)+(h.radius??0),m+=Math.floor(h.center.x*100)+Math.floor(h.center.z*100),m+=(h.zIndex??0)*1e3;for(let b=0;b<h.name.length;b++)m+=h.name.charCodeAt(b);for(let b=0;b<h.color.length;b++)m+=h.color.charCodeAt(b);if(h.directoryGitCounts)for(const b of h.directoryGitCounts)m+=(b+1)*7;if(h.logo){m+=Math.floor((h.logo.opacity??.8)*1e3),m+=Math.floor(h.logo.width*100)+Math.floor(h.logo.height*100);for(let b=0;b<h.logo.position.length;b++)m+=h.logo.position.charCodeAt(b);if(h.logo.filename)for(let b=0;b<h.logo.filename.length;b++)m+=h.logo.filename.charCodeAt(b)}i^=m|0}i!==t&&(t=i,(d=n.current)==null||d.syncAreas())})},[n])}function tO(n){x.useEffect(()=>{var s;(s=n.current)==null||s.syncBuildings();let e=0,t=0;return W.subscribe(()=>{var c,d;const r=W.getState().buildings;if(r.size!==e){e=r.size,t=Date.now(),(c=n.current)==null||c.syncBuildings();return}let i=0;for(const[f,h]of r){i^=h.position.x*1e3+h.position.z|0,i^=(h.scale||1)*1e4|0;const m=`${h.style||""}${h.name}${h.status}${h.gitChangesCount||0}`;for(let b=0;b<m.length;b++)i=(i<<5)-i+m.charCodeAt(b)|0}i!==t&&(t=i,(d=n.current)==null||d.syncBuildings())})},[n])}function nO(n,e){x.useEffect(()=>{var t;(t=n.current)==null||t.highlightArea(e)},[n,e])}function sO(n,e){x.useEffect(()=>{var t;(t=n.current)==null||t.setPowerSaving(e)},[n,e])}function Dt(n,e,t,s,a={},r="global"){return{id:n,name:e,description:t,key:s,modifiers:a,enabled:!0,context:r}}const Xm=[Dt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Dt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Dt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Dt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Dt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Dt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Dt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Dt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Dt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Dt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Dt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Dt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Dt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Dt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Dt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Dt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Dt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Dt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Dt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Dt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Dt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Dt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Dt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Dt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Dt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Dt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Dt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Dt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Dt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Dt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Dt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Dt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Dt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Dt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Dt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Dt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Dt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Dt("clear-context","Clear Context","Clear context of the selected agent","c",{alt:!0,shift:!0}),Dt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Dt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Dt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Dt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Dt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Dt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Dt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Dt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Dt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Dt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function xn(n,e){if(!e||!e.enabled)return!1;const{ctrl:t,alt:s,shift:a}=e.modifiers,r=t?n.ctrlKey||n.metaKey:!n.ctrlKey&&!n.metaKey,i=s?n.altKey:!n.altKey,c=a?n.shiftKey:!n.shiftKey;let d;if(t?d=(n.ctrlKey||n.metaKey)&&i&&c:d=r&&i&&c,!d)return!1;const f=e.key;if(f.length===1&&/^[a-zA-Z]$/.test(f)){const m=`Key${f.toUpperCase()}`;return n.code===m}if(f.length===1&&/^[0-9]$/.test(f)){const m=`Digit${f}`;return n.code===m}return f==="Space"||f===" "?n.code==="Space":n.key===f}function aO(n){return n===" "||n==="Space"?"space":(n.length===1,n.toLowerCase())}function rO(n){const e=n.trim().toLowerCase();if(e==="space")return"Space";if(e==="esc")return"Escape";if(e==="return")return"Enter";const t={escape:"Escape",enter:"Enter",tab:"Tab",backspace:"Backspace",delete:"Delete",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown"};return t[e]?t[e]:e}function iO(n){if(!(n!=null&&n.key))return"";const e=[];return n.modifiers.ctrl&&e.push("ctrl"),n.modifiers.alt&&e.push("alt"),n.modifiers.shift&&e.push("shift"),n.modifiers.meta&&e.push("meta"),e.push(aO(n.key)),e.join("+")}function nx(n){if(!n)return null;const e=n.split("+").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return null;const t=e[e.length-1],s={};for(const r of e.slice(0,-1))r==="ctrl"||r==="control"?s.ctrl=!0:r==="alt"||r==="option"?s.alt=!0:r==="shift"?s.shift=!0:(r==="meta"||r==="cmd"||r==="command")&&(s.meta=!0);const a=rO(t);return a?{key:a,modifiers:s}:null}function oO(n){const e=nx(n);return e?gb({key:e.key,modifiers:e.modifiers}):""}function lO(n,e){const t=nx(e);return t?xn(n,{key:t.key,modifiers:t.modifiers,enabled:!0}):!1}function gb(n){const e=[];if(n.modifiers.ctrl){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌘":"Ctrl")}if(n.modifiers.alt){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌥":"Alt")}n.modifiers.shift&&e.push("Shift"),n.modifiers.meta&&e.push("⌘");let t=n.key;return t===" "?t="Space":t.length===1&&(t=t.toUpperCase()),e.push(t),e.join("+")}function cO(n,e,t,s){return n.filter(a=>{if(a.id===t||!a.enabled||s&&a.context!=="global"&&a.context!==s)return!1;const r=h=>h===" "||h==="Space"?"Space":h.length===1?h.toLowerCase():h,i=r(a.key),c=r(e.key);if(i!==c)return!1;const d=a.modifiers,f=e.modifiers;return(d.ctrl||!1)===(f.ctrl||!1)&&(d.alt||!1)===(f.alt||!1)&&(d.shift||!1)===(f.shift||!1)&&(d.meta||!1)===(f.meta||!1)})}function uO({sceneRef:n,spawnModal:e,commanderModal:t,explorerModal:s,spotlightModal:a,deleteConfirmModal:r,onRequestBuildingDelete:i,onOpenDatabasePanel:c,onCloseDatabasePanel:d,databasePanelOpen:f}){x.useEffect(()=>{const h=m=>{var O,U,H,I,$;const b=W.getShortcuts(),y=m.target,v=y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true"||!!y.closest(".cm-editor"),S=W.getState(),N=b.find(z=>z.id==="deselect-all");if(xn(m,N)){if(y.closest(".guake-bottom-terminal-embed"))return;if(yf()){m.preventDefault();return}if(S.activeTool==="rectangle"||S.activeTool==="circle"){(O=n.current)==null||O.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():S.terminalOpen?(W.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(W.deselectAll(),(U=n.current)==null||U.refreshSelectionVisuals())}for(let z=1;z<=9;z++){const q=b.find(Y=>Y.id===`select-agent-${z}`);if(xn(m,q)){m.preventDefault();const Y=W.getState(),B=z-1,G=Array.from(Y.agents.keys());B<G.length&&(W.selectAgent(G[B]),(H=n.current)==null||H.refreshSelectionVisuals());return}}const k=b.find(z=>z.id==="spawn-agent");if(xn(m,k)){m.preventDefault(),e.open();return}const C=b.find(z=>z.id==="toggle-commander-tab");if(xn(m,C)&&!v){m.preventDefault(),t.toggle();return}const A=b.find(z=>z.id==="toggle-commander");if(xn(m,A)){m.preventDefault(),t.toggle();return}const E=b.find(z=>z.id==="toggle-file-explorer");if(xn(m,E)){m.preventDefault();const z=W.getState();if(s.isOpen||z.explorerFolderPath!==null||z.explorerAreaId!==null)s.close(),W.closeFileExplorer();else{const Y=W.getLastExplorerState();if((Y==null?void 0:Y.type)==="folder")W.openFileExplorer(Y.path);else if((Y==null?void 0:Y.type)==="area")if(z.areas.has(Y.areaId))s.open(Y.areaId);else{const B=Array.from(z.areas.values()).filter(G=>G.directories&&G.directories.length>0);B.length>0&&s.open(B[0].id)}else{const B=Array.from(z.areas.values()).filter(G=>G.directories&&G.directories.length>0);B.length>0&&s.open(B[0].id)}}return}if(m.altKey&&!m.ctrlKey&&!m.shiftKey&&!m.metaKey&&m.code==="KeyD"){if(m.preventDefault(),m.stopPropagation(),f){d();return}const z=localStorage.getItem("tide-commander-last-database-building"),q=W.getState();if(z){const Y=q.buildings.get(z);if((Y==null?void 0:Y.type)==="database"){c(z);return}}for(const[Y,B]of q.buildings)if(B.type==="database"){c(Y);return}return}const D=b.find(z=>z.id==="toggle-spotlight");if(xn(m,D)||m.altKey&&!m.ctrlKey&&!m.metaKey&&m.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:D,altKey:m.altKey,code:m.code}),m.preventDefault(),a.toggle();return}const _=b.find(z=>z.id==="toggle-2d-view");if(xn(m,_)){m.preventDefault();const z=W.getState().viewMode,q=z==="3d"?"2d":z==="2d"?"dashboard":"3d";W.setViewMode(q);return}const F=b.find(z=>z.id==="clear-context");if(xn(m,F)){m.preventDefault();const z=W.getState(),q=z.selectedAgentIds.size===1?Array.from(z.selectedAgentIds)[0]:null;q&&W.clearContext(q);return}const P=b.find(z=>z.id==="next-working-agent"),T=b.find(z=>z.id==="prev-working-agent");if((xn(m,P)||xn(m,T))&&!v){const z=W.getState();if(z.terminalOpen)return;const q=Array.from(z.agents.values());let Y=q.filter(V=>z.agentsWithUnseenOutput.has(V.id));if(Y.length===0&&(Y=q.filter(V=>V.status==="working")),Y.length===0)return;m.preventDefault();const B=z.selectedAgentIds.size===1?Array.from(z.selectedAgentIds)[0]:null,G=B?Y.findIndex(V=>V.id===B):-1;let te;xn(m,P)?te=G===-1?0:(G+1)%Y.length:te=G===-1?Y.length-1:(G-1+Y.length)%Y.length,W.selectAgent(Y[te].id),(I=n.current)==null||I.refreshSelectionVisuals();return}const M=b.find(z=>z.id==="delete-selected"),R=b.find(z=>z.id==="delete-selected-backspace");if((xn(m,M)||xn(m,R))&&!v){const z=W.getState();if(z.selectedAgentIds.size>0){m.preventDefault(),r.open();return}if(z.selectedBuildingIds.size>0){m.preventDefault(),i();return}return}if(!v){const z=Array.from(S.agents.values()).find(q=>{var B;const Y=(B=q.shortcut)==null?void 0:B.trim();return Y?lO(m,Y):!1});if(z){m.preventDefault(),m.stopPropagation(),W.selectAgent(z.id),W.setTerminalOpen(!0),($=n.current)==null||$.refreshSelectionVisuals();return}}};return document.addEventListener("keydown",h,!0),()=>document.removeEventListener("keydown",h,!0)},[n,e,t,s,a,r,i,c,d,f])}function dO(){const[n,e]=x.useState(!1);return window.__tideSetBackNavModal=e,x.useEffect(()=>{if(window.__tideBackNavSetup){window.location.hash.includes("app")||(window.location.hash="#app");return}window.__tideBackNavSetup=!0,window.location.hash.includes("app")||(window.location.hash="#app");const s=()=>window.innerWidth<=768;let a=0;const r=()=>{var c;Date.now()-a<200||window.location.hash.includes("app")||(window.location.hash="#app",s()&&(yf()||(c=window.__tideSetBackNavModal)==null||c.call(window,!0)))},i=()=>{var c;window.location.hash.includes("app")||(window.location.hash="#app"),window.location.hash==="#app"&&setTimeout(()=>{window.location.hash==="#app"&&!window.location.hash.includes("app2")&&(window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"))},50),s()?yf()?a=Date.now():(c=window.__tideSetBackNavModal)==null||c.call(window,!0):(yf(),a=Date.now())};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",r),window.addEventListener("popstate",i)},[]),{showBackNavModal:n,setShowBackNavModal:e,handleLeave:()=>{e(!1);const s=window.__tideHistoryDepth??2;window.history.go(-(s+1))}}}const Jm="agent-order-change";function fO(n){const e=x.useMemo(()=>new Set(n.map(d=>d.id)),[n]),[t,s]=x.useState(()=>ea(dt.AGENT_ORDER,[]));x.useEffect(()=>{const d=f=>{s(f.detail)};return window.addEventListener(Jm,d),()=>{window.removeEventListener(Jm,d)}},[]);const a=x.useMemo(()=>{const d=t.filter(b=>e.has(b)),f=n.filter(b=>!d.includes(b.id)).map(b=>b.id),h=[...d,...f],m=new Map(n.map(b=>[b.id,b]));return h.map(b=>m.get(b)).filter(b=>b!==void 0)},[n,t,e]),r=x.useCallback(d=>{s(d),wa(dt.AGENT_ORDER,d),window.dispatchEvent(new CustomEvent(Jm,{detail:d}))},[]),i=x.useCallback((d,f)=>{const h=a.map(b=>b.id),[m]=h.splice(d,1);h.splice(f,0,m),r(h)},[a,r]),c=x.useCallback(()=>{s([]),wa(dt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const d=t.filter(f=>e.has(f));d.length!==t.length&&r(d)},[e,t,r]),{orderedAgents:a,moveAgent:i,resetOrder:c}}function Sa(n){const e=x.useRef(null),t=x.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),s=x.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),n()),e.current=null},[n]);return{handleMouseDown:t,handleClick:s}}const pO=3e4;function hO(){const n=x.useRef(null);x.useEffect(()=>{const e=async()=>{var i,c;const t=W.getState(),s=new Map,a=new Map;for(const[d,f]of t.buildings){const h=f.folderPath||f.cwd;h&&(a.has(h)||a.set(h,[]),a.get(h).push(d))}for(const[d,f]of a)try{const h=await Lt(Et(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!h.ok)continue;const b=((i=(await h.json()).files)==null?void 0:i.length)||0;s.set(d,b);for(const y of f){const v=W.getState().buildings.get(y);v&&v.gitChangesCount!==b&&W.updateBuildingLocal(y,{gitChangesCount:b})}}catch{}const r=new Map;for(const[d,f]of t.areas)f.archived||!f.directories||f.directories.forEach((h,m)=>{h&&(r.has(h)||r.set(h,[]),r.get(h).push({areaId:d,dirIndex:m}))});if(r.size!==0)for(const[d,f]of r)try{let h;if(s.has(d))h=s.get(d);else{const b=await Lt(Et(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!b.ok)continue;h=((c=(await b.json()).files)==null?void 0:c.length)||0,s.set(d,h)}const m=new Map;for(const b of f)m.has(b.areaId)||m.set(b.areaId,[]),m.get(b.areaId).push({dirIndex:b.dirIndex,count:h});for(const[b,y]of m){const v=W.getState().areas.get(b);if(!v)continue;const S=v.directoryGitCounts?[...v.directoryGitCounts]:new Array(v.directories.length).fill(0);let N=!1;for(const{dirIndex:k,count:C}of y)S[k]!==C&&(S[k]=C,N=!0);N&&W.updateAreaLocal(b,{directoryGitCounts:S})}}catch{}};return e(),n.current=setInterval(e,pO),()=>{n.current&&(clearInterval(n.current),n.current=null)}},[])}function yj(n=3e3){const[e,t]=x.useState(null),s=x.useRef(null);x.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]);const a=x.useCallback(d=>{s.current&&clearTimeout(s.current),t(d),s.current=setTimeout(()=>{t(f=>f===d?null:f),s.current=null},n)},[n]),r=x.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null),t(null)},[]),i=x.useCallback(d=>e===d,[e]),c=x.useCallback((d,f)=>{e===d?(s.current&&(clearTimeout(s.current),s.current=null),t(null),f()):a(d)},[e,a]);return{isPending:i,arm:a,cancel:r,handleClick:c}}const Zm={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:"",vibrationIntensity:1,tabTitle:"",tmuxMode:!1},Ok=90,eg=["simple","chat","advanced"],Lk=55,Pk=20,Ik=95,mO=200,gO=12e4,bO=5,Zs=new Map;function xO(n){const e=Zs.get(n);e&&(Zs.delete(n),Zs.set(n,e))}function yO(){for(;Zs.size>bO;){const n=Zs.keys().next().value;if(n!==void 0)Zs.delete(n);else break}}function vO(n){Zs.delete(n)}function wO(n){return n.trim().replace(/\r\n/g,`
43
43
  `)}function bb(n,e){return`${n}:${wO(e)}`}function Bk(n,e,t,s){if(n.uuid&&e.has(n.uuid))return!1;const a=n.isUserPrompt?"user":"assistant",r=bb(a,n.text),i=n.timestamp||0,c=t.get(r);return c!==void 0&&Math.abs(i-c)<=gO?!1:i>s}function kO({selectedAgentId:n,hasSessionId:e,reconnectCount:t,historyRefreshTrigger:s,lastPrompts:a,outputScrollRef:r}){const[i,c]=x.useState([]),[d,f]=x.useState(!1),[h,m]=x.useState(!1),[b,y]=x.useState(0),[v,S]=x.useState(!1),[N,k]=x.useState(!1),[C,A]=x.useState(0),E=x.useRef(!0),D=x.useRef(0),_=x.useRef(0),F=x.useRef(!1),P=x.useRef(!1),T=x.useRef(null),M=x.useRef(!1),R=x.useRef(null),O=x.useRef(null);x.useEffect(()=>(E.current=!0,()=>{E.current=!1}),[]),x.useEffect(()=>{if(!n||!e){c([]),_.current=0,k(!1),P.current=!1,A(0),f(!1),m(!1),y(he=>he+1),M.current=!1,R.current=null;return}const q=`${n}:${t}:${s}`;if(R.current===q)return;const Y=T.current!==null&&T.current!==n,B=t>0,G=Y||B,te=!Y&&!M.current&&e;T.current=n,M.current=e,R.current=q;let V;if(B){const he=W.getOutputs(n);he.length>0&&(V=he.map(J=>({...J})))}O.current&&(clearTimeout(O.current),O.current=null),B&&Zs.delete(n),D.current+=1;const ge=D.current;if(m(!0),!B){const he=Zs.get(n);he?(xO(n),c(he.messages),_.current=he.messages.length,k(he.hasMore),P.current=he.hasMore,A(he.totalCount)):(c([]),_.current=0,k(!1),P.current=!1,A(0))}!te&&!B&&(O.current=setTimeout(()=>{f(!0)},150)),Lt(Et(`/api/agents/${n}/history?limit=${Ok}&offset=0`)).then(he=>{if(!he.ok)throw new Error(`HTTP ${he.status}: ${he.statusText}`);return he.json()}).then(he=>{if(ge!==D.current)return;const J=Array.isArray(he.messages)?he.messages:[],de=Array.isArray(he.subagents)?he.subagents:[];c(J),_.current=J.length;const je=he.hasMore||!1;if(k(je),P.current=je,A(he.totalCount||0),de.length>0&&W.hydrateSubagentsFromHistory(n,de),Zs.set(n,{messages:J,hasMore:je,totalCount:he.totalCount||0}),yO(),V&&V.length>0){const xe=J.length>0?Math.max(...J.map(Me=>Me.timestamp?new Date(Me.timestamp).getTime():0)):0,qe=new Set(J.map(Me=>Me.uuid).filter(Me=>typeof Me=="string"&&Me.length>0)),Ke=new Map;for(const Me of J){if(Me.type!=="user"&&Me.type!=="assistant")continue;const ye=bb(Me.type,Me.content),Fe=Me.timestamp?new Date(Me.timestamp).getTime():0,Q=Ke.get(ye)??0;Fe>Q&&Ke.set(ye,Fe)}const We=V.filter(Me=>Bk(Me,qe,Ke,xe));W.clearOutputs(n);for(const Me of We)W.addOutput(n,Me)}else if(J.length>0){const xe=Math.max(...J.map(ye=>ye.timestamp?new Date(ye.timestamp).getTime():0)),qe=new Set(J.map(ye=>ye.uuid).filter(ye=>typeof ye=="string"&&ye.length>0)),Ke=new Map;for(const ye of J){if(ye.type!=="user"&&ye.type!=="assistant")continue;const Fe=bb(ye.type,ye.content),Q=ye.timestamp?new Date(ye.timestamp).getTime():0,Re=Ke.get(Fe)??0;Q>Re&&Ke.set(Fe,Q)}const We=W.getOutputs(n),Me=We.filter(ye=>{const Fe=Bk(ye,qe,Ke,xe);return Fe||console.warn(`[HISTORY-DEDUP] Removing live output: uuid=${ye.uuid||"none"} ts=${ye.timestamp} lastHistTs=${xe} text="${ye.text.slice(0,80)}"`),Fe});if(We.length!==Me.length){console.warn(`[HISTORY-DEDUP] Cleared ${We.length-Me.length}/${We.length} overlapping outputs for agent ${n}`),W.clearOutputs(n);for(const ye of Me)W.addOutput(n,ye)}}if(!a.get(n)){for(let xe=J.length-1;xe>=0;xe--)if(J[xe].type==="user"){W.setLastPrompt(n,J[xe].content);break}}}).catch(he=>{if(console.error("Failed to load history:",he),c([]),_.current=0,k(!1),P.current=!1,A(0),G&&V&&V.length>0){W.clearOutputs(n);for(const J of V)W.addOutput(n,J)}}).finally(()=>{E.current&&ge===D.current&&(O.current&&(clearTimeout(O.current),O.current=null),f(!1),m(!1),y(he=>he+1))})},[n,e,t,s]);const U=x.useCallback(async()=>{if(!n||F.current||!P.current)return;const q=r.current;if(!q){console.warn("loadMoreHistory: outputScrollRef not connected");return}const Y=q.scrollHeight-q.scrollTop;F.current=!0,S(!0);const B=_.current;try{const te=await(await Lt(Et(`/api/agents/${n}/history?limit=${Ok}&offset=${B}`))).json(),V=Array.isArray(te.subagents)?te.subagents:[];if(V.length>0&&W.hydrateSubagentsFromHistory(n,V),te.messages&&te.messages.length>0){if(!E.current)return;c(he=>{const J=[...te.messages,...he];return _.current=J.length,J});const ge=te.hasMore||!1;P.current=ge,k(ge),requestAnimationFrame(()=>{requestAnimationFrame(()=>{E.current&&(r.current&&(r.current.scrollTop=r.current.scrollHeight-Y),F.current=!1,S(!1))})})}else{if(!E.current)return;F.current=!1,S(!1)}}catch(G){if(console.error("Failed to load more history:",G),!E.current)return;F.current=!1,S(!1)}},[n,r]),H=x.useCallback(q=>{if(!r.current||q.current)return;const{scrollTop:Y}=r.current;!F.current&&P.current&&Y<mO&&U()},[U,r]),I=x.useCallback(()=>{c([]),_.current=0,n&&Zs.delete(n)},[n]),$=x.useRef(!1),z=x.useCallback(async()=>{var q,Y;if(!(!n||!P.current)&&!(F.current||$.current)){$.current=!0,F.current=!0,S(!0);try{const G=await(await Lt(Et(`/api/agents/${n}/history?limit=100000&offset=0`))).json();if(!E.current)return;const te=Array.isArray(G.subagents)?G.subagents:[];te.length>0&&W.hydrateSubagentsFromHistory(n,te),G.messages&&G.messages.length>0&&(c(G.messages),_.current=G.messages.length),P.current=!1,k(!1),A(G.totalCount||((q=G.messages)==null?void 0:q.length)||0),Zs.set(n,{messages:G.messages||[],hasMore:!1,totalCount:G.totalCount||((Y=G.messages)==null?void 0:Y.length)||0})}catch(B){console.error("Failed to load all history:",B)}finally{E.current&&(F.current=!1,$.current=!1,S(!1))}}},[n]);return{history:i,loadingHistory:d,fetchingHistory:h,historyLoadVersion:b,loadingMore:v,hasMore:N,totalCount:C,isMountedRef:E,loadMoreHistory:U,loadAllHistory:z,allLoaded:!N,handleScroll:H,clearHistory:I,hasCachedHistory:x.useCallback(q=>Zs.has(q),[])}}function Dc(...n){}function SO(n){return(n.tokensUsed??0)===0&&(n.contextUsed??0)===0&&!n.contextStats&&!n.sessionId&&!n.currentTask&&!n.lastAssignedTask}function Fk(n,e){var r,i;if(!n||SO(e))return e;const t=((r=n.contextStats)==null?void 0:r.lastUpdated)??0,s=((i=e.contextStats)==null?void 0:i.lastUpdated)??0;return t>0&&t>s?{...e,contextUsed:n.contextUsed,contextLimit:n.contextLimit,contextStats:n.contextStats}:e}function CO(n,e,t,s,a){return{setAgents(r){const i=new Map,c=n().agents;for(const f of r){const h=c.get(f.id);i.set(f.id,Fk(h,f)),(f.class==="boss"||f.isBoss)&&Dc("[Store.setAgents] Boss agent:",f.name,"subordinateIds:",f.subordinateIds)}const d=r.find(f=>f.status==="working");e(f=>{f.agents=i,d&&f.selectedAgentIds.size===0&&(f.selectedAgentIds=new Set([d.id]),f.terminalOpen=!0)}),t()},addAgent(r){e(i=>{const c=new Map(i.agents);c.set(r.id,r),i.agents=c}),t()},updateAgent(r){var v;const c=n().agents.get(r.id);let d=r;const f=r.trackingStatus,h=f!=null&&f!=="working";(c==null?void 0:c.status)!=="working"&&r.status==="working"&&!h&&(d={...r,trackingStatus:"working",trackingStatusDetail:void 0,trackingStatusTimestamp:r.trackingStatusTimestamp??Date.now()});const b=(c==null?void 0:c.status)!==d.status;b&&Dc(`[Store] Agent ${d.name} status update: ${c==null?void 0:c.status} → ${d.status}`);let y=!1;e(S=>{const N=new Map(S.agents);N.set(d.id,Fk(c,d)),S.agents=N,b&&(c==null?void 0:c.status)==="working"&&d.status==="idle"&&(S.terminalOpen&&S.selectedAgentIds.has(d.id)||(S.agentsWithUnseenOutput=new Set(S.agentsWithUnseenOutput),S.agentsWithUnseenOutput.add(d.id),Dc(`[Store] Agent ${d.name} completed work - marked as unseen`),y=!0))}),y&&a&&a(),t(),b&&Dc(`[Store] Agent ${d.name} status now in store: ${(v=n().agents.get(d.id))==null?void 0:v.status}`)},updateAgentContextStats(r,i){const d=n().agents.get(r);d&&(e(f=>{const h=new Map(f.agents);h.set(r,{...d,contextStats:i,contextUsed:i.totalTokens,contextLimit:i.contextWindow}),f.agents=h}),t())},updateAgentContext(r,i,c){const f=n().agents.get(r);if(f){const h=Math.max(1,c||2e5),m=Math.max(0,Math.min(100,Number((i/h*100).toFixed(1))));e(b=>{const y=new Map(b.agents),v=f.contextStats?{...f.contextStats,totalTokens:i,contextWindow:h,usedPercent:m,lastUpdated:Date.now()}:void 0;y.set(r,{...f,contextUsed:i,contextLimit:h,contextStats:v}),b.agents=y}),t()}},removeAgent(r){const i=n().agentsWithUnseenOutput.has(r);e(c=>{const d=new Map(c.agents);d.delete(r),c.agents=d;const f=new Set(c.selectedAgentIds);f.delete(r),c.selectedAgentIds=f,c.agentOutputs.delete(r),c.lastPrompts.delete(r),c.agentsWithUnseenOutput.has(r)&&(c.agentsWithUnseenOutput=new Set(c.agentsWithUnseenOutput),c.agentsWithUnseenOutput.delete(r)),c.delegationHistories.delete(r),c.lastDelegationReceived.delete(r),c.agentTaskProgress.delete(r),c.subagents.delete(r)}),vO(r),i&&a&&a(),t()},selectAgent(r){let i=!1;e(c=>{c.selectedAgentIds=new Set(r?[r]:[]),r&&(c.lastSelectedAgentId=r,c.agentsWithUnseenOutput.has(r)&&(c.agentsWithUnseenOutput=new Set(c.agentsWithUnseenOutput),c.agentsWithUnseenOutput.delete(r),i=!0))}),i&&a&&a(),t()},addToSelection(r){let i=!1;e(c=>{const d=new Set(c.selectedAgentIds);d.has(r)?d.delete(r):(d.add(r),c.agentsWithUnseenOutput.has(r)&&(c.agentsWithUnseenOutput=new Set(c.agentsWithUnseenOutput),c.agentsWithUnseenOutput.delete(r),i=!0)),c.selectedAgentIds=d}),i&&a&&a(),t()},selectMultiple(r){e(i=>{i.selectedAgentIds=new Set(r)}),t()},deselectAll(){e(r=>{r.selectedAgentIds=new Set}),t()},spawnAgent(r,i,c,d,f,h,m,b,y,v,S,N,k,C,A){Dc("[Store] spawnAgent called with:",{name:r,agentClass:i,cwd:c,position:d,sessionId:f,useChrome:h,permissionMode:m,initialSkillIds:b,provider:y,codexConfig:v,codexModel:S,model:N,effort:C,opencodeModel:A,customInstructions:k?`${k.length} chars`:void 0});const E=d?{x:d.x,y:0,z:d.z}:void 0,D={type:"spawn_agent",payload:{name:r,class:i,cwd:c,position:E,sessionId:f,useChrome:h,permissionMode:m,initialSkillIds:b,provider:y,codexConfig:v,codexModel:S,opencodeModel:A,model:N,effort:C,customInstructions:k}},_=s();if(!_){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}_(D)},createDirectoryAndSpawn(r,i,c){var d;(d=s())==null||d({type:"create_directory",payload:{path:r,name:i,class:c}})},sendCommand(r,i){var c;e(d=>{d.lastPrompts.set(r,{text:i,timestamp:Date.now()})}),t(),(c=s())==null||c({type:"send_command",payload:{agentId:r,command:i}})},refreshAgentContext(r){var i;(i=s())==null||i({type:"request_context_stats",payload:{agentId:r}})},moveAgentLocal(r,i){const d=n().agents.get(r);d&&(e(f=>{const h={...d,position:i},m=new Map(f.agents);m.set(r,h),f.agents=m}),t())},moveAgent(r,i){var f;const d=n().agents.get(r);d&&(e(h=>{const m={...d,position:i},b=new Map(h.agents);b.set(r,m),h.agents=b}),t()),(f=s())==null||f({type:"move_agent",payload:{agentId:r,position:i}})},killAgent(r){var i;(i=s())==null||i({type:"kill_agent",payload:{agentId:r}})},stopAgent(r){var i;(i=s())==null||i({type:"stop_agent",payload:{agentId:r}})},clearContext(r){var i;(i=s())==null||i({type:"clear_context",payload:{agentId:r}}),e(c=>{const d=c.agents.get(r);if(d){const y={...d,status:"idle",currentTask:void 0,taskLabel:void 0,trackingStatus:void 0,trackingStatusDetail:void 0,trackingStatusTimestamp:void 0,currentTool:void 0,lastAssignedTask:void 0,lastAssignedTaskTime:void 0,sessionId:void 0,tokensUsed:0,contextUsed:0,contextStats:void 0},v=new Map(c.agents);v.set(r,y),c.agents=v}const f=new Map(c.agentOutputs);f.delete(r),c.agentOutputs=f;const h=new Map(c.lastPrompts);h.delete(r),c.lastPrompts=h;const m=new Map(c.subagents);let b=!1;for(const[y,v]of m)v.parentAgentId===r&&(m.delete(y),b=!0);b&&(c.subagents=m)}),t()},restoreSession(r,i){var c;(c=s())==null||c({type:"restore_session",payload:{agentId:r,sessionId:i}}),e(d=>{const f=d.agents.get(r);if(f){const b={...f,status:"idle",currentTask:void 0,taskLabel:void 0,currentTool:void 0,sessionId:i,tokensUsed:0,contextUsed:0,contextStats:void 0},y=new Map(d.agents);y.set(r,b),d.agents=y}const h=new Map(d.agentOutputs);h.delete(r),d.agentOutputs=h;const m=new Map(d.lastPrompts);m.delete(r),d.lastPrompts=m}),t()},requestSessionHistory(r){var i;(i=s())==null||i({type:"request_session_history",payload:{agentId:r}})},setSessionHistory(r,i){e(c=>{const d=new Map(c.sessionHistories);d.set(r,i),c.sessionHistories=d}),t()},getSessionHistory(r){return n().sessionHistories.get(r)||[]},collapseContext(r){var i;(i=s())==null||i({type:"collapse_context",payload:{agentId:r}})},removeAgentFromServer(r){var i;(i=s())==null||i({type:"remove_agent",payload:{agentId:r}})},renameAgent(r,i){var f;const d=n().agents.get(r);d&&(e(h=>{const m={...d,name:i},b=new Map(h.agents);b.set(r,m),h.agents=b}),t()),(f=s())==null||f({type:"rename_agent",payload:{agentId:r,name:i}})},updateAgentProperties(r,i){var f;const d=n().agents.get(r);d&&(e(h=>{const m={...d};i.class!==void 0&&(m.class=i.class),i.permissionMode!==void 0&&(m.permissionMode=i.permissionMode),i.model!==void 0&&(m.model=i.model),i.effort!==void 0&&(m.effort=i.effort),i.provider!==void 0&&(m.provider=i.provider),i.codexConfig!==void 0&&(m.codexConfig=i.codexConfig),i.codexModel!==void 0&&(m.codexModel=i.codexModel),i.opencodeModel!==void 0&&(m.opencodeModel=i.opencodeModel),i.useChrome!==void 0&&(m.useChrome=i.useChrome),i.cwd!==void 0&&(m.cwd=i.cwd),i.shortcut!==void 0&&(m.shortcut=i.shortcut);const b=new Map(h.agents);b.set(r,m),h.agents=b}),t()),(f=s())==null||f({type:"update_agent_properties",payload:{agentId:r,updates:i}}),i.shortcut!==void 0&&Lt(Et(`/api/agents/${r}`),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:i.shortcut})}).catch(h=>{console.error("[Store] Failed to persist agent shortcut",h)})},getTotalTokens(){let r=0;for(const i of n().agents.values())r+=i.tokensUsed;return r},getSelectedAgents(){const r=n(),i=[];for(const c of r.selectedAgentIds){const d=r.agents.get(c);d&&i.push(d)}return i},addActivity(r){e(i=>{i.activities.unshift(r),i.activities.length>100&&i.activities.pop()}),t()},addToolExecution(r,i,c){const f=n().agents.get(r);e(h=>{h.toolExecutions.unshift({agentId:r,agentName:(f==null?void 0:f.name)||"Unknown",toolName:i,toolInput:c,timestamp:Date.now()}),h.toolExecutions.length>200&&h.toolExecutions.pop()}),t()},addFileChange(r,i,c){const f=n().agents.get(r);e(h=>{h.fileChanges.unshift({agentId:r,agentName:(f==null?void 0:f.name)||"Unknown",action:i,filePath:c,timestamp:Date.now()}),h.fileChanges.length>200&&h.fileChanges.pop()}),t()},async loadToolHistory(){try{const i=await(await Lt(Et("/api/agents/tool-history?limit=100"))).json();e(c=>{i.toolExecutions&&(c.toolExecutions=i.toolExecutions),i.fileChanges&&(c.fileChanges=i.fileChanges)}),t()}catch(r){console.error("[Store] Failed to load tool history:",r)}}}}const zk=200;function $k(n){return n.length<=zk?n:n.slice(-zk)}function AO(n,e,t,s){return{addOutput(a,r){const i=s();e(c=>{const d=c.agentOutputs.get(a)||[];if(r.uuid&&d.some(b=>b.uuid===r.uuid))return;const f=$k([...d,r]);hu.info(`Store: ${d.length} -> ${f.length}`,{agentId:a,text:r.text.slice(0,60),isStreaming:r.isStreaming,listeners:i},"store:addOutput");const h=new Map(c.agentOutputs);h.set(a,f),c.agentOutputs=h}),t()},clearOutputs(a){e(r=>{const i=new Map(r.agentOutputs);i.delete(a),r.agentOutputs=i}),t()},getOutputs(a){return n().agentOutputs.get(a)||[]},addUserPromptToOutput(a,r){this.addOutput(a,{text:r,isStreaming:!1,timestamp:Date.now(),isUserPrompt:!0})},getLastPrompt(a){return n().lastPrompts.get(a)},setLastPrompt(a,r){e(i=>{i.lastPrompts.set(a,{text:r,timestamp:Date.now()})}),t()},preserveOutputs(){const a=n(),r=new Map;for(const[i,c]of a.agentOutputs)r.set(i,c.map(d=>({...d})));return r},mergeOutputsWithHistory(a,r,i){let c=[...r,...i];return c.sort((d,f)=>d.timestamp-f.timestamp),c=$k(c),e(d=>{const f=new Map(d.agentOutputs);f.set(a,c),d.agentOutputs=f}),t(),c}}}function jO(n,e,t,s){const a=()=>{var c;const i=Array.from(n().areas.values());(c=s())==null||c({type:"sync_areas",payload:i})},r=()=>{e(i=>{i.areas=new Map(i.areas)})};return{setActiveTool(i){e(c=>{c.activeTool=i,i!=="select"&&(c.selectedAreaId=null)}),t()},selectArea(i){e(c=>{c.selectedAreaId=i}),t()},addArea(i){if(i.zIndex===void 0||i.zIndex===null){const c=Array.from(n().areas.values()),d=c.length===0?-1:Math.max(...c.map(f=>f.zIndex??0));i.zIndex=d+1}e(c=>{c.areas.set(i.id,i)}),r(),a(),t()},updateArea(i,c){n().areas.get(i)&&(e(h=>{Object.assign(h.areas.get(i),c)}),r(),a(),t())},updateAreaLocal(i,c){n().areas.get(i)&&(e(h=>{Object.assign(h.areas.get(i),c)}),r(),t())},deleteArea(i){e(c=>{c.areas.delete(i),c.selectedAreaId===i&&(c.selectedAreaId=null)}),r(),a(),t()},assignAgentToArea(i,c){const f=n().areas.get(c);f&&!f.assignedAgentIds.includes(i)&&(e(h=>{for(const m of h.areas.values()){const b=m.assignedAgentIds.indexOf(i);b!==-1&&m.assignedAgentIds.splice(b,1)}h.areas.get(c).assignedAgentIds.push(i)}),r(),a(),t())},unassignAgentFromArea(i,c){const f=n().areas.get(c);if(f){const h=f.assignedAgentIds.indexOf(i);h!==-1&&(e(m=>{m.areas.get(c).assignedAgentIds.splice(h,1)}),r(),a(),t())}},addDirectoryToArea(i,c){const f=n().areas.get(i);f&&!f.directories.includes(c)&&(e(h=>{h.areas.get(i).directories.push(c)}),r(),a(),t())},removeDirectoryFromArea(i,c){const f=n().areas.get(i);if(f){const h=f.directories.indexOf(c);h!==-1&&(e(m=>{m.areas.get(i).directories.splice(h,1)}),r(),a(),t())}},getAreaDirectories(i){const c=n().areas.get(i);return(c==null?void 0:c.directories)||[]},isPositionInArea(i,c){if(c.type==="rectangle"&&c.width&&c.height){const d=c.width/2,f=c.height/2;return i.x>=c.center.x-d&&i.x<=c.center.x+d&&i.z>=c.center.z-f&&i.z<=c.center.z+f}else if(c.type==="circle"&&c.radius){const d=i.x-c.center.x,f=i.z-c.center.z;return d*d+f*f<=c.radius*c.radius}return!1},getAreaForAgent(i){const c=n(),d=c.agents.get(i);if(!d)return null;for(const f of c.areas.values())if(this.isPositionInArea({x:d.position.x,z:d.position.z},f))return f;return null},setAreasFromServer(i){e(c=>{const d=new Map;for(let f=0;f<i.length;f++){const h=i[f];if(!h.center||typeof h.center.x!="number"||typeof h.center.z!="number"||!h.type){console.error(`[Areas] Skipping malformed area "${(h==null?void 0:h.id)??(h==null?void 0:h.name)??"unknown"}": missing center or type`);continue}h.directories||(h.directories=[]),(h.zIndex===void 0||h.zIndex===null)&&(h.zIndex=f),h.archived===void 0&&(h.archived=!1),d.set(h.id,h)}c.areas=d}),t()},getAreasInZOrder(){return Array.from(n().areas.values()).sort((c,d)=>(c.zIndex??0)-(d.zIndex??0))},getNextZIndex(){const i=Array.from(n().areas.values());return i.length===0?0:Math.max(...i.map(d=>d.zIndex??0))+1},bringAreaToFront(i){const c=n(),d=c.areas.get(i);if(!d)return;const f=Array.from(c.areas.values()),h=f.length===0?-1:Math.max(...f.map(v=>v.zIndex??0)),m=h+1,b=d.zIndex??0,y=f.filter(v=>(v.zIndex??0)===h);b===h&&y.length===1||(e(v=>{v.areas.get(i).zIndex=m}),r(),a(),t())},sendAreaToBack(i){const c=n(),d=c.areas.get(i);if(!d)return;const f=Array.from(c.areas.values()),h=Math.min(...f.map(y=>y.zIndex??0)),m=d.zIndex??0,b=f.filter(y=>(y.zIndex??0)===h);m===h&&b.length===1||(e(y=>{for(const v of y.areas.values())v.id!==i&&(v.zIndex=(v.zIndex??0)+1);y.areas.get(i).zIndex=0}),r(),a(),t())},setAreaZIndex(i,c){n().areas.get(i)&&(e(h=>{h.areas.get(i).zIndex=c}),r(),a(),t())},archiveArea(i,c){const f=n().areas.get(i);if(!(!f||f.archived)){if(c)for(const h of f.assignedAgentIds)c(h);e(h=>{const m=h.areas.get(i);m.archived=!0,m.archivedAt=Date.now(),m.originalCenter={...m.center},h.selectedAreaId===i&&(h.selectedAreaId=null)}),r(),a(),t()}},restoreArchivedArea(i,c){const d=n(),f=d.areas.get(i);if(!f||!f.archived)return;const h=f.center,m=c||f.originalCenter||f.center,b=m.x-h.x,y=m.z-h.z,v=Array.from(d.areas.values()),N=(v.length===0?-1:Math.max(...v.map(k=>k.zIndex??0)))+1;e(k=>{const C=k.areas.get(i);if(C.archived=!1,C.archivedAt=void 0,C.center=m,C.zIndex=N,b!==0||y!==0)for(const A of C.assignedAgentIds){const E=k.agents.get(A);E&&(E.position={x:E.position.x+b,y:E.position.y,z:E.position.z+y})}}),r(),a(),t()},getArchivedAreas(){return Array.from(n().areas.values()).filter(i=>i.archived===!0)},getVisibleAreas(){return Array.from(n().areas.values()).filter(i=>!i.archived)},isAgentInArchivedArea(i){const c=n();for(const d of c.areas.values())if(d.archived&&d.assignedAgentIds.includes(i))return!0;return!1}}}const vj="tide:bottom-pm2-log-retention",tg=5e3,NO=[1e3,2500,5e3,1e4,null];function wj(){if(typeof window>"u")return tg;try{const n=window.localStorage.getItem(vj);if(!n)return tg;if(n==="unlimited")return null;const e=Number(n);if(Number.isFinite(e)&&e>0)return Math.floor(e)}catch{}return tg}function TO(n){if(!(typeof window>"u"))try{window.localStorage.setItem(vj,n===null?"unlimited":String(n))}catch{}}function kj(n,e){if(!n||e===null)return n;const t=n.split(`
44
44
  `);return t.length<=e?n:t.slice(-e).join(`
45
45
  `)}function _O(n,e,t,s){const a=()=>{var c;const i=Array.from(n().buildings.values());(c=s())==null||c({type:"sync_buildings",payload:i})},r={selectBuilding(i){e(c=>{c.selectedBuildingIds.clear(),i&&c.selectedBuildingIds.add(i)}),t()},selectMultipleBuildings(i){e(c=>{c.selectedBuildingIds.clear();for(const d of i)c.selectedBuildingIds.add(d)}),t()},toggleBuildingSelection(i){e(c=>{c.selectedBuildingIds.has(i)?c.selectedBuildingIds.delete(i):c.selectedBuildingIds.add(i)}),t()},isBuildingSelected(i){return n().selectedBuildingIds.has(i)},getSelectedBuildingIds(){return Array.from(n().selectedBuildingIds)},deleteSelectedBuildings(){var c,d,f;const i=n();for(const h of i.selectedBuildingIds){const m=i.buildings.get(h);((c=m==null?void 0:m.pm2)!=null&&c.enabled||(d=m==null?void 0:m.docker)!=null&&d.enabled)&&((f=s())==null||f({type:"building_command",payload:{buildingId:h,command:"delete"}}))}e(h=>{const m=new Map(h.buildings);for(const b of h.selectedBuildingIds)m.delete(b);h.buildings=m,h.selectedBuildingIds.clear()}),a(),t()},addBuilding(i){e(c=>{const d=new Map(c.buildings);d.set(i.id,i),c.buildings=d}),a(),t()},updateBuilding(i,c){const f=n().buildings.get(i);f&&(e(h=>{const m=new Map(h.buildings);m.set(i,{...f,...c}),h.buildings=m}),a(),t())},updateBuildingLocal(i,c){const f=n().buildings.get(i);f&&(e(h=>{const m=new Map(h.buildings);m.set(i,{...f,...c}),h.buildings=m}),t())},deleteBuilding(i){var f,h,m;const d=n().buildings.get(i);((f=d==null?void 0:d.pm2)!=null&&f.enabled||(h=d==null?void 0:d.docker)!=null&&h.enabled)&&((m=s())==null||m({type:"building_command",payload:{buildingId:i,command:"delete"}})),e(b=>{const y=new Map(b.buildings);y.delete(i),b.buildings=y,b.selectedBuildingIds.delete(i)}),a(),t()},moveBuilding(i,c){const f=n().buildings.get(i);f&&(e(h=>{const m=new Map(h.buildings);m.set(i,{...f,position:c}),h.buildings=m}),a(),t())},updateBuildingPosition(i,c){r.moveBuilding(i,c)},createBuilding(i){const c={...i,id:`building_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,status:"stopped",createdAt:Date.now()};r.addBuilding(c)},sendBuildingCommand(i,c){var d;(d=s())==null||d({type:"building_command",payload:{buildingId:i,command:c}})},addBuildingLogs(i,c){e(d=>{const h=[...d.buildingLogs.get(i)||[],c];h.length>500&&h.splice(0,h.length-500);const m=new Map(d.buildingLogs);m.set(i,h),d.buildingLogs=m}),t()},getBuildingLogs(i){return n().buildingLogs.get(i)||[]},clearBuildingLogs(i){e(c=>{const d=new Map(c.buildingLogs);d.delete(i),c.buildingLogs=d}),t()},setBuildingsFromServer(i){e(c=>{const d=new Map;for(const f of i)d.set(f.id,f);c.buildings=d}),t()},updateBuildingFromServer(i){e(c=>{const d=new Map(c.buildings);d.set(i.id,i),c.buildings=d}),t()},removeBuildingFromServer(i){e(c=>{const d=new Map(c.buildings);d.delete(i),c.buildings=d,c.selectedBuildingIds.delete(i)}),t()},startLogStreaming(i,c=100){var f,h,m;const d=n().buildings.get(i);e(b=>{const y=new Map(b.streamingBuildingLogs);y.set(i,""),b.streamingBuildingLogs=y}),(f=d==null?void 0:d.docker)!=null&&f.enabled?(h=s())==null||h({type:"docker_logs_start",payload:{buildingId:i,lines:c}}):(m=s())==null||m({type:"pm2_logs_start",payload:{buildingId:i,lines:c}})},stopLogStreaming(i){var d,f,h;const c=n().buildings.get(i);(d=c==null?void 0:c.docker)!=null&&d.enabled?(f=s())==null||f({type:"docker_logs_stop",payload:{buildingId:i}}):(h=s())==null||h({type:"pm2_logs_stop",payload:{buildingId:i}})},appendStreamingLogChunk(i,c){e(d=>{const f=d.streamingBuildingLogs.get(i)||"",h=wj(),m=kj(f+c,h),b=new Map(d.streamingBuildingLogs);b.set(i,m),d.streamingBuildingLogs=b}),t()},setStreamingStatus(i,c){e(d=>{const f=new Set(d.streamingBuildingIds);c?f.add(i):f.delete(i),d.streamingBuildingIds=f}),t()},getStreamingLogs(i){return n().streamingBuildingLogs.get(i)||""},clearStreamingLogs(i){e(c=>{const d=new Map(c.streamingBuildingLogs);d.delete(i),c.streamingBuildingLogs=d}),t()},isLogStreaming(i){return n().streamingBuildingIds.has(i)},sendBossBuildingCommand(i,c){var d;(d=s())==null||d({type:"boss_building_command",payload:{buildingId:i,command:c}})},assignBuildingsToBoSS(i,c){var h;const f=n().buildings.get(i);f&&(e(m=>{const b=new Map(m.buildings);b.set(i,{...f,subordinateBuildingIds:c}),m.buildings=b}),a(),t()),(h=s())==null||h({type:"assign_buildings",payload:{bossBuildingId:i,subordinateBuildingIds:c}})},startBossLogStreaming(i,c=50){var d;e(f=>{const h=new Map(f.bossStreamingLogs);h.set(i,[]),f.bossStreamingLogs=h}),(d=s())==null||d({type:"boss_building_logs_start",payload:{buildingId:i,lines:c}})},stopBossLogStreaming(i){var c;(c=s())==null||c({type:"boss_building_logs_stop",payload:{buildingId:i}})},appendBossStreamingLogChunk(i,c,d,f,h){e(m=>{const b=m.bossStreamingLogs.get(i)||[],y={subordinateId:c,subordinateName:d,chunk:f,timestamp:Date.now(),isError:h},v=[...b,y];v.length>1e3&&v.splice(0,v.length-1e3);const S=new Map(m.bossStreamingLogs);S.set(i,v),m.bossStreamingLogs=S}),t()},getBossStreamingLogs(i){return n().bossStreamingLogs.get(i)||[]},clearBossStreamingLogs(i){e(c=>{const d=new Map(c.bossStreamingLogs);d.delete(i),c.bossStreamingLogs=d}),t()},requestDockerContainersList(){var i;(i=s())==null||i({type:"docker_list_containers",payload:{}})},setDockerContainersList(i,c){e(d=>{d.dockerContainersList=i,d.dockerComposeProjectsList=c}),t()},getDockerContainersList(){return n().dockerContainersList},getDockerComposeProjectsList(){return n().dockerComposeProjectsList}};return r}function EO(n,e,t,s){return{addPermissionRequest(a){e(r=>{const i=new Map(r.permissionRequests);i.set(a.id,a),r.permissionRequests=i}),t()},resolvePermissionRequest(a,r){const c=n().permissionRequests.get(a);c&&(e(d=>{const f=new Map(d.permissionRequests);f.set(a,{...c,status:r?"approved":"denied"}),d.permissionRequests=f}),t(),setTimeout(()=>{e(d=>{const f=new Map(d.permissionRequests);f.delete(a),d.permissionRequests=f}),t()},2e3))},respondToPermissionRequest(a,r,i,c){var d;(d=s())==null||d({type:"permission_response",payload:{requestId:a,approved:r,reason:i,remember:c}})},getPendingPermissionsForAgent(a){return Array.from(n().permissionRequests.values()).filter(r=>r.agentId===a&&r.status==="pending")},clearAllPermissions(){e(a=>{a.permissionRequests=new Map}),t()}}}function MO(n,e,t,s){return{spawnBossAgent(a,r,i,c,d,f,h,m,b,y,v,S,N){var C;const k=c?{x:c.x,y:0,z:c.z}:void 0;(C=s())==null||C({type:"spawn_boss_agent",payload:{name:a,class:r,cwd:i,position:k,subordinateIds:d,useChrome:f,permissionMode:h,provider:m,codexConfig:b,codexModel:y,model:v,customInstructions:S,initialSkillIds:N}})},assignSubordinates(a,r){var i;(i=s())==null||i({type:"assign_subordinates",payload:{bossId:a,subordinateIds:r}})},removeSubordinate(a,r){var i;(i=s())==null||i({type:"remove_subordinate",payload:{bossId:a,subordinateId:r}})},sendBossCommand(a,r){var i;e(c=>{c.pendingDelegation={bossId:a,command:r}}),t(),(i=s())==null||i({type:"send_boss_command",payload:{bossId:a,command:r}})},requestDelegationHistory(a){var r;(r=s())==null||r({type:"request_delegation_history",payload:{bossId:a}})},handleDelegationDecision(a){e(r=>{var f;const i=new Map(r.delegationHistories),c=i.get(a.bossId)||[],d=c.findIndex(h=>h.id===a.id);if(d!==-1?c[d]=a:(c.unshift(a),c.length>100&&c.pop()),i.set(a.bossId,c),r.delegationHistories=i,a.status==="sent"&&a.selectedAgentId){const h=r.agents.get(a.bossId),m=new Map(r.lastDelegationReceived);m.set(a.selectedAgentId,{bossName:(h==null?void 0:h.name)||"Boss",taskCommand:a.userCommand,timestamp:Date.now()}),r.lastDelegationReceived=m}((f=r.pendingDelegation)==null?void 0:f.bossId)===a.bossId&&a.status!=="pending"&&(r.pendingDelegation=null)}),t()},setDelegationHistory(a,r){e(i=>{const c=new Map(i.delegationHistories);c.set(a,r),i.delegationHistories=c}),t()},getDelegationHistory(a){return n().delegationHistories.get(a)||[]},getLastDelegationReceived(a){return n().lastDelegationReceived.get(a)||null},clearLastDelegationReceived(a){n().lastDelegationReceived.has(a)&&(e(i=>{const c=new Map(i.lastDelegationReceived);c.delete(a),i.lastDelegationReceived=c}),t())},updateBossSubordinates(a,r){const c=n().agents.get(a);c&&(e(d=>{const f={...c,subordinateIds:r},h=new Map(d.agents);h.set(a,f),d.agents=h}),t())},getSubordinates(a){const r=n(),i=r.agents.get(a),c=(i==null?void 0:i.isBoss)===!0||(i==null?void 0:i.class)==="boss";return!i||!c||!i.subordinateIds?[]:i.subordinateIds.map(d=>r.agents.get(d)).filter(d=>d!==void 0)},isBossAgent(a){const r=n().agents.get(a);return(r==null?void 0:r.isBoss)===!0||(r==null?void 0:r.class)==="boss"},getBossForAgent(a){const r=n(),i=r.agents.get(a);return i!=null&&i.bossId&&r.agents.get(i.bossId)||null},getAvailableSubordinates(){return Array.from(n().agents.values()).filter(a=>a.class!=="boss")},handleAgentTaskStarted(a,r,i,c){e(d=>{const f=new Map(d.agentTaskProgress);let h=f.get(a);h||(h=new Map,f.set(a,h)),h.set(r,{agentId:r,agentName:i,taskDescription:c,status:"working",output:[],startedAt:Date.now()}),d.agentTaskProgress=f}),t()},handleAgentTaskOutput(a,r,i){e(c=>{const d=c.agentTaskProgress.get(a);if(!d)return;const f=d.get(r);if(!f)return;const h=200;let m=[...f.output,i];m.length>h&&(m=m.slice(-h));const b=new Map(c.agentTaskProgress),y=new Map(d);y.set(r,{...f,output:m}),b.set(a,y),c.agentTaskProgress=b}),t()},handleAgentTaskCompleted(a,r,i){e(c=>{const d=c.agentTaskProgress.get(a);if(!d)return;const f=d.get(r);if(!f)return;const h=f.output.length>20?f.output.slice(-20):f.output,m=new Map(c.agentTaskProgress),b=new Map(d);b.set(r,{...f,status:i?"completed":"failed",completedAt:Date.now(),output:h}),m.set(a,b),c.agentTaskProgress=m}),t()},getAgentTaskProgress(a){return n().agentTaskProgress.get(a)||new Map},clearAgentTaskProgress(a,r){e(i=>{if(r){const c=i.agentTaskProgress.get(a);if(c){const d=new Map(i.agentTaskProgress),f=new Map(c);f.delete(r),d.set(a,f),i.agentTaskProgress=d}}else{const c=new Map(i.agentTaskProgress);c.delete(a),i.agentTaskProgress=c}}),t()},clearAllSubordinatesContext(a){const i=n().agents.get(a),c=(i==null?void 0:i.isBoss)===!0||(i==null?void 0:i.class)==="boss";if(console.log("[Store] clearAllSubordinatesContext called:",{bossId:a,bossName:i==null?void 0:i.name,isBoss:c,subordinateIds:i==null?void 0:i.subordinateIds}),!i||!c||!i.subordinateIds||i.subordinateIds.length===0){console.log("[Store] clearAllSubordinatesContext: No boss or subordinates found, returning early");return}const d=s();console.log("[Store] clearAllSubordinatesContext: sendMessage available:",!!d);for(const f of i.subordinateIds)console.log("[Store] clearAllSubordinatesContext: Sending clear_context for subordinate:",f),d==null||d({type:"clear_context",payload:{agentId:f}});e(f=>{const h=new Map(f.agentOutputs);for(const m of i.subordinateIds||[])h.delete(m);f.agentOutputs=h}),t(),console.log("[Store] clearAllSubordinatesContext: Completed")}}}function DO(n,e,t,s){return{setSkillsFromServer(a){e(r=>{const i=new Map;for(const c of a)i.set(c.id,c);r.skills=i}),t()},addSkillFromServer(a){e(r=>{const i=new Map(r.skills);i.set(a.id,a),r.skills=i}),t()},updateSkillFromServer(a){e(r=>{const i=new Map(r.skills);i.set(a.id,a),r.skills=i}),t()},removeSkillFromServer(a){e(r=>{const i=new Map(r.skills);i.delete(a),r.skills=i}),t()},getSkill(a){return n().skills.get(a)},getAllSkills(){return Array.from(n().skills.values())},getSkillsForAgent(a){const r=n(),i=r.agents.get(a);return i?Array.from(r.skills.values()).filter(c=>c.enabled?!!(c.assignedAgentIds.includes(a)||c.assignedAgentClasses.includes(i.class)):!1):[]},createSkill(a){var r;(r=s())==null||r({type:"create_skill",payload:a})},updateSkill(a,r){var i;(i=s())==null||i({type:"update_skill",payload:{id:a,updates:r}})},deleteSkill(a){var r;(r=s())==null||r({type:"delete_skill",payload:{id:a}})},assignSkillToAgent(a,r){var i;(i=s())==null||i({type:"assign_skill",payload:{skillId:a,agentId:r}})},unassignSkillFromAgent(a,r){var i;(i=s())==null||i({type:"unassign_skill",payload:{skillId:a,agentId:r}})},requestAgentSkills(a){var r;(r=s())==null||r({type:"request_agent_skills",payload:{agentId:a}})},setCustomAgentClassesFromServer(a){e(r=>{const i=new Map;for(const c of a)i.set(c.id,c);r.customAgentClasses=i}),t()},addCustomAgentClassFromServer(a){e(r=>{const i=new Map(r.customAgentClasses);i.set(a.id,a),r.customAgentClasses=i}),t()},updateCustomAgentClassFromServer(a){e(r=>{const i=new Map(r.customAgentClasses);i.set(a.id,a),r.customAgentClasses=i}),t()},removeCustomAgentClassFromServer(a){e(r=>{const i=new Map(r.customAgentClasses);i.delete(a),r.customAgentClasses=i}),t()},getCustomAgentClass(a){return n().customAgentClasses.get(a)},getAllCustomAgentClasses(){return Array.from(n().customAgentClasses.values())},createCustomAgentClass(a){var r;(r=s())==null||r({type:"create_custom_agent_class",payload:a})},updateCustomAgentClass(a,r){var i;(i=s())==null||i({type:"update_custom_agent_class",payload:{id:a,updates:r}})},deleteCustomAgentClass(a){var r;(r=s())==null||r({type:"delete_custom_agent_class",payload:{id:a}})}}}function RO(n,e,t){return{handleExecTaskStarted(s,a,r,i,c){e(d=>{const f={taskId:s,agentId:a,agentName:r,command:i,cwd:c,status:"running",output:[],startedAt:Date.now()};d.execTasks||(d.execTasks=new Map),d.execTasks.set(s,f)}),t()},handleExecTaskOutput(s,a,r,i){e(c=>{var m;const d=(m=c.execTasks)==null?void 0:m.get(s);if(!d)return;const f=r.split(`
@@ -141,5 +141,5 @@ ${De}`:X=De}W.sendCommand(t,X),R==null||R(),r(""),c(!1),N(new Map),h([]),k(),win
141
141
  `)},v.onerror=q=>{Ht("WebSocket ERROR:",q)},b.onResize(({cols:q,rows:Y})=>h(q,Y))})(),()=>{var C;m=!0,c.current=!1,S==null||S.cancel(),N==null||N.disconnect(),k&&((C=s.current)==null||C.removeEventListener("contextmenu",k)),v&&v.readyState<=WebSocket.OPEN&&v.close(),i.current=null,b==null||b.dispose(),a.current=null,r.current=null}},[t,e,f,h]),x.useEffect(()=>{t&&r.current&&a.current&&requestAnimationFrame(()=>{var m;(m=r.current)==null||m.fit(),a.current&&h(a.current.cols,a.current.rows)})},[t,h]),o.jsx("div",{ref:s,className:"guake-bottom-terminal-embed",style:{display:t?void 0:"none"}})}),NW=128,TW=95;function _W(n,e){if(e.type==="rectangle"&&e.width&&e.height){const t=e.width/2,s=e.height/2;return n.x>=e.center.x-t&&n.x<=e.center.x+t&&n.z>=e.center.z-s&&n.z<=e.center.z+s}if(e.type==="circle"&&e.radius){const t=n.x-e.center.x,s=n.z-e.center.z;return t*t+s*s<=e.radius*e.radius}return!1}let EW=1;function gf(){return`bp-${EW++}`}const MW=x.memo(function({buildingId:e,filterText:t,maxRetention:s}){const{streamingBuildingLogs:a}=Fs(),r=a.get(e)||"",i=x.useRef(null),c=x.useRef(!1),d=x.useRef(0),f=t.trim().toLowerCase(),h=30,m=x.useCallback(()=>{const A=i.current;if(!A)return;const E=A.scrollTop+A.clientHeight>=A.scrollHeight-h;c.current=!E},[]),b=x.useMemo(()=>kj(r,s),[r,s]);x.useLayoutEffect(()=>{const A=i.current;if(!A)return;const E=d.current,D=A.scrollHeight;if(c.current){const _=E-D;_>0&&(A.scrollTop=Math.max(0,A.scrollTop-_))}else A.scrollTop=D;d.current=A.scrollHeight},[b,f]);const y=x.useMemo(()=>b?f?b.split(`
142
142
  `).filter(A=>A.toLowerCase().includes(f)).join(`
143
143
  `):b:"",[b,f]),v=x.useMemo(()=>y?y.split(`
144
- `):[],[y]),S=x.useMemo(()=>v.map(A=>Sl(A||" ")),[v]),N=x.useMemo(()=>b?f&&!y?"No log lines match the current filter.":null:"Waiting for logs...",[b,f,y]),k=Wj({count:S.length,getScrollElement:()=>i.current,estimateSize:()=>20,overscan:12,measureElement:A=>A.getBoundingClientRect().height}),C=k.getVirtualItems();return o.jsx("div",{ref:i,className:"guake-bottom-pm2-logs",onScroll:m,children:N?o.jsx("div",{className:"guake-bottom-pm2-logs-empty",children:N}):o.jsx("div",{className:"guake-bottom-pm2-logs-inner",style:{height:k.getTotalSize()},children:C.map(A=>o.jsx("div",{ref:k.measureElement,className:"guake-bottom-pm2-log-line","data-index":A.index,style:{transform:`translateY(${A.start}px)`},dangerouslySetInnerHTML:{__html:S[A.index]}},A.key))})})});x.memo(function({src:e,title:t}){const s=x.useRef(null),[a,r]=x.useState(!1),[i,c]=x.useState(null);x.useEffect(()=>{r(!1),c(null);const h=setTimeout(()=>c(e),400);return()=>clearTimeout(h)},[e]);const d=x.useCallback(()=>{var m;const h=s.current;if(h){document.activeElement===h&&h.blur();try{(m=h.contentWindow)==null||m.blur()}catch{}}},[]),f=x.useCallback(()=>{const h=document.querySelector(".guake-input-container"),m=h==null?void 0:h.querySelector("textarea, input");h==null||h.focus({preventScroll:!0}),m==null||m.focus({preventScroll:!0})},[]);return x.useEffect(()=>{if(!i)return;const h=Date.now(),m=()=>{Date.now()-h>1500||(d(),f())};return window.addEventListener("focus",m,!0),document.addEventListener("focusin",m,!0),()=>{window.removeEventListener("focus",m,!0),document.removeEventListener("focusin",m,!0)}},[f,d,i]),o.jsxs(o.Fragment,{children:[!a&&o.jsx("div",{className:"guake-bottom-terminal-starting",children:o.jsx("span",{children:"Loading terminal..."})}),o.jsx("iframe",{ref:s,src:i??void 0,className:`guake-bottom-terminal-iframe${a?"":" iframe-loading"}`,title:t,allow:"clipboard-read; clipboard-write",loading:"lazy",tabIndex:-1,onLoad:()=>{r(!0),d(),f()}})]})});const DW=x.memo(function(){var la,wo,ko,dr,fr,Fl,So,zl,Gr,ca,Co,Yr,ja;const{t:e}=ut(["terminal","common"]),t=Rl(),s=rx(),a=Tj(),r=_j(),i=ox(),c=lx(),d=Array.from(s),h=d.length===1?d[0]:null,b=mo(h)||null,y=h,v=xL(),S=x.useCallback(ne=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(ne)},[]),N=Pa(),k=ix(),C=x.useMemo(()=>{if(!y)return null;const ne=new Set,Te=[];for(const $e of N.values())$e.archived||$e.directories.length===0||$e.assignedAgentIds.includes(y)&&(ne.add($e.id),Te.push($e));const ve=t.get(y);if(ve)for(const $e of N.values())$e.archived||$e.directories.length===0||ne.has($e.id)||_W({x:ve.position.x,z:ve.position.z},$e)&&(ne.add($e.id),Te.push($e));return Te.length===0?null:Te.flatMap($e=>$e.directories.filter(ft=>ft&&ft.trim().length>0).map(ft=>({areaId:$e.id,areaName:$e.name,dir:ft})))},[y,N,t]),A=x.useMemo(()=>{var ve;if(!y)return[];const ne=W.getAreaForAgent(y);if(!ne)return[];const Te=[];for(const $e of k.values())$e.type==="terminal"&&W.isPositionInArea($e.position,ne)&&Te.push({id:$e.id,name:$e.name,hasUrl:!!((ve=$e.terminalStatus)!=null&&ve.url)});return Te},[y,k,N]),E=x.useMemo(()=>{var ve;if(!y)return[];const ne=W.getAreaForAgent(y);if(!ne)return[];const Te=[];for(const $e of k.values())$e.type==="server"&&((ve=$e.pm2)!=null&&ve.enabled)&&W.isPositionInArea($e.position,ne)&&Te.push({id:$e.id,name:$e.name});return Te},[y,k,N]),D=x.useMemo(()=>{if(!y)return[];const ne=W.getAreaForAgent(y);if(!ne)return[];const Te=[];for(const ve of k.values())ve.type==="database"&&ve.database&&W.isPositionInArea(ve.position,ne)&&Te.push({id:ve.id,name:ve.name});return Te},[y,k,N]),{branches:_,fetchRemote:F,fetchingDirs:P}=h9(C),{terminalHeight:T,terminalRef:M,handleResizeStart:R}=l9(),{mobileOverviewHeight:O,handleResizeMouseDown:U,handleResizeTouchStart:H}=d9(),I=o9(),[$,z]=x.useState(()=>{const ne=Gb(dt.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,ne))}),q=x.useRef(null),Y=x.useCallback((ne,Te)=>{ne.preventDefault(),q.current={startX:ne.clientX,startW:$},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",W.setTerminalResizing(!0);let ve=$;const $e=jt=>{if(!q.current)return;const Ft=jt.clientX-q.current.startX,zt=Te==="left"?-Ft:Ft;ve=Math.max(280,Math.min(700,q.current.startW+zt)),z(ve)},ft=()=>{q.current=null,document.body.style.cursor="",document.body.style.userSelect="",W.setTerminalResizing(!1),document.removeEventListener("mousemove",$e),document.removeEventListener("mouseup",ft),Yb(dt.SIDE_PANEL_WIDTH,ve)};document.addEventListener("mousemove",$e),document.addEventListener("mouseup",ft)},[$]),B=x.useRef(null),G=x.useRef(null),[te,V]=x.useState(()=>{const ne=ka(dt.VIEW_MODE);return ne==="simple"||ne==="chat"||ne==="advanced"?ne:ka(dt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[ge,he]=x.useState(()=>hl(dt.TERMINAL_FULLSCREEN,!1)),[J,de]=x.useState(null),[je,xe]=x.useState(null),[qe,Ke]=x.useState(null),[We,Me]=x.useState(null),[ye,Fe]=x.useState(!1);Jt("guake-image-modal",J!==null,()=>de(null)),Jt("guake-bash-modal",je!==null,()=>xe(null)),Jt("guake-response-modal",We!==null,()=>Me(null)),Jt("guake-context-confirm",qe!==null,()=>Ke(null)),Jt("guake-agent-info",ye,()=>Fe(!1));const[Q,Re]=x.useState(!1),[pe,Ie]=x.useState(()=>ps.isEnabled()),[Ne,fe]=x.useState(()=>hl(dt.GIT_PANEL_OPEN,!1)),Ue=x.useCallback(ne=>{fe(ne),to(dt.GIT_PANEL_OPEN,ne)},[]),[rt,ct]=x.useState(()=>hl(dt.BUILDINGS_PANEL_OPEN,!1)),oe=x.useCallback(ne=>{ct(ne),to(dt.BUILDINGS_PANEL_OPEN,ne)},[]),[Z,ae]=x.useState(()=>hl(dt.WORKFLOW_PANEL_OPEN,!1)),be=x.useCallback(ne=>{ae(ne),to(dt.WORKFLOW_PANEL_OPEN,ne)},[]),[ee,ce]=x.useState(!1);x.useEffect(()=>{if(!y){ce(!1);return}let ne=!1;return(async()=>{try{const Te=await Lt(Et("/api/workflows/definitions"));if(ne||!Te.ok)return;const $e=(await Te.json()).some(ft=>ft.states.some(jt=>{var Ft,zt;return((Ft=jt.action)==null?void 0:Ft.type)==="agent_task"&&((zt=jt.action)==null?void 0:zt.agentId)===y}));ne||ce($e)}catch{ne||ce(!1)}})(),()=>{ne=!0}},[y]);const Ve=bL(),we=x.useCallback(ne=>W.setOverviewPanelOpen(ne),[]),[ie,X]=x.useState([]),[_e,me]=x.useState({}),[le,De]=x.useState(()=>wj()),[Qe,se]=x.useState(()=>{try{return localStorage.getItem("tide:bottom-split-direction")==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[Ee,He]=x.useState(()=>{try{const ne=localStorage.getItem("tide:bottom-terminal-height");return ne?Math.max(120,Math.min(600,Number(ne))):250}catch{return 250}}),Ye=x.useRef(null),[tt,at]=x.useState([1]),pt=x.useRef(null),Mt=x.useRef(null),[Ze,lt]=x.useState(null),[xt,Tt]=x.useState(null),en=x.useMemo(()=>ie.filter(ne=>ne.areaId===xt),[ie,xt]),Fn=x.useMemo(()=>new Set(en.map(ne=>ne.buildingId)),[en]),Tn=x.useRef(new Map);x.useEffect(()=>{try{const ne=localStorage.getItem("tide:bottom-panels-v2");if(ne){const Te=JSON.parse(ne);Tn.current=new Map(Te.map(([ve,$e])=>[ve,$e.map(ft=>({id:ft.id??gf(),type:ft.type,buildingId:ft.buildingId}))]))}else{const Te=localStorage.getItem("tide:bottom-terminals");if(Te){const ve=JSON.parse(Te);for(const[$e,ft]of ve)Tn.current.set($e,[{id:gf(),type:"terminal",buildingId:ft}])}}}catch{}},[]);const qn=x.useCallback(ne=>{if(!y)return;const Te=W.getAreaForAgent(y);if(Te)try{ne.length>0?Tn.current.set(Te.id,ne.map($e=>({id:$e.id,type:$e.type,buildingId:$e.buildingId}))):Tn.current.delete(Te.id);const ve=Array.from(Tn.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(ve))}catch{}},[y]),is=x.useCallback(()=>{if(!y)return null;const ne=W.getAreaForAgent(y);return(ne==null?void 0:ne.id)??null},[y]),pn=x.useCallback((ne,Te)=>{const ve=is();me({}),X($e=>{for(const zt of $e)zt.areaId===ve&&zt.type==="pm2-logs"&&W.stopLogStreaming(zt.buildingId);const ft=$e.filter(zt=>zt.areaId!==ve),jt={id:gf(),type:Te,buildingId:ne,areaId:ve??void 0},Ft=[...ft,jt];return qn([jt]),Ft})},[qn,is]),Dn=x.useCallback((ne,Te,ve)=>{const $e=is();se(ve);try{localStorage.setItem("tide:bottom-split-direction",ve)}catch{}X(ft=>{const jt=ft.filter(zn=>zn.areaId===$e);if(jt.length>=4||jt.some(zn=>zn.buildingId===ne))return ft;const Ft={id:gf(),type:Te,buildingId:ne,areaId:$e??void 0},zt=[...ft,Ft];return qn(jt.concat(Ft)),zt})},[qn,is]),it=x.useCallback(ne=>{me(Te=>{if(!(ne in Te))return Te;const ve={...Te};return delete ve[ne],ve}),X(Te=>{const ve=Te.find(jt=>jt.id===ne);(ve==null?void 0:ve.type)==="pm2-logs"&&W.stopLogStreaming(ve.buildingId);const $e=Te.filter(jt=>jt.id!==ne),ft=ve==null?void 0:ve.areaId;return ft&&qn($e.filter(jt=>jt.areaId===ft)),$e})},[qn]);x.useCallback(()=>{me({}),X(ne=>{for(const Te of ne)Te.type==="pm2-logs"&&W.stopLogStreaming(Te.buildingId);return qn([]),[]})},[qn]),x.useEffect(()=>{if(!y){Tt(null);return}const ne=W.getAreaForAgent(y);if(!ne){Tt(null);return}Tt(ne.id),X(Te=>{if(Te.filter(jt=>jt.areaId===ne.id).length>0)return Te;const $e=Tn.current.get(ne.id);if(!$e||$e.length===0)return Te;const ft=$e.map(jt=>({id:jt.id,type:jt.type,buildingId:jt.buildingId,areaId:ne.id}));return[...Te,...ft]})},[y]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&pn(ve.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",ne),()=>window.removeEventListener("tide:open-bottom-terminal",ne)},[pn]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&pn(ve.buildingId,"pm2-logs")};return window.addEventListener("tide:open-bottom-pm2-logs",ne),()=>window.removeEventListener("tide:open-bottom-pm2-logs",ne)},[pn]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&pn(ve.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",ne),()=>window.removeEventListener("tide:open-bottom-database",ne)},[pn]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&(ve!=null&&ve.type)&&(ve!=null&&ve.direction)&&(en.length===0?pn(ve.buildingId,ve.type):Dn(ve.buildingId,ve.type,ve.direction))};return window.addEventListener("tide:split-bottom-panel",ne),()=>window.removeEventListener("tide:split-bottom-panel",ne)},[en.length,pn,Dn]),x.useEffect(()=>{at(ne=>ne.length===en.length?ne:en.length<=1?[1]:(en.length>ne.length,Array(en.length).fill(1)))},[en.length]);const At=x.useCallback((ne,Te)=>{var zn;ne.preventDefault();const ve=Qe==="horizontal";pt.current={index:Te,startPos:ve?ne.clientX:ne.clientY,startRatios:[...tt]},document.body.style.cursor=ve?"col-resize":"row-resize",document.body.style.userSelect="none";const $e=(zn=Mt.current)==null?void 0:zn.querySelectorAll("iframe");$e==null||$e.forEach(On=>On.style.pointerEvents="none");const ft=Mt.current,jt=ft?ve?ft.offsetWidth:ft.offsetHeight:1,Ft=On=>{const Na=pt.current;if(!Na||!ft)return;const $l=(ve?On.clientX:On.clientY)-Na.startPos,Kr=Na.startRatios.reduce((Pp,Ip)=>Pp+Ip,0),_i=$l/jt*Kr,Ao=[...Na.startRatios],Fu=.1*Kr;Ao[Te]=Math.max(Fu,Na.startRatios[Te]+_i),Ao[Te+1]=Math.max(Fu,Na.startRatios[Te+1]-_i),at(Ao)},zt=()=>{pt.current=null,document.body.style.cursor="",document.body.style.userSelect="",$e==null||$e.forEach(On=>On.style.pointerEvents=""),document.removeEventListener("mousemove",Ft),document.removeEventListener("mouseup",zt)};document.addEventListener("mousemove",Ft),document.addEventListener("mouseup",zt)},[Qe,tt]),ln=x.useRef(new Set);x.useEffect(()=>{const ne=new Set(ie.filter(Te=>Te.type==="pm2-logs").map(Te=>Te.buildingId));for(const Te of ne)ln.current.has(Te)||W.startLogStreaming(Te,200);ln.current=ne},[ie]);const nn=x.useRef(new Set);x.useEffect(()=>{var ve;const ne=ie.filter($e=>$e.type==="terminal");for(const $e of ne){const ft=k.get($e.buildingId);!!((ve=ft==null?void 0:ft.terminalStatus)!=null&&ve.url)?nn.current.add($e.buildingId):nn.current.has($e.buildingId)&&(nn.current.delete($e.buildingId),it($e.id))}const Te=new Set(ne.map($e=>$e.buildingId));for(const $e of nn.current)Te.has($e)||nn.current.delete($e)},[ie,k,it]);const os=x.useCallback(ne=>{ne.preventDefault(),Ye.current={startY:ne.clientY,startH:Ee};let Te=Ee;const ve=ft=>{if(!Ye.current)return;const jt=Ye.current.startY-ft.clientY;Te=Math.max(120,Math.min(600,Ye.current.startH+jt)),He(Te)},$e=()=>{Ye.current=null,document.removeEventListener("mousemove",ve),document.removeEventListener("mouseup",$e);try{localStorage.setItem("tide:bottom-terminal-height",String(Te))}catch{}};document.addEventListener("mousemove",ve),document.addEventListener("mouseup",$e)},[Ee]),[ms,ts]=x.useState(!1),ia=x.useRef(0),Rt=a&&b!==null,gs=x.useRef([]),ns=x.useRef(-1),$s=x.useRef(!1),Hs=x.useRef(!1),_n=x.useRef(!1),Fa=x.useRef(null),[Ur,Aa]=x.useState(!1),[oa,Il]=x.useState(!1),_s=x.useCallback(()=>{const ne=gs.current,Te=ns.current;Aa(Te>0),Il(Te>=0&&Te<ne.length-1)},[]),lr=x.useCallback(ne=>{const Te=gs.current;if(Te.length===0)return;let ve=ns.current+ne;for(;ve>=0&&ve<Te.length;){const $e=Te[ve];if(t.has($e)){$s.current=!0,ns.current=ve,_s(),W.selectAgent($e);return}ve+=ne}},[t,_s]),cr=x.useCallback(()=>{lr(-1)},[lr]),Se=x.useCallback(()=>{lr(1)},[lr]),nt=x.useCallback((ne,Te)=>{if(typeof window>"u")return;const ve=window.history.state,ft={...typeof ve=="object"&&ve!==null?ve:{},__guakeAgentNav:{agentId:ne}};Te==="replace"?window.history.replaceState(ft,"",window.location.href):window.history.pushState(ft,"",window.location.href)},[]),yt=x.useCallback(()=>{he(ne=>{const Te=!ne;return to(dt.TERMINAL_FULLSCREEN,Te),Te})},[]),wt=f9({agents:t,selectedAgentId:y,isOpen:Rt,overviewPanelOpen:Ve,loadingHistory:((la=B.current)==null?void 0:la.historyLoader.fetchingHistory)??!1,hasModalOpen:!!(J||je||We||i||c),outputRef:((wo=B.current)==null?void 0:wo.outputScrollRef)??{current:null}});x.useEffect(()=>{const ne=M.current;if(!ne||!Rt)return;const Te=$e=>{$e.button===3?($e.preventDefault(),$e.stopPropagation(),cr()):$e.button===4&&($e.preventDefault(),$e.stopPropagation(),Se())},ve=$e=>{($e.button===3||$e.button===4)&&$e.preventDefault()};return ne.addEventListener("mouseup",Te),ne.addEventListener("mousedown",ve),()=>{ne.removeEventListener("mouseup",Te),ne.removeEventListener("mousedown",ve)}},[Rt,cr,Se]);const ss=x.useCallback(ne=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(ne)},[]),hn=typeof window<"u"&&window.innerWidth<=768&&Ve&&Rt,kt=JD({gestureRef:((ko=B.current)==null?void 0:ko.outputScrollRef)??{current:null},agentListRef:G,enabled:hn,onSelect:ss});x.useEffect(()=>{Q&&!pe&&(Ie(!0),ps.setEnabled(!0))},[Q,pe]),x.useEffect(()=>{Rt||Fe(!1)},[Rt]),x.useEffect(()=>{var Te;if(!(je!=null&&je.isLive)||!je.command)return;const ne=((Te=B.current)==null?void 0:Te.getDedupedHistory())??[];for(const ve of ne)if(ve._bashCommand===je.command&&ve._bashOutput){xe({command:je.command,output:ve._bashOutput,isLive:!1});return}},[je]);const wn=x.useCallback((ne,Te)=>{de({url:ne,name:Te})},[]),bs=x.useCallback((ne,Te)=>{const ve=fx(ne,b==null?void 0:b.cwd),$e=ve.line?{...Te||{},targetLine:ve.line}:Te;W.setFileViewerPath(ve.path,$e,b==null?void 0:b.cwd)},[b==null?void 0:b.cwd]),ls=x.useCallback((ne,Te)=>{xe({command:ne,output:Te,isLive:Te==="Running..."})},[]),Rn=x.useCallback(ne=>{Me(ne)},[]),ur=x.useCallback(()=>{Fe(ne=>!ne)},[]),[Ti,Wr]=x.useState(0),[za,xo]=x.useState(!1),Pu=x.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(xo(!0),Wr(NW),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{W.setMobileView("3d"),xo(!1),Wr(0)},TW))},[]),Vr=x.useCallback(ne=>{za||Wr(ne)},[za]);x.useEffect(()=>{Wr(0),xo(!1)},[y]),x.useEffect(()=>{if(!y){gs.current=[],ns.current=-1,_s(),_n.current=!1,Fa.current=null;return}const ne=gs.current;if($s.current){$s.current=!1,_s();return}const Te=ns.current;if(Te>=0&&ne[Te]===y){_s();return}const ve=Te<ne.length-1?ne.slice(0,Te+1):ne.slice();ve.push(y),ve.length>100&&ve.shift(),gs.current=ve,ns.current=ve.length-1,_s()},[y,_s]),x.useEffect(()=>{if(!(!Rt||!y)){if(!_n.current){nt(y,"replace"),_n.current=!0,Fa.current=y;return}if(Hs.current){Hs.current=!1,Fa.current=y;return}Fa.current!==y&&(nt(y,"push"),Fa.current=y)}},[Rt,y,nt]),x.useEffect(()=>{if(!Rt)return;const ne=Te=>{var jt,Ft;const ve=(Ft=(jt=Te.state)==null?void 0:jt.__guakeAgentNav)==null?void 0:Ft.agentId;if(!ve||typeof ve!="string"||!t.has(ve)||ve===h)return;Hs.current=!0,$s.current=!0;const $e=gs.current,ft=$e.lastIndexOf(ve);ft>=0?ns.current=ft:($e.push(ve),ns.current=$e.length-1),_s(),W.selectAgent(ve)};return window.addEventListener("popstate",ne),()=>window.removeEventListener("popstate",ne)},[Rt,t,h,_s]),x.useEffect(()=>{Rt&&h&&W.clearUnseenForAgent(h)},[Rt,h]),x.useEffect(()=>{const ne=Te=>{if(Te.key==="`"&&!Te.ctrlKey&&!Te.altKey&&b){const ve=Te.target;ve.tagName!=="INPUT"&&ve.tagName!=="TEXTAREA"&&(Te.preventDefault(),W.toggleTerminal())}};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[b]),x.useEffect(()=>{if(!Rt)return;const ne=Te=>{Te.altKey&&(Te.key!=="ArrowLeft"&&Te.key!=="ArrowRight"||(Te.key==="ArrowLeft"&&Ur?(Te.preventDefault(),cr()):Te.key==="ArrowRight"&&oa&&(Te.preventDefault(),Se())))};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[Rt,Ur,oa,cr,Se]),x.useEffect(()=>{const ne=Te=>{var ve;Te.key==="Escape"&&(i?(Te.stopImmediatePropagation(),W.clearFileViewerPath()):c?(Te.stopImmediatePropagation(),W.closeContextModal()):We?(Te.stopImmediatePropagation(),Me(null)):je?(Te.stopImmediatePropagation(),xe(null)):J?(Te.stopImmediatePropagation(),de(null)):(ve=B.current)!=null&&ve.search.searchMode&&(Te.stopImmediatePropagation(),B.current.search.closeSearch()))};return document.addEventListener("keydown",ne,!0),()=>document.removeEventListener("keydown",ne,!0)},[J,je,We,i,c]);const Iu=x.useRef(Rt),qr=x.useRef(!1);x.useEffect(()=>{Iu.current=Rt},[Rt]),x.useEffect(()=>{if(window.innerWidth<=768)return;const Te=ft=>{var On;if(!(ft instanceof Element))return!1;const jt=(On=M.current)==null?void 0:On.contains(ft),Ft=ft.closest(".agent-bar"),zt=ft.closest(".sidebar, .sidebar-collapse-edge-btn"),zn=!!ft.closest(".modal-overlay, .modal, .image-modal-overlay, .image-modal, .bash-modal-overlay, .bash-modal, .agent-info-modal-overlay, .agent-info-modal, .agent-response-modal, .pasted-text-modal-overlay, .pasted-text-modal, .file-viewer-overlay, .file-viewer-modal, .context-view-modal, .guake-context-confirm-overlay, .guake-context-confirm-modal, .pm2-logs-modal-overlay, .pm2-logs-modal, .database-panel-modal, .context-menu, .guake-git-diff-modal-overlay, .guake-git-delete-confirm, .theme-selector-dropdown");return!!jt||!!Ft||!!zt||zn},ve=ft=>{if(!Iu.current){qr.current=!1;return}if(YD("terminal")){qr.current=!1;return}qr.current=!Te(ft.target)},$e=ft=>{qr.current&&(Te(ft.target)||W.setTerminalOpen(!1),qr.current=!1)};return document.addEventListener("mousedown",ve,!0),document.addEventListener("mouseup",$e,!0),()=>{document.removeEventListener("mousedown",ve,!0),document.removeEventListener("mouseup",$e,!0)}},[]),x.useEffect(()=>{const ne=()=>{document.hidden&&I.cleanup()};return document.addEventListener("visibilitychange",ne),()=>document.removeEventListener("visibilitychange",ne)},[I]),x.useEffect(()=>()=>I.cleanup(),[y,I]);const yo=typeof window<"u"&&window.innerWidth<=768;if(!b)return yo&&r==="terminal"&&s.size===0?o.jsx("div",{ref:M,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${T}%`},children:o.jsx("div",{className:"guake-content",children:o.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:o.jsxs("div",{style:{textAlign:"center"},children:[o.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"👆"}),o.jsx("div",{style:{fontSize:"16px"},children:e("terminal:empty.tapAgent")}),o.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:e("terminal:empty.switchTo3D")})]})})})}):yo&&r==="terminal"&&s.size>0?o.jsx("div",{ref:M,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${T}%`},children:o.jsx("div",{className:"guake-content",children:o.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:o.jsxs("div",{className:"guake-empty loading",children:[e("terminal:empty.loadingTerminal"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]})})})}):null;if(!y)return null;const Bl=ne=>{ne.preventDefault(),ne.stopPropagation(),ia.current++,ne.dataTransfer.types.includes("Files")&&ts(!0)},Op=ne=>{ne.preventDefault(),ne.stopPropagation()},Lp=ne=>{ne.preventDefault(),ne.stopPropagation(),ia.current--,ia.current===0&&ts(!1)},vo=async ne=>{var ve,$e;ne.preventDefault(),ne.stopPropagation(),ia.current=0,ts(!1);const Te=ne.dataTransfer.files;if(Te.length)for(const ft of Te){const jt=await((ve=B.current)==null?void 0:ve.terminalInput.uploadFile(ft));jt&&(($e=B.current)==null||$e.terminalInput.setAttachedFiles(Ft=>[...Ft,jt]))}};return o.jsxs("div",{ref:M,className:`guake-terminal ${Rt?"open":"collapsed"} ${ge&&Rt?"fullscreen":""} ${Q&&Rt?"with-debug-panel":""} ${Ne&&Rt?"with-git-panel":""} ${rt&&Rt?"with-buildings-panel":""} ${Z&&Rt?"with-workflow-panel":""} ${v&&Rt?"with-tracking-board":""} ${Ve&&Rt?"with-overview-panel":""} ${ms?"drag-over":""} ${Ti>0?"mobile-swipe-close-active":""} ${za?"mobile-swipe-close-closing":""}`,style:{"--terminal-height":`${T}%`,"--mobile-swipe-close-offset":`${Ti}px`,"--guake-side-panel-width":`${$}px`,...O>0?{"--guake-mobile-overview-height":`${O}px`}:{}},onDragEnter:Bl,onDragOver:Op,onDragLeave:Lp,onDrop:vo,children:[o.jsxs("div",{className:"guake-drop-overlay",children:[o.jsx("div",{className:"drop-border"}),o.jsx("span",{className:"drop-icon",children:"📎"}),o.jsx("span",{className:"drop-label",children:e("terminal:input.dropToAttach")})]}),Q&&Rt&&y&&o.jsx(j6,{agentId:y,onClose:()=>Re(!1)}),Ne&&Rt&&y&&o.jsx(F6,{agentId:y,agents:t,onClose:()=>Ue(!1),branchInfoMap:_,fetchRemote:F,fetchingDirs:P}),rt&&Rt&&y&&o.jsx(pW,{agentId:y,onClose:()=>oe(!1)}),Z&&Rt&&y&&o.jsx(gW,{agentId:y,onClose:()=>be(!1)}),v&&Rt&&y&&o.jsxs("div",{className:"guake-tracking-board-panel",children:[o.jsxs("div",{className:"guake-tracking-board-header",children:[o.jsxs("div",{className:"guake-tracking-board-title",children:[o.jsx("span",{className:"guake-tracking-board-icon",children:"▥"}),o.jsx("span",{children:"Tracking Board"})]}),o.jsx("button",{type:"button",className:"guake-tracking-board-close",onClick:()=>W.setTrackingBoardVisible(!1),title:"Close tracking board",children:"✕"})]}),o.jsx("div",{className:"guake-tracking-board-body",children:o.jsx(Hj,{activeAgentId:y,onSelectAgent:S})})]}),(Q||Ne||rt||Z||v)&&Rt&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:ne=>Y(ne,"right")}),Ve&&Rt&&y&&o.jsx(s5,{activeAgentId:y,onClose:()=>we(!1),onSelectAgent:ne=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(ne)},agentListRef:G,twoFingerState:kt}),Ve&&Rt&&y&&o.jsx("div",{className:"guake-side-panel-resize left",onMouseDown:ne=>Y(ne,"left")}),Ve&&Rt&&y&&o.jsx("div",{className:"aop-resize-handle",onMouseDown:U,onTouchStart:H}),o.jsxs("div",{className:"guake-content",children:[o.jsx(O9,{selectedAgent:b,selectedAgentId:y,sortedAgents:wt.sortedAgents,swipeOffset:wt.swipeOffset,viewMode:te,setViewMode:V,searchMode:((dr=B.current)==null?void 0:dr.search.searchMode)??!1,toggleSearch:((fr=B.current)==null?void 0:fr.search.toggleSearch)??(()=>{}),closeSearch:((Fl=B.current)==null?void 0:Fl.search.closeSearch)??(()=>{}),debugPanelOpen:Q,setDebugPanelOpen:Re,debuggerEnabled:pe,setDebuggerEnabled:Ie,gitPanelOpen:Ne,setGitPanelOpen:Ue,buildingsPanelOpen:rt,setBuildingsPanelOpen:oe,workflowPanelOpen:Z,setWorkflowPanelOpen:be,hasWorkflow:ee,trackingBoardVisible:v,setTrackingBoardVisible:ne=>W.setTrackingBoardVisible(ne),overviewPanelOpen:Ve,setOverviewPanelOpen:we,agentInfoOpen:ye,onToggleAgentInfo:ur,isFullscreen:ge,onToggleFullscreen:yt,onNavigateBack:cr,onNavigateForward:Se,canNavigateBack:Ur,canNavigateForward:oa,outputsLength:((So=B.current)==null?void 0:So.outputsLength)??0,setContextConfirm:Ke,onClearContextDirect:()=>{var ne;W.clearContext(y),(ne=B.current)==null||ne.historyLoader.clearHistory()},headerRef:wt.headerRef}),o.jsxs("div",{className:`guake-swipe-container ${wt.swipeAnimationClass}`,style:wt.swipeOffset!==0?{transform:`translateX(${wt.swipeOffset*40}%)`}:void 0,children:[wt.sortedAgents.length>1&&wt.swipeOffset!==0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`swipe-indicator left ${wt.swipeOffset>.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-icon",children:"←"}),o.jsx("span",{className:"indicator-name",children:(zl=wt.nextAgent)==null?void 0:zl.name})]}),o.jsxs("div",{className:`swipe-indicator right ${wt.swipeOffset<-.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-name",children:(Gr=wt.prevAgent)==null?void 0:Gr.name}),o.jsx("span",{className:"indicator-icon",children:"→"})]})]}),wt.sortedAgents.length>1&&wt.sortedAgents.length<=8&&wt.swipeOffset!==0&&o.jsx("div",{className:`swipe-dots ${Math.abs(wt.swipeOffset)>.1?"visible":""}`,children:wt.sortedAgents.map((ne,Te)=>o.jsx("div",{className:`swipe-dot ${Te===wt.currentAgentIndex?"active":""}`},ne.id))}),o.jsx(dW,{activeAgentId:y,activeAgent:b,paneRef:B,viewMode:te,isOpen:Rt,onImageClick:wn,onFileClick:bs,onBashClick:ls,onViewMarkdown:Rn,keyboard:I,canSwipeClose:yo&&r==="terminal"&&!((ca=B.current)!=null&&ca.search.searchMode)&&!((Co=B.current)!=null&&Co.historyLoader.fetchingHistory),onSwipeCloseOffsetChange:Vr,onSwipeClose:Pu,hasModalOpen:!!(J||je||We||i)})]}),o.jsxs("div",{className:"guake-agent-status-bar",children:[(b==null?void 0:b.isDetached)&&o.jsx(Un,{content:o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",e("terminal:empty.reattachingSessionTitle")]}),o.jsxs("div",{className:"tide-tooltip__text",children:[e("terminal:empty.reattachingSessionDesc"),o.jsx("br",{}),o.jsx("br",{}),o.jsxs("strong",{children:[e("common:labels.status"),":"]})," ",e("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:o.jsxs("span",{className:"guake-detached-badge",title:e("terminal:empty.reattachingBadge"),children:[o.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",e("terminal:empty.reattaching")]})}),(b==null?void 0:b.cwd)&&o.jsxs("span",{className:"guake-agent-cwd",title:b.cwd,children:["📁 ",b.cwd.split("/").filter(Boolean).slice(-2).join("/")||b.cwd]}),C&&C.map(({areaId:ne,areaName:Te,dir:ve})=>{const $e=_.get(ve),ft=P.has(ve);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${Te}: ${ve}${$e?` (${$e.branch}${$e.ahead?` ↑${$e.ahead}`:""}${$e.behind?` ↓${$e.behind}`:""})`:""}`,onClick:()=>W.openFileExplorerForAreaFolder(ne,ve),children:["📂 ",ve.split("/").filter(Boolean).pop()||ve,$e&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",$e.branch]}),$e.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${$e.ahead} ahead`,children:["↑",$e.ahead]}),$e.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${$e.behind} behind`,children:["↓",$e.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${ft?"fetching":""}`,title:"Git fetch",onClick:jt=>{jt.stopPropagation(),F(ve)},children:ft?"⏳":"⇣"})]})]},`${ne}:${ve}`)}),b&&(()=>{const ne=b.contextStats,Te=!!ne,ve=ne?ne.totalTokens:b.contextUsed||0,$e=ne?ne.contextWindow:b.contextLimit||2e5,ft=ne?ne.usedPercent:Math.round(ve/$e*100),jt=Math.max(0,Math.min(100,ft)),Ft=Math.max(0,100-jt),zt=jt>=80?"#ff4a4a":jt>=60?"#ff9e4a":jt>=40?"#ffd700":"#4aff9e",zn=(ve/1e3).toFixed(1),On=($e/1e3).toFixed(1);return o.jsxs("span",{className:"guake-agent-context",onClick:()=>W.setContextModalAgentId(y),title:e(Te?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[o.jsx("span",{className:"context-icon",children:"📊"}),o.jsxs("span",{className:"context-label",children:[e("terminal:agentInfo.context"),":"]}),o.jsx("span",{className:"context-bar-mini",children:o.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,jt)}%`,backgroundColor:zt}})}),o.jsxs("span",{className:"context-tokens",style:{color:zt},children:[zn,"k/",On,"k"]}),o.jsxs("span",{className:"context-free",children:["(",e("terminal:context.percentFree",{percent:Ft}),")"]}),!Te&&o.jsx("span",{className:"context-warning",title:e("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),o.jsxs("span",{className:"guake-status-right",children:[A.length>0&&o.jsx("span",{className:"guake-status-terminals",children:A.map(ne=>{const Te=Fn.has(ne.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""} ${ne.hasUrl?"":"offline"}`,title:`${Te?"Hide":"Show"} terminal: ${ne.name}${ne.hasUrl?"":" (starting...)"}`,onClick:()=>{if(Te){const ve=ie.find($e=>$e.buildingId===ne.id);ve&&it(ve.id)}else ne.hasUrl||W.sendBuildingCommand(ne.id,"start"),pn(ne.id,"terminal")},onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),Fn.has(ne.id)||lt({position:{x:ve.clientX,y:ve.clientY},buildingId:ne.id,type:"terminal"})},children:"💻"},ne.id)})}),E.length>0&&o.jsx("span",{className:"guake-status-terminals",children:E.map(ne=>{const Te=Fn.has(ne.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} logs: ${ne.name}`,onClick:()=>{if(Te){const ve=ie.find($e=>$e.buildingId===ne.id);ve&&it(ve.id)}else pn(ne.id,"pm2-logs")},onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),Fn.has(ne.id)||lt({position:{x:ve.clientX,y:ve.clientY},buildingId:ne.id,type:"pm2-logs"})},children:"📜"},ne.id)})}),D.length>0&&o.jsx("span",{className:"guake-status-terminals",children:D.map(ne=>{const Te=Fn.has(ne.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} database: ${ne.name}`,onClick:()=>{if(Te){const ve=ie.find($e=>$e.buildingId===ne.id);ve&&it(ve.id)}else pn(ne.id,"database")},onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),Fn.has(ne.id)||lt({position:{x:ve.clientX,y:ve.clientY},buildingId:ne.id,type:"database"})},children:"🗄️"},ne.id)})}),o.jsx(kW,{})]})]}),(()=>{const ne=[];return Ze&&(ne.push({id:"open",label:"Open",icon:"⬇",onClick:()=>pn(Ze.buildingId,Ze.type)}),en.length>0&&(ne.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Dn(Ze.buildingId,Ze.type,"horizontal")}),ne.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Dn(Ze.buildingId,Ze.type,"vertical")}))),o.jsx(Ba,{children:o.jsx(co,{isOpen:Ze!==null,position:(Ze==null?void 0:Ze.position)||{x:0,y:0},worldPosition:{x:0,z:0},actions:ne,onClose:()=>lt(null)})})})(),en.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:os}),o.jsx("div",{ref:Mt,className:`guake-bottom-panels-container ${Qe}`,style:{height:Ee},onWheel:ne=>ne.stopPropagation(),children:en.map((ne,Te)=>{const ve=k.get(ne.buildingId);if(!ve)return null;const $e=tt[Te]??1,ft=(()=>{var jt;if(ne.type==="terminal")return(jt=ve.terminalStatus)!=null&&jt.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ve.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx(Hb,{terminalUrl:ve.terminalStatus.url,visible:!0})]},ne.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ve.name," (starting...)"]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx("div",{className:"guake-bottom-terminal-starting",children:o.jsx("span",{children:"Starting terminal..."})})]},ne.id);if(ne.type==="pm2-logs"){const Ft=_e[ne.id]||"";return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",ve.name]}),o.jsxs("div",{className:"guake-bottom-terminal-controls",children:[o.jsx("input",{type:"text",className:"guake-bottom-terminal-filter",value:Ft,onChange:zt=>{const zn=zt.target.value;me(On=>{if(!zn.trim()){if(!(ne.id in On))return On;const Na={...On};return delete Na[ne.id],Na}return{...On,[ne.id]:zn}})},placeholder:"Filter logs","aria-label":`Filter logs for ${ve.name}`,spellCheck:!1}),o.jsx("select",{className:"guake-bottom-terminal-retention",value:le===null?"unlimited":String(le),onChange:zt=>{const zn=zt.target.value==="unlimited"?null:Number(zt.target.value);De(zn),TO(zn)},"aria-label":`Max log retention for ${ve.name}`,children:NO.map(zt=>o.jsx("option",{value:zt===null?"unlimited":String(zt),children:zt===null?"Unlimited":`${zt.toLocaleString()} lines`},zt===null?"unlimited":zt))}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>W.clearStreamingLogs(ne.buildingId),title:"Clear logs",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"})})}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>W.sendBuildingCommand(ne.buildingId,"restart"),title:"Restart",children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M1 4v6h6"}),o.jsx("path",{d:"M3.51 15a9 9 0 105.64-11.36L3 10"})]})}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),o.jsx(MW,{buildingId:ne.buildingId,filterText:Ft,maxRetention:le})]},ne.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",ve.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx(i9,{building:ve})]},ne.id)})();return Te>0?o.jsxs(Ce.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${Qe}`,onMouseDown:jt=>At(jt,Te-1)}),ft]},ne.id):ft})})]}),ie.filter(ne=>ne.areaId!==xt&&ne.type==="terminal").map(ne=>{var ve;const Te=k.get(ne.buildingId);return(ve=Te==null?void 0:Te.terminalStatus)!=null&&ve.url?o.jsx(Hb,{terminalUrl:Te.terminalStatus.url,visible:!1},ne.id):null})]}),Rt&&!ge&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:R,title:e("common:rightPanel.dragToResize")}),!(Rt&&ge)&&o.jsxs("div",{className:"guake-handle",onClick:()=>{Rt&&W.toggleTerminal()},onDoubleClick:()=>{Rt||W.toggleTerminal()},style:{top:Rt?`min(${T}%, calc(100vh - 72px))`:"0"},children:[o.jsx("span",{className:"guake-handle-icon",children:Rt?"▲":"▼"}),o.jsx("span",{className:"guake-handle-text",children:b.name})]}),J&&o.jsx(x6,{url:J.url,name:J.name,onClose:()=>de(null)}),je&&o.jsx(y6,{state:je,onClose:()=>xe(null)}),qe&&o.jsx(v6,{action:qe,selectedAgentId:y,subordinateCount:((Yr=b==null?void 0:b.subordinateIds)==null?void 0:Yr.length)||0,onClose:()=>Ke(null),onClearHistory:((ja=B.current)==null?void 0:ja.historyLoader.clearHistory)??(()=>{})}),o.jsx(w6,{}),o.jsx(k6,{}),o.jsx(A6,{agent:b,isOpen:ye,onClose:()=>Fe(!1)}),o.jsx(S6,{agent:b,content:We,onClose:()=>Me(null)})]})});function RW(n){return n.trim().replace(/^v/i,"")}function CA(n){const t=RW(n).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!t)return null;const s=t[1].split(".").map(r=>Number.parseInt(r,10));if(s.some(Number.isNaN))return null;const a=t[2]?t[2].split("."):[];return{core:s,prerelease:a}}function OW(n,e){if(n.length===0&&e.length===0)return 0;if(n.length===0)return 1;if(e.length===0)return-1;const t=Math.max(n.length,e.length);for(let s=0;s<t;s+=1){const a=n[s],r=e[s];if(a===void 0)return-1;if(r===void 0)return 1;const i=/^\d+$/.test(a)?Number.parseInt(a,10):null,c=/^\d+$/.test(r)?Number.parseInt(r,10):null;if(i!==null&&c!==null){if(i>c)return 1;if(i<c)return-1;continue}if(i!==null)return-1;if(c!==null)return 1;const d=a.localeCompare(r);if(d!==0)return d>0?1:-1}return 0}function LW(n,e){const t=CA(n),s=CA(e);if(!t||!s)return null;const a=Math.max(t.core.length,s.core.length);for(let r=0;r<a;r+=1){const i=t.core[r]??0,c=s.core[r]??0;if(i>c)return 1;if(i<c)return-1}return OW(t.prerelease,s.prerelease)}function PW(n,e){const t=LW(n,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function IW(n,e={}){const{timeoutMs:t=5e3,fetchImpl:s=fetch}=e;try{const a=new AbortController,r=setTimeout(()=>a.abort(),t),i=Date.now(),c=await s(`https://registry.npmjs.org/${encodeURIComponent(n)}/latest?t=${i}`,{signal:a.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!c.ok)return null;const d=await c.json();return typeof d.version=="string"?d.version:null}catch{return null}}async function BW(n,e,t={}){const s=await IW(n,t);return s?{currentVersion:e,latestVersion:s,relation:PW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const FW="tide-commander",Yg="1.52.0";function zW(){const[n,e]=x.useState({currentVersion:Yg,latestVersion:null,relation:"unknown",isChecking:!1}),t=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await BW(FW,Yg);e({currentVersion:Yg,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return x.useEffect(()=>{t()},[t]),{...n,refresh:t}}const $W=x.memo(function({agent:e,currentIndex:t,agentIndex:s,isTouchInput:a,isTouchDragEnabled:r,isSelected:i,hasUnseenOutput:c,isDragging:d,isDragOver:f,customClasses:h,onDragStart:m,onDragEnd:b,onDragOver:y,onDragEnter:v,onDragLeave:S,onDrop:N,onAgentClick:k,onAgentDoubleClick:C,onTouchStart:A,onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onHoverEnter:F,onHoverLeave:P,onItemRef:T}){const M=!a||r,R=x.useCallback(O=>{T(e.id,O)},[e.id,T]);return o.jsxs("div",{ref:R,className:`agent-bar-item ${i?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${d?"dragging":""} ${f?"drag-over":""} ${r?"touch-drag-enabled":""}`,draggable:M,onDragStart:O=>m(O,e),onDragEnd:b,onDragOver:O=>y(O,s),onDragEnter:O=>v(O,s),onDragLeave:S,onDrop:O=>N(O,s),onTouchStart:O=>A(O,e.id),onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onClick:O=>k(e,O),onDoubleClick:()=>C(e),onMouseEnter:()=>F(e),onMouseLeave:P,title:a?`${e.name} (${t+1}) - Long press to reorder`:`${e.name} (${t+1}) - Drag to reorder within group`,children:[o.jsxs("div",{className:"agent-bar-avatar",children:[o.jsx(Nn,{classId:e.class,size:"100%",className:"agent-bar-icon"}),o.jsx("span",{className:"agent-bar-status",style:{backgroundColor:qb(e.status)}}),c&&o.jsx("span",{className:"agent-bar-notification-badge",title:"New output available - click to view"}),e.status==="idle"&&e.lastActivity>0&&o.jsx("span",{className:"agent-bar-idle-clock",style:{color:Vb(e.lastActivity)},title:fp(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${t+1}`,children:["^",t+1]})]})}),HW=x.memo(function({onFocusAgent:e,onSpawnClick:t,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=ut(["common"]),c=Rl(),d=Pa(),f=rx(),h=$O(),m=Aj(),b=Br(),y=Ia(),v=ux(),[S]=tx(),[N,k]=x.useState(!1);oj("AgentBar");const C=x.useRef(null),A=x.useRef(null),E=x.useRef(null),D=x.useRef(new Map);x.useEffect(()=>{{k(!1);return}},[b.experimental2DView]),x.useEffect(()=>{const le=A.current;if(!le)return;const De=Qe=>{le.scrollWidth<=le.clientWidth||(Qe.preventDefault(),Math.abs(Qe.deltaX)>Math.abs(Qe.deltaY)?le.scrollLeft+=Qe.deltaX:le.scrollLeft+=Qe.deltaY)};return le.addEventListener("wheel",De,{passive:!1}),()=>le.removeEventListener("wheel",De)},[]);const[_,F]=x.useState(null),[P,T]=x.useState(new Map),[M,R]=x.useState(null),[O,U]=x.useState(null),H=x.useRef(0),[I,$]=x.useState(null),z=x.useRef(null),q=x.useRef(null),Y=x.useRef(null),B=x.useRef(null),G=350,te=8,V=x.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),ge=x.useMemo(()=>Array.from(c.values()).filter(le=>{if(W.isAgentInArchivedArea(le.id))return!1;if(S){const De=W.getAreaForAgent(le.id);if(!hp((De==null?void 0:De.id)??null))return!1}return!0}).sort((le,De)=>(le.createdAt||0)-(De.createdAt||0)),[c,d,S]),{orderedAgents:he,moveAgent:J}=fO(ge),de=he,je=x.useMemo(()=>{const le=new Map;for(const De of de)le.set(De.id,W.getAreaForAgent(De.id));return le},[de,d]),xe=x.useMemo(()=>{const le=new Map;for(const Qe of de){const se=je.get(Qe.id)||null,Ee=(se==null?void 0:se.id)||null;le.has(Ee)||le.set(Ee,{area:se,agents:[]}),le.get(Ee).agents.push(Qe)}const De=Array.from(le.values());return De.sort((Qe,se)=>{var Ee,He;return!Qe.area&&se.area?1:Qe.area&&!se.area?-1:!Qe.area&&!se.area?0:(((Ee=Qe.area)==null?void 0:Ee.name)||"").localeCompare(((He=se.area)==null?void 0:He.name)||"")}),De},[de,je]),qe=x.useRef(e);qe.current=e;const Ke=x.useRef(M);Ke.current=M;const We=x.useRef(de);We.current=de;const Me=x.useRef(je);Me.current=je;const ye=x.useRef(J);ye.current=J,x.useEffect(()=>{const le=new Map(P);let De=!1;for(const Qe of de){const se=P.get(Qe.id);Qe.currentTool?(!se||se.tool!==Qe.currentTool)&&(le.set(Qe.id,{tool:Qe.currentTool,key:Date.now()}),De=!0):se&&setTimeout(()=>{T(Ee=>{const He=new Map(Ee);return He.delete(Qe.id),He})},1500)}De&&T(le)},[de.map(le=>le.currentTool).join(",")]),x.useEffect(()=>{const le=h;if(!le)return;const De=D.current.get(le),Qe=A.current;De&&Qe&&requestAnimationFrame(()=>{const se=De.getBoundingClientRect(),Ee=Qe.getBoundingClientRect(),Ye=se.left-Ee.left+Qe.scrollLeft+se.width/2,tt=Qe.clientWidth;Qe.scrollTo({left:Ye-tt/2,behavior:"smooth"})})},[h]);const Fe=x.useCallback((le,De)=>{if(Y.current===le.id){Y.current=null,De.preventDefault(),De.stopPropagation();return}W.setLastSelectionViaDirectClick(!0),De.shiftKey?W.addToSelection(le.id):W.selectAgent(le.id),W.setTerminalOpen(!0)},[]),Q=x.useCallback(le=>{var De;(De=qe.current)==null||De.call(qe,le.id),W.setTerminalOpen(!0)},[]),Re=x.useCallback(()=>F(null),[]),pe=x.useCallback((le,De)=>{De?D.current.set(le,De):D.current.delete(le)},[]),Ie=x.useCallback((le,De)=>{R(De),$(De.id),le.dataTransfer.effectAllowed="move",le.dataTransfer.setData("text/plain",De.id),requestAnimationFrame(()=>{le.target.classList.add("dragging")})},[]),Ne=x.useCallback(le=>{R(null),U(null),$(null),H.current=0,le.target.classList.remove("dragging")},[]),fe=x.useCallback((le,De)=>{le.preventDefault();const Qe=Ke.current;if(Qe){const se=Me.current.get(Qe.id),Ee=We.current[De],He=Ee?Me.current.get(Ee.id):null,Ye=(se==null?void 0:se.id)??null,tt=(He==null?void 0:He.id)??null;le.dataTransfer.dropEffect=Ye===tt?"move":"none"}else le.dataTransfer.dropEffect="move"},[]),Ue=x.useCallback((le,De)=>{le.preventDefault(),H.current++;const Qe=Ke.current;if(Qe){const se=Me.current.get(Qe.id),Ee=We.current[De],He=Ee?Me.current.get(Ee.id):null,Ye=(se==null?void 0:se.id)??null,tt=(He==null?void 0:He.id)??null;U(Ye===tt?De:null)}else U(De)},[]),rt=x.useCallback(le=>{H.current--,H.current===0&&U(null)},[]),ct=x.useCallback((le,De)=>{le.preventDefault();const Qe=Ke.current;if(!Qe)return;const se=We.current,Ee=Me.current,He=se.findIndex(Ye=>Ye.id===Qe.id);if(He!==-1&&He!==De){const Ye=Ee.get(Qe.id),tt=se[De],at=tt?Ee.get(tt.id):null,pt=(Ye==null?void 0:Ye.id)??null,Mt=(at==null?void 0:at.id)??null;pt===Mt&&ye.current(He,De)}R(null),U(null),$(null),H.current=0},[]),oe=x.useCallback(()=>{z.current&&(clearTimeout(z.current),z.current=null)},[]),Z=x.useCallback(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),ae=x.useCallback((le,De)=>{if(!V||le.touches.length!==1)return;oe(),Z(),$(null);const Qe=le.touches[0];q.current={agentId:De,x:Qe.clientX,y:Qe.clientY},z.current=setTimeout(()=>{$(De),Y.current=De,z.current=null},G)},[oe,Z,V]),be=x.useCallback(le=>{if(!V||le.touches.length!==1)return;const De=q.current;if(!De||!z.current)return;const Qe=le.touches[0],se=Qe.clientX-De.x,Ee=Qe.clientY-De.y;Math.sqrt(se*se+Ee*Ee)>te&&(oe(),q.current=null)},[oe,V]),ee=x.useCallback(()=>{oe(),q.current=null,Ke.current||$(null),Z(),B.current=setTimeout(()=>{Y.current=null,B.current=null},450)},[oe,Z]);x.useEffect(()=>()=>{oe(),Z()},[oe,Z]);const ce=le=>{const De=`common:status.${le}`;return i(De,{defaultValue:i("common:status.unknown")})},{currentVersion:Ve,latestVersion:we,relation:ie,isChecking:X}=zW(),_e=Ve;let me=0;return o.jsxs("div",{className:"agent-bar",ref:C,children:[o.jsxs("div",{className:"agent-bar-scroll",ref:A,children:[o.jsxs("div",{className:"agent-bar-version",title:we?`Tide Commander v${_e} (npm: v${we})`:`Tide Commander v${_e}`,children:[o.jsxs("span",{children:["v",_e]}),ie==="behind"&&we?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${we}`,children:["npm v",we]}):ie==="ahead"&&we?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${we}`,children:["npm v",we]}):null,ie==="behind"?o.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status agent-bar-version-status-behind",title:i("common:agentBar.behindNpmTooltip",{defaultValue:"Current version is behind npm latest"}),children:i("common:agentBar.behindNpm",{defaultValue:"(behind npm)"})}):ie==="ahead"?o.jsx("span",{className:"agent-bar-version-status agent-bar-version-status-ahead",title:i("common:agentBar.aheadNpmTooltip",{defaultValue:"Current version is newer than npm latest"}),children:i("common:agentBar.aheadNpm",{defaultValue:"(ahead of npm)"})}):ie==="equal"?o.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status",children:i("common:agentBar.updated")}):X?o.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.checkingNpm",{defaultValue:"(checking npm)"})}):o.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.unknownNpm",{defaultValue:"(npm unknown)"})}),N&&o.jsx(Un,{content:"Refresh 3D Scene (HMR changes pending)",position:"bottom",children:o.jsx("button",{className:"agent-bar-hmr-refresh",onClick:xj,children:"↻"})})]}),o.jsxs("div",{className:"agent-bar-list",ref:E,children:[o.jsx(Un,{content:i("common:agentBar.spawnNewAgent"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn",onClick:t,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"+"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newAgent")})]})}),o.jsx(Un,{content:i("common:agentBar.spawnBoss"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-boss-btn",onClick:s,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"👑"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBoss")})]})}),o.jsx(Un,{content:i("common:agentBar.addNewBuilding"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-building-btn",onClick:a,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"🏢"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBuilding")})]})}),o.jsx(Un,{content:i("common:agentBar.drawNewArea"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-area-btn",onClick:r,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"🔲"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newArea")})]})}),xe.map(le=>{var se,Ee,He,Ye,tt;const De=le.agents,Qe=!le.area;return o.jsxs("div",{className:`agent-bar-group ${Qe?"unassigned":""}`,style:{borderColor:((se=le.area)==null?void 0:se.color)||void 0,background:le.area?`${le.area.color}15`:void 0},children:[o.jsx("div",{className:"agent-bar-area-label",children:o.jsx("span",{className:"agent-bar-area-name",style:{color:((Ee=le.area)==null?void 0:Ee.color)||"#888"},children:((He=le.area)==null?void 0:He.name)||i("common:agentBar.unassigned")})}),((Ye=le.area)==null?void 0:Ye.directories)&&le.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:le.area.directories.map((at,pt)=>o.jsxs("div",{className:"agent-bar-folder-item",onClick:Mt=>{Mt.stopPropagation(),W.openFileExplorer(at)},children:[o.jsx("span",{className:"agent-bar-folder-icon",children:"📁"}),o.jsxs("div",{className:"agent-bar-folder-tooltip",children:[o.jsx("div",{className:"agent-bar-folder-tooltip-path",children:at}),o.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},pt))}),De.map(at=>{const pt=me++,Mt=de.findIndex(Ze=>Ze.id===at.id);return o.jsx($W,{agent:at,currentIndex:pt,agentIndex:Mt,isTouchInput:V,isTouchDragEnabled:I===at.id,isSelected:f.has(at.id),hasUnseenOutput:v.has(at.id),isDragging:(M==null?void 0:M.id)===at.id,isDragOver:O===Mt,customClasses:y,onDragStart:Ie,onDragEnd:Ne,onDragOver:fe,onDragEnter:Ue,onDragLeave:rt,onDrop:ct,onAgentClick:Fe,onAgentDoubleClick:Q,onTouchStart:ae,onTouchMove:be,onTouchEnd:ee,onTouchCancel:ee,onHoverEnter:F,onHoverLeave:Re,onItemRef:pe},at.id)})]},((tt=le.area)==null?void 0:tt.id)||"unassigned")})]})]}),Array.from(P.entries()).map(([le,De])=>{const Qe=D.current.get(le);if(!Qe)return null;const se=Qe.getBoundingClientRect(),Ee=rs[De.tool]||rs.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:De.tool,style:{position:"fixed",left:se.left+se.width/2,bottom:window.innerHeight-se.top+8},children:[o.jsx("span",{className:"agent-bar-tool-icon",children:Ee}),o.jsx("span",{className:"agent-bar-tool-name",children:De.tool})]},`tool-${le}-${De.key}`)}),_&&(()=>{const le=W.getAreaForAgent(_.id),De=m.get(_.id),Qe=Fr(_.class,y),se=Date.now()-(_.createdAt||Date.now()),Ee=Math.floor(se/6e4),He=Math.floor(Ee/60),Ye=He>0?`${He}h ${Ee%60}m`:`${Ee}m`,tt=Ze=>Ze>=1e6?`${(Ze/1e6).toFixed(1)}M`:Ze>=1e3?`${(Ze/1e3).toFixed(1)}K`:Ze.toString(),at=_.contextLimit>0?Math.round(_.contextUsed/_.contextLimit*100):0,pt=D.current.get(_.id),Mt={};if(pt){const Ze=pt.getBoundingClientRect();Mt.position="fixed",Mt.left=Ze.left+Ze.width/2,Mt.bottom=window.innerHeight-Ze.top+12}return o.jsxs("div",{className:"agent-bar-tooltip",style:Mt,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:o.jsx(Nn,{classId:_.class,size:18})}),o.jsxs("span",{className:"agent-bar-tooltip-name",children:[o.jsx("img",{src:_.provider==="codex"?"/assets/codex.png":_.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:_.provider,className:"agent-bar-provider-icon",title:_.provider==="codex"?"Codex Agent":_.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),_.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:qb(_.status)},children:ce(_.status)})]}),o.jsxs("div",{className:"agent-bar-tooltip-info",children:[o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.class"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.class," — ",Qe.description]})]}),le&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.area"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:le.color},children:le.name})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.directory"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:_.cwd})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.uptime"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",children:Ye})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.tokens"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[tt(_.tokensUsed)," ",i("common:agentPopup.used")]})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.context"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:at>80?"#ff4a4a":at>60?"#ff9e4a":void 0},children:[tt(_.contextUsed)," / ",tt(_.contextLimit)," (",at,"%)"]})]}),_.currentTool&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.tool"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[rs[_.currentTool]||rs.default," ",_.currentTool]})]}),_.taskLabel&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsx("span",{className:"agent-bar-tooltip-label",children:"📋 Task:"}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:_.taskLabel})]}),_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.task"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.currentTask.substring(0,150),_.currentTask.length>150?"...":""]})]}),_.lastAssignedTask&&!_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.assignedTask"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[_.lastAssignedTask.substring(0,200),_.lastAssignedTask.length>200?"...":""]})]}),De&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.lastQuery"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[De.text.substring(0,300),De.text.length>300?"...":""]})]})]})]})})()]})});function UW({activeTool:n,onExit:e}){const{t}=ut(["notifications","terminal"]);if(!n||n==="select")return null;const s=t(n==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=n==="rectangle"?"▭":"○";return o.jsxs("div",{className:"drawing-mode-indicator",children:[o.jsxs("div",{className:"drawing-mode-content",children:[o.jsx("span",{className:"drawing-mode-icon",children:a}),o.jsxs("div",{className:"drawing-mode-text",children:[o.jsxs("span",{className:"drawing-mode-title",children:[t("terminal:drawingMode.drawingArea"),": ",s]}),o.jsxs("span",{className:"drawing-mode-hint",children:[t("terminal:drawingMode.clickAndDrag")," • ",t("terminal:drawingMode.pressEscape")]})]})]}),o.jsx("button",{className:"drawing-mode-exit",onClick:e,title:t("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const WW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Kg=n=>n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}K`:n.toString(),VW=x.memo(function({agent:e,screenPos:t,onClose:s}){const{t:a}=ut(["common"]),r=Ia(),i=W.getAreaForAgent(e.id),c=W.getState().lastPrompts.get(e.id),d=Fr(e.class,r),f=Date.now()-(e.createdAt||Date.now()),h=Math.floor(f/6e4),m=Math.floor(h/60),b=m>0?`${m}h ${h%60}m`:`${h}m`,y=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,v=x.useMemo(()=>{let k=t.x-150,C=t.y-320-10;return typeof window<"u"&&(k<10?k=10:k+300>window.innerWidth-10&&(k=window.innerWidth-300-10),C<10&&(C=t.y+10)),{position:"fixed",left:k,top:C,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[t.x,t.y]);return o.jsxs("div",{className:"agent-hover-popup",style:v,onMouseLeave:s,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:o.jsx(Nn,{agent:e,size:18})}),o.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:qb(e.status)},children:a(WW[e.status]||"common:status.unknown")})]}),o.jsxs("div",{className:"agent-bar-tooltip-info",children:[o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.class"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.class," — ",d.description]})]}),i&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.area"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:i.color},children:i.name})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.directory"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:e.cwd})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.uptime"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",children:b})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.tokens"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[Kg(e.tokensUsed)," ",a("common:agentPopup.used")]})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.context"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:y>80?"#ff4a4a":y>60?"#ff9e4a":void 0},children:[Kg(e.contextUsed)," / ",Kg(e.contextLimit)," (",y,"%)"]})]}),e.currentTool&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.tool"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[rs[e.currentTool]||rs.default," ",e.currentTool]})]}),e.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.task"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.currentTask.substring(0,150),e.currentTask.length>150?"...":""]})]}),e.lastAssignedTask&&!e.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.assignedTask"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[e.lastAssignedTask.substring(0,200),e.lastAssignedTask.length>200?"...":""]})]}),c&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.lastQuery"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[c.text.substring(0,300),c.text.length>300?"...":""]})]})]})]})});function AA(n){if(n===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,s)).toFixed(1))+" "+t[s]}function jA(n){const t=Date.now()-n,s=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const NA={30:"#1a1a1a",31:"#e74c3c",32:"#2ecc71",33:"#f39c12",34:"#3498db",35:"#9b59b6",36:"#00bcd4",37:"#ecf0f1",90:"#7f8c8d",91:"#ff6b6b",92:"#4ade80",93:"#fbbf24",94:"#60a5fa",95:"#c084fc",96:"#22d3ee",97:"#ffffff"};function qW(n){const e=[],t=/\x1B\[([0-9;]*)m/g;let s=0,a=null,r;for(;(r=t.exec(n))!==null;){if(r.index>s){const c=n.slice(s,r.index);a?e.push(o.jsx("span",{style:{color:a},children:c},e.length)):e.push(c)}const i=r[1].split(";").map(Number);for(const c of i)c===0||c===39?a=null:NA[c]&&(a=NA[c]);s=t.lastIndex}if(s<n.length){const i=n.slice(s);a?e.push(o.jsx("span",{style:{color:a},children:i},e.length)):e.push(i)}return e.length>0?e:[n]}const GW=x.memo(function({building:e,screenPos:t,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var $,z,q,Y,B,G,te,V,ge,he,J,de,je,xe,qe,Ke,We,Me,ye,Fe;const{t:c}=ut(["terminal","common"]),[d,f]=x.useState(!1),[h,m]=x.useState(null),[b,y]=x.useState(!1),v=x.useRef(null),S=x.useRef(h);S.current=h;const{buildingLogs:N}=Fs(),k=W.getBuildingLogs(e.id),C=($=e.pm2)==null?void 0:$.enabled,A=(z=e.docker)==null?void 0:z.enabled,E=x.useRef(null),D=x.useRef(null),_=x.useCallback(Q=>{Q.preventDefault();const Re=S.current?S.current.x:0,pe=S.current?S.current.y:0;v.current={mouseX:Q.clientX,mouseY:Q.clientY,popupX:Re,popupY:pe},y(!0),E.current=Ie=>{if(!v.current)return;const Ne=Ie.clientX-v.current.mouseX,fe=Ie.clientY-v.current.mouseY;m({x:v.current.popupX+Ne,y:v.current.popupY+fe})},D.current=()=>{y(!1),v.current=null,E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",E.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const F=Q=>{if(Q==="logs"){if((C||A)&&r){r();return}W.sendBuildingCommand(e.id,Q),f(!0)}else W.sendBuildingCommand(e.id,Q)},P=(Q,Re)=>{if(Q){const pe=`http://localhost:${Q}`;Re&&i?i(pe):window.open(pe,"_blank")}},T=((q=e.pm2Status)==null?void 0:q.ports)||[],M=((B=(Y=e.dockerStatus)==null?void 0:Y.ports)==null?void 0:B.map(Q=>Q.host))||[],R=C?T:A?M:[],O=C?!!((G=e.pm2)!=null&&G.script):A?!!((te=e.docker)!=null&&te.image)||((V=e.docker)==null?void 0:V.mode)==="compose"||((ge=e.docker)==null?void 0:ge.mode)==="existing":!!((he=e.commands)!=null&&he.start),U=C?!!((J=e.pm2)!=null&&J.script):A?!0:!!((de=e.commands)!=null&&de.stop),H=C?!!((je=e.pm2)!=null&&je.script):A?!0:!!((xe=e.commands)!=null&&xe.restart),I=x.useMemo(()=>{const Re=d?400:250;let pe=t.x+20,Ie=t.y-80;return typeof window<"u"&&!h&&(t.x+20+280>window.innerWidth&&(pe=t.x-280-20),t.y-80<0?Ie=10:t.y-80+Re>window.innerHeight&&(Ie=window.innerHeight-Re-10)),{position:"fixed",left:pe+((h==null?void 0:h.x)||0),top:Ie+((h==null?void 0:h.y)||0),zIndex:1e3,cursor:b?"grabbing":void 0}},[t.x,t.y,d,h,b]);return o.jsxs("div",{className:"building-action-popup",style:I,onClick:Q=>Q.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header ${b?"dragging":""}`,onMouseDown:_,children:[o.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&o.jsx("span",{className:"building-popup-ports",children:R.map(Q=>o.jsxs("a",{href:`http://localhost:${Q}`,className:"building-popup-port-link",onClick:Re=>{Re.preventDefault(),Re.stopPropagation(),P(Q,Re.altKey)},onMouseDown:Re=>Re.stopPropagation(),title:`Open http://localhost:${Q} (Alt+Click for modal)`,children:[":",Q]},Q))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:ob[e.status]},children:e.status}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),C&&e.pm2Status&&o.jsxs("div",{className:"building-popup-metrics",children:[o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"PID"}),o.jsx("span",{className:"value",children:e.pm2Status.pid||"-"})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"CPU"}),o.jsxs("span",{className:"value",children:[((qe=e.pm2Status.cpu)==null?void 0:qe.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:AA(e.pm2Status.memory||0)})]}),e.pm2Status.restarts!==void 0&&e.pm2Status.restarts>0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"RST"}),o.jsx("span",{className:"value",children:e.pm2Status.restarts})]}),e.pm2Status.uptime&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"UP"}),o.jsx("span",{className:"value",children:jA(e.pm2Status.uptime)})]})]}),A&&e.dockerStatus&&o.jsxs("div",{className:"building-popup-metrics",children:[o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"ID"}),o.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"CPU"}),o.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:AA(e.dockerStatus.memory)})]}),e.dockerStatus.health&&e.dockerStatus.health!=="none"&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"HEALTH"}),o.jsx("span",{className:"value",style:{color:e.dockerStatus.health==="healthy"?"#4ade80":e.dockerStatus.health==="unhealthy"?"#f87171":"#fbbf24"},children:e.dockerStatus.health==="healthy"?"✓":e.dockerStatus.health==="unhealthy"?"✗":"..."})]}),e.dockerStatus.startedAt&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"UP"}),o.jsx("span",{className:"value",children:jA(e.dockerStatus.startedAt)})]})]}),A&&((Ke=e.dockerStatus)==null?void 0:Ke.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Q,Re)=>o.jsxs("span",{className:"service-item",title:`${Q.name}: ${Q.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:Q.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:Q.name})]},Re))}),(e.lastError||C&&((We=e.pm2Status)==null?void 0:We.status)==="errored"||A&&((Me=e.dockerStatus)==null?void 0:Me.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),C&&((ye=e.pm2Status)==null?void 0:ye.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),A&&((Fe=e.dockerStatus)==null?void 0:Fe.health)==="unhealthy"&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.healthCheckFailing")]})]}),o.jsxs("div",{className:"building-popup-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>F("start"),disabled:!O||e.status==="running"||e.status==="starting",title:c(O?"terminal:buildingAction.start":"terminal:buildingAction.noStartCommand"),children:[o.jsx("span",{className:"icon",children:"▶"}),c("terminal:buildingAction.start")]}),o.jsxs("button",{className:"action-btn stop",onClick:()=>F("stop"),disabled:!U||e.status==="stopped"||e.status==="stopping",title:c(U?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:buildingAction.stop")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>F("restart"),disabled:!H,title:c(H?"terminal:buildingAction.restart":"terminal:buildingAction.noRestartCommand"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:buildingAction.restart")]}),o.jsxs("button",{className:"action-btn logs",onClick:()=>F("logs"),title:c("terminal:buildingAction.viewLogs"),children:[o.jsx("span",{className:"icon",children:"📄"}),c("terminal:logs.title")]}),R.length===1&&o.jsxs("button",{className:"action-btn open-url",onClick:Q=>P(R[0],Q.altKey),title:`Open http://localhost:${R[0]} (Alt+Click for modal)`,children:[o.jsx("span",{className:"icon",children:"🔗"}),c("terminal:buildingAction.openInBrowser")]}),R.length>1&&o.jsxs("div",{className:"action-btn-group",children:[o.jsxs("span",{className:"action-btn-label",children:[c("terminal:buildingAction.openInBrowser"),":"]}),R.map(Q=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:Re=>P(Q,Re.altKey),title:`Open http://localhost:${Q} (Alt+Click for modal)`,children:[":",Q]},Q))]})]}),d&&k.length>0&&o.jsxs("div",{className:"building-popup-logs",children:[o.jsxs("div",{className:"logs-header",children:[o.jsx("span",{children:c("terminal:logs.title")}),o.jsx("button",{onClick:()=>W.clearBuildingLogs(e.id),children:c("terminal:logs.clear")})]}),o.jsx("div",{className:"logs-content",children:k.slice(-50).map((Q,Re)=>o.jsx("pre",{children:qW(Q)},Re))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function YW(n){if(n===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,s)).toFixed(1))+" "+t[s]}function KW(n){const t=Date.now()-n,s=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const QW=x.memo(function({building:e,screenPos:t,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){const{t:c}=ut(["terminal","common"]),[d,f]=x.useState(null),[h,m]=x.useState(!1),b=x.useRef(null),y=x.useRef(d);y.current=d;const{buildings:v}=Fs(),N=(e.subordinateBuildingIds||[]).map(T=>v.get(T)).filter(T=>T!==void 0),k=x.useRef(null),C=x.useRef(null),A=x.useCallback(T=>{T.preventDefault();const M=y.current?y.current.x:0,R=y.current?y.current.y:0;b.current={mouseX:T.clientX,mouseY:T.clientY,popupX:M,popupY:R},m(!0),k.current=O=>{if(!b.current)return;const U=O.clientX-b.current.mouseX,H=O.clientY-b.current.mouseY;f({x:b.current.popupX+U,y:b.current.popupY+H})},C.current=()=>{m(!1),b.current=null,k.current&&document.removeEventListener("mousemove",k.current),C.current&&document.removeEventListener("mouseup",C.current)},document.addEventListener("mousemove",k.current),document.addEventListener("mouseup",C.current)},[]);x.useEffect(()=>()=>{k.current&&document.removeEventListener("mousemove",k.current),C.current&&document.removeEventListener("mouseup",C.current)},[]);const E=T=>{W.sendBossBuildingCommand(e.id,T)},D=N.reduce((T,M)=>(T[M.status]=(T[M.status]||0)+1,T),{}),_=N.some(T=>{var M;return(M=T.pm2)==null?void 0:M.enabled}),F=(T,M)=>{const R=`http://localhost:${T}`;M&&i?i(R):window.open(R,"_blank")},P=x.useMemo(()=>{let R=t.x+20,O=t.y-80;return typeof window<"u"&&!d&&(t.x+20+340>window.innerWidth&&(R=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:R+((d==null?void 0:d.x)||0),top:O+((d==null?void 0:d.y)||0),zIndex:1e3,cursor:h?"grabbing":void 0}},[t.x,t.y,d,h]);return o.jsxs("div",{className:"building-action-popup boss-building-popup",style:P,onClick:T=>T.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header boss-header ${h?"dragging":""}`,onMouseDown:A,children:[o.jsx("span",{className:"boss-icon",children:"👑"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"subordinate-count",children:c("terminal:building.unitsCount",{count:N.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),o.jsxs("div",{className:"boss-status-overview",children:[Object.entries(D).map(([T,M])=>o.jsxs("span",{className:"status-badge",style:{backgroundColor:ob[T]||"#666"},children:[M," ",T]},T)),N.length===0&&o.jsx("span",{className:"no-subordinates",children:c("terminal:building.noSubordinates")})]}),N.length>0&&o.jsx("div",{className:"subordinate-list",children:N.map(T=>{var M,R,O;return o.jsxs("div",{className:"subordinate-item",children:[o.jsx("span",{className:"sub-status-dot",style:{backgroundColor:ob[T.status]}}),o.jsx("span",{className:"sub-name",children:T.name}),((M=T.pm2Status)==null?void 0:M.ports)&&T.pm2Status.ports.length>0&&o.jsx("span",{className:"sub-port",children:T.pm2Status.ports.map(U=>o.jsxs("a",{href:`http://localhost:${U}`,className:"building-popup-port-link",onClick:H=>{H.preventDefault(),H.stopPropagation(),F(U,H.altKey)},title:`Open http://localhost:${U} (Alt+Click for modal)`,children:[":",U]},U))}),T.pm2Status&&o.jsxs("span",{className:"sub-metrics",children:[(R=T.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",YW(T.pm2Status.memory||0)]}),((O=T.pm2Status)==null?void 0:O.uptime)&&o.jsx("span",{className:"sub-uptime",children:KW(T.pm2Status.uptime)})]},T.id)})}),o.jsxs("div",{className:"building-popup-actions boss-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>E("start_all"),disabled:N.length===0,title:c("terminal:building.startAllSubs"),children:[o.jsx("span",{className:"icon",children:"▶"}),c("terminal:building.startAll")]}),o.jsxs("button",{className:"action-btn stop",onClick:()=>E("stop_all"),disabled:N.length===0,title:c("terminal:building.stopAllSubs"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:building.stopAll")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>E("restart_all"),disabled:N.length===0,title:c("terminal:building.restartAllSubs"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:building.restartAll")]}),_&&o.jsxs("button",{className:"action-btn logs",onClick:r,title:c("terminal:building.viewUnifiedLogs"),children:[o.jsx("span",{className:"icon",children:"📄"}),c("terminal:building.logs")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:building.fullSettings")})]})}),XW=x.memo(function({building:e,screenPos:t,onClose:s,onOpenSettings:a,onOpenDatabasePanel:r}){var D;const{t:i}=ut(["terminal","common"]),[c,d]=x.useState(null),[f,h]=x.useState(!1),m=x.useRef(null),b=x.useRef(c);b.current=c;const y=cx(e.id),v=((D=e.database)==null?void 0:D.connections)??[],S=x.useRef(null),N=x.useRef(null),k=x.useCallback(_=>{_.preventDefault();const F=b.current?b.current.x:0,P=b.current?b.current.y:0;m.current={mouseX:_.clientX,mouseY:_.clientY,popupX:F,popupY:P},h(!0),S.current=T=>{if(!m.current)return;const M=T.clientX-m.current.mouseX,R=T.clientY-m.current.mouseY;d({x:m.current.popupX+M,y:m.current.popupY+R})},N.current=()=>{h(!1),m.current=null,S.current&&document.removeEventListener("mousemove",S.current),N.current&&document.removeEventListener("mouseup",N.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",N.current)},[]);x.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),N.current&&document.removeEventListener("mouseup",N.current)},[]);const C=_=>{W.testDatabaseConnection(e.id,_)},A=_=>y.connectionStatus.get(_),E=x.useMemo(()=>{let P=t.x+20,T=t.y-80;return typeof window<"u"&&!c&&(t.x+20+320>window.innerWidth&&(P=t.x-320-20),t.y-80<0?T=10:t.y-80+300>window.innerHeight&&(T=window.innerHeight-300-10)),{position:"fixed",left:P+((c==null?void 0:c.x)||0),top:T+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,f]);return o.jsxs("div",{className:"building-action-popup database-building-popup",style:E,onClick:_=>_.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header database-header ${f?"dragging":""}`,onMouseDown:k,children:[o.jsx("span",{className:"database-icon",children:"🗄️"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"connection-count",children:i("terminal:building.connCount",{count:v.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),v.length>0?o.jsx("div",{className:"database-connection-list",children:v.map(_=>{var P;const F=A(_.id);return o.jsxs("div",{className:"database-connection-item",children:[o.jsx("span",{className:"conn-engine",children:((P=jL[_.engine])==null?void 0:P.icon)??"🗄️"}),o.jsx("span",{className:"conn-name",children:_.name}),o.jsx("span",{className:"conn-host",children:_.engine==="sqlite"?_.filepath||_.database||":memory:":`${_.host}:${_.port}`}),F&&o.jsx("span",{className:`conn-status ${F.connected?"connected":"disconnected"}`,children:F.connected?"●":"○"}),o.jsx("button",{className:"conn-test-btn",onClick:()=>C(_.id),title:i("terminal:building.testConnection"),children:"↻"})]},_.id)})}):o.jsxs("div",{className:"database-no-connections",children:[o.jsx("p",{children:i("terminal:building.noConnections")}),o.jsx("p",{className:"hint",children:i("terminal:building.clickSettingsToAdd")})]}),o.jsxs("div",{className:"building-popup-actions database-actions",children:[o.jsxs("button",{className:"action-btn query",onClick:r,disabled:v.length===0,title:i("terminal:building.openDbExplorer"),children:[o.jsx("span",{className:"icon",children:"⌨"}),i("terminal:building.query")]}),o.jsxs("button",{className:"action-btn test-all",onClick:()=>v.forEach(_=>C(_.id)),disabled:v.length===0,title:i("terminal:building.testAllConnections"),children:[o.jsx("span",{className:"icon",children:"↻"}),i("terminal:building.testAll")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:i("common:buttons.settings")})]})});function JW({visible:n=!0,position:e="top-right"}){const[t,s]=x.useState(0),[a,r]=x.useState([]),[i,c]=x.useState(null),[d,f]=x.useState([]),[h,m]=x.useState(null),[b,y]=x.useState(null),[v,S]=x.useState(!1),[N,k]=x.useState("fps"),[C,A]=x.useState(null),[E,D]=x.useState(null),[_,F]=x.useState(null),[P,T]=x.useState(typeof window<"u"?window.innerWidth:1024),[M,R]=x.useState(null);x.useEffect(()=>{const J=()=>T(window.innerWidth);return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]);const O=ax(),U=x.useMemo(()=>{const J=O.filter(je=>je.memoryUsageMB!==void 0&&je.memoryUsageMB>0);return{totalMB:J.reduce((je,xe)=>je+(xe.memoryUsageMB||0),0),agentCount:J.length,agents:J.map(je=>({name:je.name,memoryMB:je.memoryUsageMB||0,status:je.status})).sort((je,xe)=>xe.memoryMB-je.memoryMB)}},[O]),H=x.useRef([]),I=x.useRef(null);if(x.useEffect(()=>{H.current=d},[d]),x.useEffect(()=>{I.current=h},[h]),x.useEffect(()=>{if(!n)return;const J=async()=>{try{const je=await Lt(Et("/api/perf"));if(je.ok){const xe=await je.json();D(xe)}}catch{}};J();const de=setInterval(J,v?3e3:1e4);return()=>clearInterval(de)},[n,v]),x.useEffect(()=>{if(!n)return;const J=Ec.getUsage();J&&M===null&&R(J.usedMB);const de=setInterval(()=>{var Re,pe;qd.update();const je=qd.getStats();s(je.current),r(Ie=>[...Ie,je.current].slice(-60));const xe=Ec.getUsage();xe&&c(xe);const qe=window.__tideScene;if(qe){const Ie=(Re=qe.getMemoryDiagnostics)==null?void 0:Re.call(qe);Ie!=null&&Ie.threeJs&&m(Ie.threeJs);const Ne=qe.renderer;if((pe=Ne==null?void 0:Ne.info)!=null&&pe.memory){const fe=Ne.info.memory.textures||0,Ue=Math.round(fe*1);F({count:fe,estimatedMB:Ue})}}const Ke=document.getElementsByTagName("*"),We=document.getElementsByTagName("canvas"),Me=document.getElementsByTagName("img"),ye=document.getElementsByTagName("video");let Fe=0;for(let Ie=0;Ie<Math.min(Ke.length,500);Ie++){const Ne=Ke[Ie];Ne.onclick&&Fe++,Ne.onmousedown&&Fe++,Ne.onkeydown&&Fe++}Fe+=10,A({nodeCount:Ke.length,listenerCount:Fe,canvasCount:We.length,imageCount:Me.length,videoCount:ye.length}),xe&&f(Ie=>{const Ne=I.current,fe={timestamp:Date.now(),heapMB:xe.usedMB,geometries:(Ne==null?void 0:Ne.geometries)??0,textures:(Ne==null?void 0:Ne.textures)??0};return[...Ie,fe].slice(-120)});const Q=H.current;if(Q.length>=10){const Ie=Q[0],Ne=Q[Q.length-1],fe=(Ne.timestamp-Ie.timestamp)/1e3/60;fe>.1&&y((Ne.heapMB-Ie.heapMB)/fe)}},1e3);return()=>{clearInterval(de)}},[n,M]),!n)return null;const $=J=>{const de=Math.floor(J/3600),je=Math.floor(J%3600/60),xe=J%60;return de>0?`${de}h ${je}m`:je>0?`${je}m ${xe}s`:`${xe}s`},z=J=>J>=55?"#4aff9e":J>=30?"#ffcc00":"#ff4a4a",q=(J,de)=>{const je=J/de;return je<.5?"#4aff9e":je<.8?"#ffcc00":"#ff4a4a"},Y=J=>J===null?"#888":J<1?"#4aff9e":J<5?"#ffcc00":"#ff4a4a",B=qd.getStats(),te=P<=768?80:10,V={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:te,left:10},"bottom-right":{bottom:te,right:10}},ge=M&&i?i.usedMB-M:0,he=J=>({padding:"2px 8px",fontSize:"9px",border:"none",background:N===J?"rgba(74, 158, 255, 0.4)":"rgba(255, 255, 255, 0.1)",color:N===J?"#4a9eff":"#888",borderRadius:"3px",cursor:"pointer"});return o.jsxs("div",{style:{position:"fixed",...V[e],zIndex:99999,fontFamily:"monospace",fontSize:"11px",background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",padding:"6px 10px",color:"#fff",userSelect:"none",minWidth:v?"260px":"120px",maxWidth:"calc(100vw - 20px)",maxHeight:v?"calc(100vh - 100px)":"auto",overflowY:v?"auto":"visible",transition:"all 0.2s ease"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:()=>S(!v),children:[o.jsx("span",{style:{color:z(t),fontWeight:"bold",fontSize:"14px"},children:t}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"FPS"}),i&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:q(i.usedMB,i.totalMB),fontWeight:"bold"},children:i.usedMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"MB"})]}),b!==null&&Math.abs(b)>.5&&o.jsxs("span",{style:{color:Y(b),fontSize:"10px",marginLeft:"4px"},children:[b>0?"+":"",b.toFixed(1),"/m"]}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:"#ff9e4a",fontWeight:"bold"},children:E.process.rssMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"SRV"})]}),o.jsx("span",{style:{color:"#444",marginLeft:"auto",fontSize:"10px"},children:v?"▼":"▶"})]}),v&&o.jsxs("div",{style:{marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px"},children:[o.jsxs("div",{style:{display:"flex",gap:"4px",marginBottom:"8px",flexWrap:"wrap"},children:[o.jsx("button",{style:he("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:he("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:he("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:he("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:he("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:he("http"),onClick:()=>k("http"),children:"HTTP"})]}),N==="fps"&&o.jsxs("div",{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Current:"}),o.jsx("span",{style:{color:z(B.current)},children:B.current}),o.jsx("span",{style:{color:"#888"},children:"Min:"}),o.jsx("span",{style:{color:z(B.min)},children:B.min}),o.jsx("span",{style:{color:"#888"},children:"Max:"}),o.jsx("span",{style:{color:z(B.max)},children:B.max}),o.jsx("span",{style:{color:"#888"},children:"Avg:"}),o.jsx("span",{style:{color:z(B.avg)},children:B.avg})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"60s History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"30px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:a.slice(-60).map((J,de)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,J/60*100)}%`,background:z(J),opacity:.8}},de))})]})]}),N==="memory"&&i&&o.jsxs("div",{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Used:"}),o.jsxs("span",{style:{color:q(i.usedMB,i.totalMB)},children:[i.usedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Total:"}),o.jsxs("span",{children:[i.totalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Limit:"}),o.jsxs("span",{children:[i.limitMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Baseline:"}),o.jsxs("span",{children:[M??"—"," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Growth:"}),o.jsxs("span",{style:{color:ge>50?"#ff4a4a":ge>20?"#ffcc00":"#4aff9e"},children:[ge>0?"+":"",ge," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Rate:"}),o.jsx("span",{style:{color:Y(b)},children:b!==null?`${b.toFixed(2)} MB/min`:"—"})]}),o.jsx("div",{style:{marginBottom:"8px"},children:o.jsx("div",{style:{height:"8px",background:"rgba(255,255,255,0.1)",borderRadius:"4px",overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:`${i.usedMB/i.limitMB*100}%`,background:q(i.usedMB,i.totalMB),transition:"width 0.3s ease"}})})}),d.length>1&&o.jsxs("div",{children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"Memory History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"40px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:d.slice(-60).map((J,de)=>{const je=Math.min(...d.map(We=>We.heapMB)),qe=Math.max(...d.map(We=>We.heapMB))-je||1,Ke=(J.heapMB-je)/qe*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,Ke)}%`,background:J.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${J.heapMB}MB`},de)})})]}),U.agentCount>0&&o.jsxs("div",{style:{marginTop:"8px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:["Agent Memory (",U.agentCount,"):"]}),o.jsxs("div",{style:{fontSize:"10px"},children:[o.jsxs("div",{style:{color:"#4aff9e",fontWeight:"bold",marginBottom:"2px"},children:["Total: ",U.totalMB,"MB"]}),o.jsx("div",{style:{maxHeight:"50px",overflowY:"auto"},children:U.agents.slice(0,4).map((J,de)=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":"#666",maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB,"MB"]})]},de))})]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[i.usedMB," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsxs("span",{style:{color:"#9e4aff"},children:["DOM (",(C==null?void 0:C.nodeCount.toLocaleString())??0," nodes)"]}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",i.usedMB+((_==null?void 0:_.estimatedMB)??0)+Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)," MB"]})]})]})]})]}),N==="threejs"&&o.jsx("div",{children:h?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Geometries:"}),o.jsx("span",{style:{color:"#4aff9e"},children:h.geometries}),o.jsx("span",{style:{color:"#888"},children:"Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:h.textures}),o.jsx("span",{style:{color:"#888"},children:"Programs:"}),o.jsx("span",{style:{color:"#9e4aff"},children:h.programs})]}),d.length>1&&o.jsxs("div",{children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"Resource History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"40px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:d.slice(-60).map((J,de)=>{const je=Math.max(...d.map(xe=>xe.textures))||1;return o.jsx("div",{style:{width:"3px",height:`${J.textures/je*100}%`,background:"#ff9e4a",opacity:.8},title:`${J.textures} textures`},de)})})]}),o.jsx("div",{style:{color:"#666",fontSize:"9px",marginTop:"8px"},children:"Tip: Watch textures count. If it keeps increasing, there's a leak."})]}):o.jsxs("div",{style:{color:"#666",fontSize:"10px"},children:["Three.js stats unavailable.",o.jsx("br",{}),"SceneManager not exposed."]})}),N==="dom"&&o.jsx("div",{children:C?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"DOM Nodes:"}),o.jsx("span",{style:{color:C.nodeCount>5e3?"#ff4a4a":C.nodeCount>2e3?"#ffcc00":"#4aff9e"},children:C.nodeCount.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Canvases:"}),o.jsx("span",{style:{color:"#4a9eff"},children:C.canvasCount}),o.jsx("span",{style:{color:"#888"},children:"Images:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:C.imageCount}),o.jsx("span",{style:{color:"#888"},children:"Videos:"}),o.jsx("span",{style:{color:"#9e4aff"},children:C.videoCount})]}),_&&o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("span",{style:{color:"#888"},children:"GPU Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:_.count}),o.jsx("span",{style:{color:"#888"},children:"Est. VRAM:"}),o.jsxs("span",{style:{color:_.estimatedMB>100?"#ff4a4a":"#4aff9e"},children:["~",_.estimatedMB," MB"]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[(i==null?void 0:i.usedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#9e4aff"},children:"DOM (~0.5KB/node)"}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(C.nodeCount*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",((i==null?void 0:i.usedMB)??0)+((_==null?void 0:_.estimatedMB)??0)+Math.round(C.nodeCount*.5/1024)," MB"]})]})]})]}),o.jsx("div",{style:{color:"#666",fontSize:"9px",marginTop:"8px"},children:"Note: Task Manager shows more due to browser overhead, decoded images, and WebGL buffers."})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading DOM stats..."})}),N==="server"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Uptime:"}),o.jsx("span",{style:{color:"#4aff9e"},children:$(E.uptime)}),o.jsx("span",{style:{color:"#888"},children:"Heap Used:"}),o.jsxs("span",{style:{color:E.process.heapUsedMB>500?"#ff4a4a":"#4aff9e"},children:[E.process.heapUsedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Heap Total:"}),o.jsxs("span",{children:[E.process.heapTotalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"RSS:"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.rssMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"External:"}),o.jsxs("span",{children:[E.process.externalMB," MB"]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"System:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Load Avg:"}),o.jsx("span",{style:{color:E.system.loadAvg[0]>E.system.cpuCount?"#ff4a4a":"#4aff9e"},children:E.system.loadAvg.join(" ")}),o.jsx("span",{style:{color:"#888"},children:"CPUs:"}),o.jsx("span",{children:E.system.cpuCount}),o.jsx("span",{style:{color:"#888"},children:"Sys Memory:"}),o.jsxs("span",{children:[E.system.totalMemMB-E.system.freeMemMB," / ",E.system.totalMemMB," MB"]})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"WebSocket:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Clients:"}),o.jsx("span",{style:{color:"#4a9eff"},children:E.websocket.clients}),o.jsx("span",{style:{color:"#888"},children:"Sent:"}),o.jsx("span",{children:E.websocket.messagesSent.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Received:"}),o.jsx("span",{children:E.websocket.messagesReceived.toLocaleString()})]})]}),E.agents.total>0&&o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:["Agents (",E.agents.working,"w / ",E.agents.idle,"i / ",E.agents.total,"t):"]}),o.jsx("div",{style:{maxHeight:"80px",overflowY:"auto",fontSize:"10px"},children:E.agents.processes.map(J=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":J.status==="idle"?"#888":"#ff4a4a",maxWidth:"100px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB!=null?`${J.memoryMB}MB`:"—",J.pid?` (${J.pid})`:""]})]},J.id))})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading server metrics..."})}),N==="http"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Req/sec (30s):"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.http.reqPerSec}),o.jsx("span",{style:{color:"#888"},children:"Avg Latency:"}),o.jsxs("span",{style:{color:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e"},children:[E.http.avgLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Max Latency:"}),o.jsxs("span",{style:{color:E.http.maxLatencyMs>500?"#ff4a4a":E.http.maxLatencyMs>200?"#ffcc00":"#4aff9e"},children:[E.http.maxLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Recent Reqs:"}),o.jsx("span",{children:E.http.recentRequests})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Avg Latency:"}),o.jsx("div",{style:{height:"8px",background:"rgba(255,255,255,0.1)",borderRadius:"4px",overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:`${Math.min(100,E.http.avgLatencyMs/500*100)}%`,background:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e",transition:"width 0.3s ease"}})}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"8px",color:"#444",marginTop:"2px"},children:[o.jsx("span",{children:"0ms"}),o.jsx("span",{children:"500ms"})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Server Process:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"CPU (user):"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.cpuUser," ms"]}),o.jsx("span",{style:{color:"#888"},children:"CPU (system):"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:[E.process.cpuSystem," ms"]}),o.jsx("span",{style:{color:"#888"},children:"WS Clients:"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.websocket.clients})]})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading HTTP metrics..."})}),o.jsxs("div",{style:{display:"flex",gap:"4px",marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px",flexWrap:"wrap"},children:[o.jsx("button",{onClick:J=>{J.stopPropagation();const de=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&de.push("","--- Memory ---",`Heap Used: ${i.usedMB} MB`,`Heap Total: ${i.totalMB} MB`,`Heap Limit: ${i.limitMB} MB`,`Baseline: ${M??"N/A"} MB`,`Growth: ${ge>0?"+":""}${ge} MB`,`Growth Rate: ${b!==null?`${b.toFixed(2)} MB/min`:"N/A"}`),h&&de.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),U.agentCount>0&&(de.push("","--- Agent Memory ---",`Total: ${U.totalMB} MB`,`Agents: ${U.agentCount}`),U.agents.slice(0,5).forEach(xe=>{de.push(` ${xe.name}: ${xe.memoryMB} MB (${xe.status})`)})),C&&de.push("","--- DOM ---",`DOM Nodes: ${C.nodeCount.toLocaleString()}`,`Canvases: ${C.canvasCount}`,`Images: ${C.imageCount}`,`Videos: ${C.videoCount}`),_&&de.push("","--- Estimated Memory ---",`GPU Textures: ${_.count}`,`Est. VRAM: ~${_.estimatedMB} MB`,`Est. DOM: ~${Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)} MB`,`Est. Total: ~${((i==null?void 0:i.usedMB)??0)+_.estimatedMB+Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)} MB`),E&&(de.push("","--- Server ---",`Uptime: ${$(E.uptime)}`,`Heap: ${E.process.heapUsedMB}/${E.process.heapTotalMB} MB`,`RSS: ${E.process.rssMB} MB`,`Load Avg: ${E.system.loadAvg.join(" ")}`,`System Memory: ${E.system.totalMemMB-E.system.freeMemMB}/${E.system.totalMemMB} MB`,"","--- WebSocket ---",`Clients: ${E.websocket.clients}`,`Sent: ${E.websocket.messagesSent}`,`Received: ${E.websocket.messagesReceived}`,"","--- HTTP ---",`Req/sec: ${E.http.reqPerSec}`,`Avg Latency: ${E.http.avgLatencyMs} ms`,`Max Latency: ${E.http.maxLatencyMs} ms`),E.agents.processes.length>0&&(de.push("","--- Agent Processes ---",`Total: ${E.agents.total} (${E.agents.working} working, ${E.agents.idle} idle)`),E.agents.processes.forEach(xe=>{de.push(` ${xe.name}: ${xe.memoryMB!=null?`${xe.memoryMB}MB`:"N/A"} (${xe.status})${xe.pid?` PID:${xe.pid}`:""}`)})));const je=de.join(`
145
- `);navigator.clipboard.writeText(je).then(()=>{const xe=J.currentTarget,qe=xe.textContent;xe.textContent="Copied!",setTimeout(()=>{xe.textContent=qe},1e3)})},style:{flex:1,background:"rgba(74, 255, 158, 0.3)",border:"1px solid rgba(74, 255, 158, 0.5)",color:"#4aff9e",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Copy Stats"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),Ec.report();const de=window.__tideScene;de!=null&&de.logMemoryDiagnostics&&de.logMemoryDiagnostics()},style:{flex:1,background:"rgba(74, 158, 255, 0.3)",border:"1px solid rgba(74, 158, 255, 0.5)",color:"#4a9eff",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Console"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),fb.clear(),qd.reset(),Ec.reset(),r([]),f([]);const de=Ec.getUsage();de&&R(de.usedMB)},style:{flex:1,background:"rgba(255, 74, 74, 0.3)",border:"1px solid rgba(255, 74, 74, 0.5)",color:"#ff4a4a",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Reset"})]})]})]})}function ZW(){const n=Dj(),e=x.useCallback(t=>{W.setViewMode(t)},[]);return[n,e]}const eV=["3d","2d","dashboard"],tV=x.memo(function({className:e=""}){const{t}=ut(["common"]),[s,a]=ZW(),r=x.useRef(null),[i,c]=x.useState(null);x.useLayoutEffect(()=>{const f=r.current;if(!f)return;const h=f.querySelector(".view-mode-toggle__btn--active");h&&c({left:h.offsetLeft,width:h.offsetWidth})},[s]);const d=x.useCallback(f=>{if(f!==s){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:f}})),f==="3d"){requestAnimationFrame(()=>a(f));return}a(f)}},[s,a]);return o.jsxs("div",{className:`view-mode-toggle ${e}`,ref:r,children:[i&&o.jsx("div",{className:"view-mode-toggle__indicator",style:{left:i.left,width:i.width}}),eV.map(f=>o.jsxs("button",{className:`view-mode-toggle__btn ${s===f?"view-mode-toggle__btn--active":""}`,onClick:()=>d(f),title:t(`common:viewMode.descriptions.${f}`),children:[o.jsxs("span",{className:"view-mode-toggle__icon",children:[f==="2d"&&o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),o.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),o.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),f==="3d"&&o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),o.jsx("path",{d:"M2 17l10 5 10-5"}),o.jsx("path",{d:"M2 12l10 5 10-5"})]}),f==="dashboard"&&o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),o.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),o.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),o.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),o.jsx("span",{className:"view-mode-toggle__label",children:t(`common:viewMode.labels.${f}`)})]},f))]})});function ST({className:n}){const{t:e}=ut(["terminal"]),[t,s]=x.useState(!1),[a,r]=x.useState(null),i=Kx(),c=x.useCallback(async y=>{if(y.trim()){console.log("[VoiceAssistant] Transcribed:",y),s(!0),r(null);try{const S=await(await Lt(Et("/api/voice-assistant/process"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:y})})).json();if(S.success&&S.response)console.log("[VoiceAssistant] Response:",S.response),i.speak(S.response);else{const N=S.error||e("terminal:voiceAssistant.failedToProcess");console.error("[VoiceAssistant] Error:",N),r(N),i.speak(N)}}catch(v){console.error("[VoiceAssistant] Request failed:",v);const S=e("terminal:voiceAssistant.unavailable");r(S),i.speak(S)}finally{s(!1)}}},[i]),d=wT({language:"Spanish",model:"medium",onTranscription:c}),f=d.recording||d.transcribing||t||i.speaking,h=()=>d.error?`${e("terminal:voiceAssistant.error")}: ${d.error}`:a?`${e("terminal:voiceAssistant.error")}: ${a}`:d.recording?e("terminal:voiceAssistant.recording"):d.transcribing?e("terminal:voiceAssistant.transcribing"):t?e("terminal:voiceAssistant.processing"):i.speaking?e("terminal:voiceAssistant.speaking"):e("terminal:voiceAssistant.title"),m=()=>{const y=["voice-assistant-btn",n].filter(Boolean);return d.recording&&y.push("recording"),(d.transcribing||t)&&y.push("processing"),i.speaking&&y.push("speaking"),(a||d.error)&&y.push("error"),y.join(" ")},b=()=>{if(r(null),i.speaking){i.stop();return}d.transcribing||t||d.toggleRecording()};return o.jsxs("button",{className:m(),onClick:b,title:d.supported?h():e("terminal:voiceAssistant.notSupported"),disabled:!d.supported||d.transcribing||t,children:[d.recording?o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor",children:[o.jsx("path",{d:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"}),o.jsx("path",{d:"M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"})]}):i.speaking?o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5",fill:"currentColor"}),o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),o.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),o.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),o.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),f&&o.jsx("span",{className:"voice-assistant-indicator"})]})}const nV=x.memo(function({isOpen:e,onToggle:t,onShowTerminal:s,onOpenSidebar:a,onOpenToolbox:r,onOpenCommander:i,onOpenControls:c,onOpenSkills:d,mobileView:f}){const{t:h}=ut(["terminal","common"]),m=Br(),b=y=>{y(),t()};return o.jsxs(o.Fragment,{children:[m.experimentalVoiceAssistant&&o.jsx(ST,{className:"mobile-voice-assistant"}),f!=="terminal"&&o.jsx("button",{className:`mobile-fab-toggle ${e?"open":""}`,onClick:t,onTouchStart:y=>y.stopPropagation(),title:h(e?"terminal:mobileFab.closeMenu":"terminal:mobileFab.openMenu"),children:e?"✕":"☰"}),f==="3d"&&o.jsxs("div",{className:`mobile-fab-menu ${e?"open":""}`,children:[o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(s),onTouchEnd:y=>{y.preventDefault(),b(s)},title:h("terminal:mobileFab.showTerminal"),children:"💬"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(a),onTouchEnd:y=>{y.preventDefault(),b(a)},title:h("terminal:header.openSidebar"),children:"📋"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(r),onTouchEnd:y=>{y.preventDefault(),b(r)},title:h("common:floatingButtons.settingsAndTools"),children:"⚙️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(i),onTouchEnd:y=>{y.preventDefault(),b(i)},title:h("common:floatingButtons.commanderView"),children:"📊"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(c),onTouchEnd:y=>{y.preventDefault(),b(c)},title:h("common:floatingButtons.controls"),children:"⌨️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(d),onTouchEnd:y=>{y.preventDefault(),b(d)},title:h("common:floatingButtons.manageSkills"),children:"⭐"})]})]})}),sV=x.memo(function({onOpenToolbox:e,onOpenCommander:t,onOpenControls:s,onOpenSkills:a,onSpawnAgent:r,onSpawnBoss:i,onNewBuilding:c,onNewArea:d}){const{t:f}=ut(["common","terminal"]),h=Br();return o.jsxs(o.Fragment,{children:[h.experimentalVoiceAssistant&&o.jsx(ST,{}),o.jsx(Un,{content:f("common:floatingButtons.settingsAndTools"),position:"right",children:o.jsx("button",{className:"floating-settings-btn",onClick:e,"aria-label":f("common:floatingButtons.settingsAndTools"),children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})}),o.jsx(Un,{content:f("common:floatingButtons.commanderView"),position:"right",children:o.jsx("button",{className:"commander-toggle-btn",onClick:t,"aria-label":f("common:floatingButtons.commanderView"),children:o.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"3",y:"3",width:"7",height:"7"}),o.jsx("rect",{x:"14",y:"3",width:"7",height:"7"}),o.jsx("rect",{x:"3",y:"14",width:"7",height:"7"}),o.jsx("rect",{x:"14",y:"14",width:"7",height:"7"})]})})}),o.jsx(Un,{content:f("common:floatingButtons.controls"),position:"right",children:o.jsx("button",{className:"shortcuts-toggle-btn",onClick:s,"aria-label":f("common:floatingButtons.controls"),children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"4",y1:"21",x2:"4",y2:"14"}),o.jsx("line",{x1:"4",y1:"10",x2:"4",y2:"3"}),o.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"12"}),o.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"3"}),o.jsx("line",{x1:"20",y1:"21",x2:"20",y2:"16"}),o.jsx("line",{x1:"20",y1:"12",x2:"20",y2:"3"}),o.jsx("line",{x1:"1",y1:"14",x2:"7",y2:"14"}),o.jsx("line",{x1:"9",y1:"8",x2:"15",y2:"8"}),o.jsx("line",{x1:"17",y1:"16",x2:"23",y2:"16"})]})})}),o.jsx(Un,{content:f("common:floatingButtons.manageSkills"),position:"right",children:o.jsx("button",{className:"skills-toggle-btn",onClick:a,"aria-label":f("common:floatingButtons.manageSkills"),children:o.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"})})})}),o.jsx(Un,{content:f("common:agentBar.spawnNewAgent"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-agent-btn",onClick:r,"aria-label":f("common:agentBar.spawnNewAgent"),children:o.jsx("span",{className:"fab-spawn-icon",children:"+"})})}),o.jsx(Un,{content:f("common:agentBar.spawnBoss"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-boss-btn",onClick:i,"aria-label":f("common:agentBar.spawnBoss"),children:o.jsx("span",{className:"fab-spawn-icon",children:"👑"})})}),o.jsx(Un,{content:f("common:agentBar.addNewBuilding"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-building-btn",onClick:c,"aria-label":f("common:agentBar.addNewBuilding"),children:o.jsx("span",{className:"fab-spawn-icon",children:"🏢"})})}),o.jsx(Un,{content:f("common:agentBar.drawNewArea"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-area-btn",onClick:d,"aria-label":f("common:agentBar.drawNewArea"),children:o.jsx("span",{className:"fab-spawn-icon",children:"🔲"})})})]})}),aV=Ce.lazy(()=>gt(()=>import("./SpawnModal-Bn3ZqlXN.js"),__vite__mapDeps([17,3,1,4])).then(n=>({default:n.SpawnModal}))),rV=Ce.lazy(()=>gt(()=>import("./BossSpawnModal-DnGG9qzz.js"),__vite__mapDeps([18,3,1,4])).then(n=>({default:n.BossSpawnModal}))),iV=Ce.lazy(()=>gt(()=>import("./SubordinateAssignmentModal-DhejKnmh.js"),__vite__mapDeps([19,3,1,4])).then(n=>({default:n.SubordinateAssignmentModal}))),oV=Ce.lazy(()=>gt(()=>import("./index-BafIwYn2.js"),__vite__mapDeps([20,3,1,4,21])).then(n=>({default:n.Toolbox}))),lV=Ce.lazy(()=>gt(()=>import("./index-W4C-3jYM.js"),__vite__mapDeps([22,3,1,4])).then(n=>({default:n.BuildingConfigModal}))),cV=Ce.lazy(()=>gt(()=>import("./index-C7D5bylg.js"),__vite__mapDeps([23,24,3,1,4])).then(n=>({default:n.CommanderView}))),uV=Ce.lazy(()=>gt(()=>import("./index-D8ooZD2k.js").then(n=>n.y),[]).then(n=>({default:n.FileExplorerPanel}))),dV=Ce.lazy(()=>gt(()=>import("./index-D3rq1hsg.js"),__vite__mapDeps([25,3,1,4])).then(n=>({default:n.Spotlight}))),fV=Ce.lazy(()=>gt(()=>import("./ControlsModal-DRP1_rbW.js"),__vite__mapDeps([26,3,1,4])).then(n=>({default:n.ControlsModal}))),pV=Ce.lazy(()=>gt(()=>import("./SkillsPanel-CocWkSNx.js"),__vite__mapDeps([27,3,1,4])).then(n=>({default:n.SkillsPanel}))),hV=Ce.lazy(()=>gt(()=>Promise.resolve().then(()=>O2),void 0).then(n=>({default:n.AgentEditModal}))),mV=Ce.lazy(()=>gt(()=>import("./RestoreArchivedAreaModal-DFk4VoA6.js"),__vite__mapDeps([28,3,1,4])).then(n=>({default:n.RestoreArchivedAreaModal}))),gV=Ce.lazy(()=>gt(()=>import("./IntegrationsPanel-BUFdQGGO.js"),__vite__mapDeps([29,3,1,4])).then(n=>({default:n.IntegrationsPanel}))),bV=Ce.lazy(()=>gt(()=>import("./MonitoringModal-myaLpP0P.js"),__vite__mapDeps([30,3,1,4])).then(n=>({default:n.MonitoringModal}))),xV=Ce.lazy(()=>gt(()=>import("./WorkflowEditorPanel-DvIqQCf4.js"),__vite__mapDeps([31,3,1,4])).then(n=>({default:n.WorkflowEditorPanel}))),yV=Ce.lazy(()=>gt(()=>import("./TriggerManagerPanel-2TubwcF4.js"),__vite__mapDeps([32,3,1,4])).then(n=>({default:n.TriggerManagerPanel})));function vV({spawnModal:n,bossSpawnModal:e,subordinateModal:t,toolboxModal:s,commanderModal:a,deleteConfirmModal:r,spotlightModal:i,controlsModal:c,skillsModal:d,integrationsModal:f,monitoringModal:h,workflowEditorModal:m,triggerManagerModal:b,buildingModal:y,agentEditModal:v,restoreArchivedModal:S,explorerModal:N,contextMenu:k,spawnPosition:C,spawnAreaId:A,explorerFolderPath:E,contextMenuActions:D,buildingInitialPosition:_,sceneConfig:F,onConfigChange:P,onToolChange:T,onOpenAreaExplorer:M,onDeleteSelectedAgents:R,pendingBuildingDelete:O,onCancelBuildingDelete:U,onConfirmBuildingDelete:H,showBackNavModal:I,onCloseBackNavModal:$,onLeave:z,onOpenPM2LogsModal:q,onOpenBossLogsModal:Y,onOpenDatabasePanel:B,onSyncScene:G}){const te=Fs(),V=O==="selected",ge=O&&O!=="selected"?te.buildings.get(O):null,he=te.selectedBuildingIds.size;return o.jsxs(x.Suspense,{fallback:null,children:[o.jsx(oV,{config:F,onConfigChange:P,onToolChange:T,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:J=>y.open(J||null),onOpenAreaExplorer:M,onOpenIntegrationsModal:J=>f.open(J),onOpenMonitoringModal:()=>h.open(),onOpenWorkflowEditor:()=>m.open(),onOpenTriggerManager:()=>b.open()}),o.jsx(lV,{isOpen:y.isOpen,onClose:y.close,buildingId:y.data,initialPosition:_||void 0}),o.jsx(aV,{isOpen:n.isOpen,onClose:n.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:C,spawnAreaId:A}),o.jsx(rV,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:C}),o.jsx(iV,{isOpen:t.isOpen,bossId:t.data||"",onClose:t.close}),v.isOpen&&v.data&&(()=>{const J=te.agents.get(v.data);return J?o.jsx(hV,{agent:J,isOpen:v.isOpen,onClose:v.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:J=>{J.key==="Escape"&&r.close(),J.key==="Enter"&&R()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:J=>J.stopPropagation(),children:[o.jsx("div",{className:"modal-header",children:"Remove Agents"}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[o.jsxs("p",{children:["Remove ",te.selectedAgentIds.size," selected agent",te.selectedAgentIds.size>1?"s":""," from the battlefield?"]}),o.jsx("p",{className:"confirm-modal-note",children:"Claude Code sessions will continue running in the background."})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:r.close,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:R,autoFocus:!0,children:"Remove"})]})]})}),(ge||V)&&o.jsx("div",{className:"modal-overlay visible",onClick:U,onKeyDown:J=>{J.key==="Escape"&&U(),J.key==="Enter"&&H()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:J=>J.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",V&&he>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[V?o.jsxs("p",{children:["Delete ",he," selected building",he>1?"s":"","?"]}):o.jsxs("p",{children:["Delete ",o.jsx("strong",{children:ge==null?void 0:ge.name}),"?"]}),o.jsxs("p",{className:"confirm-modal-note",children:["This will permanently remove the building",V&&he>1?"s":""," and ",V&&he>1?"their":"its"," configuration."]})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:U,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:H,autoFocus:!0,children:"Delete"})]})]})}),I&&o.jsx("div",{className:"modal-overlay navigation-confirm-overlay visible",onClick:$,onKeyDown:J=>{J.key==="Escape"&&$()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:J=>J.stopPropagation(),children:[o.jsx("div",{className:"modal-header",children:"Leave Tide Commander?"}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[o.jsx("p",{children:"Are you sure you want to leave this page?"}),o.jsx("p",{className:"confirm-modal-note",children:"Active Claude Code sessions will continue running in the background."})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:$,autoFocus:!0,children:"Stay"}),o.jsx("button",{className:"btn btn-danger",onClick:z,children:"Leave"})]})]})}),o.jsx(x.Profiler,{id:"CommanderView",onRender:pb,children:o.jsx(cV,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(uV,{isOpen:N.isOpen||E!==null||te.explorerAreaId!==null,areaId:N.id||te.explorerAreaId||null,folderPath:E,onChangeArea:J=>N.open(J),onClose:()=>{N.close(),W.closeFileExplorer()}}),o.jsx(dV,{isOpen:i.isOpen,onClose:i.close,onOpenSpawnModal:()=>n.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenFileExplorer:J=>N.open(J),onOpenPM2LogsModal:q,onOpenBossLogsModal:Y,onOpenDatabasePanel:B,onOpenMonitoringModal:()=>h.open()}),o.jsx(fV,{isOpen:c.isOpen,onClose:c.close}),o.jsx(pV,{isOpen:d.isOpen,onClose:d.close}),o.jsx(gV,{isOpen:f.isOpen,onClose:f.close,initialTab:f.data}),o.jsx(bV,{isOpen:h.isOpen,onClose:h.close}),o.jsx(xV,{isOpen:m.isOpen,onClose:m.close}),o.jsx(yV,{isOpen:b.isOpen,onClose:b.close}),o.jsx(mV,{isOpen:S.isOpen,restorePosition:S.data??null,onClose:S.close,onRestored:G}),o.jsx(co,{isOpen:k.isOpen,position:k.screenPosition,worldPosition:k.worldPosition,actions:D,onClose:k.close})]})}function wV(n){const e=n.trim();if(!e)return{ok:!0,normalizedUrl:""};let t;try{t=new URL(e)}catch{return{ok:!1,normalizedUrl:"",error:"Invalid URL format. Use http://host:port"}}return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,normalizedUrl:"",error:"Unsupported protocol. Use http or https"}:{ok:!0,normalizedUrl:e}}async function kV(n,e=5e3,t=fetch){if(!n)return{ok:!0};const a=`${n.replace(/\/$/,"")}/api/health`,r=new AbortController,i=setTimeout(()=>r.abort(),e);try{const c=await t(a,{method:"GET",cache:"no-store",signal:r.signal});return c.ok?{ok:!0}:{ok:!1,error:`Host reachable but unhealthy (${c.status})`}}catch(c){return c instanceof Error&&c.name==="AbortError"?{ok:!1,error:"Connection timed out while checking host"}:{ok:!1,error:"Host unreachable. Check URL, host, and port"}}finally{clearTimeout(i)}}const SV=4e3;function CV(){const n=jj(),[e,t]=x.useState(!1),[s,a]=x.useState(!1),[r,i]=x.useState(!0),[c,d]=x.useState(!1),[f,h]=x.useState(()=>Kb()),[m,b]=x.useState(!1),[y,v]=x.useState(null),[S,N]=x.useState(null),k=x.useRef(!0),C=x.useRef(!1),A=x.useCallback((P=7e3)=>W.getState().isConnected?Promise.resolve(!0):new Promise(T=>{let M=!1;const R=H=>{M||(M=!0,clearTimeout(U),O(),T(H))},O=W.subscribe(()=>{W.getState().isConnected&&R(!0)}),U=setTimeout(()=>R(!1),P)}),[]);x.useEffect(()=>{const P=setTimeout(()=>i(!1),3e3);return()=>clearTimeout(P)},[]),x.useEffect(()=>{if(n){C.current=!0,d(!1);return}if(C.current){i(!0),d(!0);const P=setTimeout(()=>{i(!1),d(!1)},1e4);return()=>clearTimeout(P)}},[n]),x.useEffect(()=>()=>{k.current=!1},[]),x.useEffect(()=>UD(P=>{h(P)}),[]);const E=x.useCallback(()=>{navigator.clipboard.writeText("bunx tide-commander").then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(()=>{})},[]),D=x.useCallback(async()=>{if(m)return;const P=Date.now(),T=()=>SV-(Date.now()-P);v(null),N("Validating URL");const M=f.trim()||"http://localhost:6200",R=wV(M);if(!R.ok){N(null),v(R.error||"Invalid backend URL");return}b(!0),N("Checking host reachability");const O=T();if(O<=0){b(!1),N(null),v("Connection timeout after 4 seconds");return}const U=await kV(R.normalizedUrl,O);if(!U.ok){if(!k.current)return;b(!1),N(null),T()<=0?v("Connection timeout after 4 seconds"):v(U.error||"Failed to reach host");return}HD(R.normalizedUrl),N("Connecting to server"),RR();const H=T();if(H<=0){b(!1),N(null),v("Connection timeout after 4 seconds");return}const I=await A(H);if(k.current){if(!I){b(!1),N(null),T()<=0?v("Connection timeout after 4 seconds"):v("Could not establish WebSocket connection. Verify host and auth token, then retry");return}b(!1),N("Connected"),v(null)}},[f,m,A]),_=x.useCallback(P=>{P.key==="Enter"&&!m&&D()},[D,m]),F=x.useCallback(()=>{t(!0)},[]);return n||e?null:r&&c?o.jsxs("div",{className:"reconnecting-toast",children:[o.jsx("span",{className:"reconnecting-spinner"}),"Reconnecting..."]}):r?null:o.jsx("div",{className:"not-connected-overlay",children:o.jsxs("div",{className:"not-connected-panel",children:[o.jsx("h2",{className:"not-connected-title",children:"Tide Commander"}),o.jsx("p",{className:"not-connected-description",children:"A visual multi-agent orchestrator for Claude Code and Codex. Deploy, control, and monitor your AI team from an RTS-inspired interface."}),o.jsx("p",{className:"not-connected-privacy",children:"Tide Commander syncs with Claude Code instances running on your local machine. No files or code are sent to this server."}),o.jsxs("div",{className:"not-connected-setup",children:[o.jsx("p",{className:"not-connected-setup-label",children:"Get started:"}),o.jsxs("div",{className:"not-connected-code",onClick:E,title:"Click to copy",children:[o.jsx("span",{children:"bunx tide-commander"}),o.jsx("span",{className:"not-connected-copy-icon",children:s?"✓":"⧉"})]})]}),o.jsxs("div",{className:"not-connected-url-section",children:[o.jsx("label",{className:"not-connected-url-label",htmlFor:"backend-url",children:"Backend URL"}),o.jsx("div",{className:"not-connected-url-row",children:o.jsx("input",{id:"backend-url",type:"text",className:"not-connected-url-input",placeholder:"http://localhost:6200",value:f,disabled:m,onChange:P=>{const T=P.target.value;h(T),y&&v(null)},onKeyDown:_})}),o.jsx("span",{className:"config-hint",children:"Leave empty for auto-detect"}),S&&!y&&o.jsx("div",{className:"not-connected-status","aria-live":"polite",children:S}),y&&o.jsx("div",{className:"not-connected-error","aria-live":"assertive",children:y})]}),o.jsxs("div",{className:"not-connected-actions",children:[o.jsx("button",{className:"not-connected-btn not-connected-btn-retry",onClick:()=>{D()},disabled:m,children:m?"Connecting...":"↻ Connect"}),o.jsx("button",{className:"not-connected-btn not-connected-btn-explore",onClick:F,children:"Explore"})]})]})})}const TA="tide-onboarding-dismissed";function AV({onCreateAgent:n}){const{t:e}=ut("common"),t=jj(),s=Sj(),[a,r]=x.useState(()=>sessionStorage.getItem(TA)==="1"),i=t&&!a&&s===0,c=x.useCallback(()=>{r(!0),sessionStorage.setItem(TA,"1")},[]),d=x.useCallback(()=>{c(),n()},[c,n]),f=x.useCallback(h=>{h.key==="Escape"&&c()},[c]);return i?o.jsx(Ba,{children:o.jsx("div",{className:"modal-overlay visible",onClick:c,onKeyDown:f,children:o.jsxs("div",{className:"modal onboarding-modal",onClick:h=>h.stopPropagation(),children:[o.jsxs("div",{className:"onboarding-header",children:[o.jsx("h2",{children:e("onboarding.title")}),o.jsx("p",{className:"onboarding-subtitle",children:e("onboarding.subtitle")})]}),o.jsxs("div",{className:"onboarding-steps",children:[o.jsxs("div",{className:"onboarding-step",children:[o.jsx("span",{className:"onboarding-step-number",children:"1"}),o.jsxs("div",{children:[o.jsx("strong",{children:e("onboarding.step1Title")}),o.jsx("p",{children:e("onboarding.step1Desc")})]})]}),o.jsxs("div",{className:"onboarding-step",children:[o.jsx("span",{className:"onboarding-step-number",children:"2"}),o.jsxs("div",{children:[o.jsx("strong",{children:e("onboarding.step2Title")}),o.jsx("p",{children:e("onboarding.step2Desc")})]})]}),o.jsxs("div",{className:"onboarding-step",children:[o.jsx("span",{className:"onboarding-step-number",children:"3"}),o.jsxs("div",{children:[o.jsx("strong",{children:e("onboarding.step3Title")}),o.jsx("p",{children:e("onboarding.step3Desc")})]})]})]}),o.jsxs("div",{className:"onboarding-actions",children:[o.jsx("button",{className:"btn onboarding-cta",onClick:d,autoFocus:!0,children:e("onboarding.createFirst")}),o.jsx("button",{className:"btn btn-secondary",onClick:c,children:e("onboarding.explore")})]})]})})}):null}function CT(){return{"Content-Type":"application/json","X-Auth-Token":Ir()}}async function jV(n){const e=await fetch(`${ra()}/api/areas/${n}/organize`,{method:"POST",headers:CT()});if(!e.ok)throw new Error(`Failed to organize area: ${e.statusText}`);const t=await e.json();return{organized:Array.isArray(t.organized)?t.organized:[],buildings:Array.isArray(t.buildings)?t.buildings:[]}}async function NV(){const n=await fetch(`${ra()}/api/areas/organize-all`,{method:"POST",headers:CT()});if(!n.ok)throw new Error(`Failed to organize all areas: ${n.statusText}`);const e=await n.json();return Array.isArray(e.organized)?{organized:e.organized,buildings:Array.isArray(e.buildings)?e.buildings:[]}:(Array.isArray(e.results)?e.results:[]).reduce((t,s)=>(t.organized.push(...s.organized),t.buildings.push(...s.buildings),t),{organized:[],buildings:[]})}function AT(n,e){var s,a;const t=W.getState();for(const r of n.organized){const i=t.agents.get(r.agentId);if(i){const c={...i,position:r.position};W.updateAgent(c),(s=e.current)==null||s.updateAgent(c,!0)}}for(const r of n.buildings){const i=t.buildings.get(r.buildingId);i&&(W.updateBuilding(r.buildingId,{position:r.position}),(a=e.current)==null||a.updateBuilding({...i,position:r.position}))}}function TV(n,e,t,s,a,r){const i=[];if(e.type==="agent"&&e.id){const d=t.get(e.id);if(d)return i.push({id:"select-agent",label:`Select ${d.name}`,icon:"👆",onClick:()=>{var f;W.selectAgent(e.id),(f=r.sceneRef.current)==null||f.refreshSelectionVisuals()}}),i.push({id:"focus-agent",label:"Focus Camera",icon:"🎯",onClick:()=>{var f;(f=r.sceneRef.current)==null||f.focusAgent(e.id)}}),i.push({id:"open-terminal",label:"Open Terminal",icon:"💬",onClick:()=>{W.selectAgent(e.id),W.setTerminalOpen(!0)}}),i.push({id:"edit-agent",label:"Edit Agent",icon:"✏️",onClick:()=>{r.openAgentEditModal(e.id)}}),i.push({id:"divider-agent",label:"",divider:!0,onClick:()=>{}}),i.push({id:"delete-agent",label:`Remove ${d.name}`,icon:"❌",danger:!0,onClick:()=>{var f;W.removeAgentFromServer(e.id),(f=r.sceneRef.current)==null||f.removeAgent(e.id),r.showToast("info","Agent Removed",`${d.name} removed from view`)}}),i}if(e.type==="area"&&e.id){const d=s.get(e.id);if(d)return i.push({id:"select-area",label:`Select "${d.name}"`,icon:"📐",onClick:()=>{W.selectArea(e.id),r.openToolboxModal()}}),d.directories&&d.directories.length>0&&i.push({id:"open-explorer",label:"Open File Explorer",icon:"📁",onClick:()=>{r.openExplorerModal(e.id)}}),i.push({id:"spawn-in-area",label:"Spawn Agent",icon:"🤖",onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-spawn-modal",{detail:{areaId:e.id,position:{x:d.center.x,z:d.center.z}}}))}}),i.push({id:"divider-area-layer",label:"",divider:!0,onClick:()=>{}}),i.push({id:"bring-to-front",label:"Bring to Front",icon:"⬆️",onClick:()=>{var f;W.bringAreaToFront(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),i.push({id:"send-to-back",label:"Send to Back",icon:"⬇️",onClick:()=>{var f;W.sendAreaToBack(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),d.assignedAgentIds.length>0&&i.push({id:"organize-area",label:"Organize Area",icon:"✨",onClick:()=>{jV(e.id).then(f=>{AT(f,r.sceneRef),r.showToast("success","Area Organized",`Arranged ${f.organized.length} agent${f.organized.length!==1?"s":""} in "${d.name}"`)}).catch(f=>{console.error("organize area error:",f),r.showToast("error","Organize Failed",f.message||"Failed to organize area")})}}),i.push({id:"divider-area",label:"",divider:!0,onClick:()=>{}}),i.push({id:"archive-area",label:`Archive "${d.name}"`,icon:"📦",onClick:()=>{var m,b;const f=d.assignedAgentIds.length;W.archiveArea(e.id,y=>W.stopAgent(y)),(m=r.sceneRef.current)==null||m.syncAreas(),(b=r.sceneRef.current)==null||b.syncAgents(Array.from(W.getState().agents.values()));const h=f>0?` (${f} agent${f>1?"s":""} stopped)`:"";r.showToast("info","Zone Archived",`"${d.name}" has been archived${h}`)}}),i.push({id:"delete-area",label:`Delete "${d.name}"`,icon:"🗑️",danger:!0,onClick:()=>{var f;W.deleteArea(e.id),(f=r.sceneRef.current)==null||f.syncAreas(),r.showToast("info","Area Deleted",`"${d.name}" has been deleted`)}}),i}if(e.type==="building"&&e.id){const d=a.get(e.id);if(d)return i.push({id:"select-building",label:`Select "${d.name}"`,icon:"🏢",onClick:()=>{W.selectBuilding(e.id),r.openToolboxModal()}}),i.push({id:"edit-building",label:"Edit Building",icon:"✏️",onClick:()=>{r.openBuildingModal(e.id)}}),i.push({id:"clone-building",label:"Clone Building",icon:"📋",onClick:()=>{const f={name:`${d.name} (Copy)`,type:d.type,style:d.style,color:d.color,scale:d.scale,position:{x:d.position.x+2,z:d.position.z+2},cwd:d.cwd,folderPath:d.folderPath,commands:d.commands,pm2:d.pm2,docker:d.docker,database:d.database,urls:d.urls,subordinateBuildingIds:d.subordinateBuildingIds};W.createBuilding(f),r.showToast("success","Building Cloned",`Created "${f.name}"`)}}),d.type==="folder"&&d.folderPath&&i.push({id:"open-folder",label:"Open Folder",icon:"📁",onClick:()=>{W.openFileExplorer(d.folderPath)}}),i.push({id:"divider-building",label:"",divider:!0,onClick:()=>{}}),i.push({id:"delete-building",label:`Delete "${d.name}"`,icon:"🗑️",danger:!0,onClick:()=>{r.requestBuildingDelete(e.id)}}),i}i.push({id:"spawn-agent",label:"Spawn Agent Here",icon:"🤖",shortcut:"N",onClick:()=>{r.setSpawnPosition(n),r.openSpawnModal()}}),i.push({id:"spawn-boss",label:"Spawn Boss Here",icon:"👑",onClick:()=>{r.setSpawnPosition(n),r.openBossSpawnModal()}}),i.push({id:"divider-1",label:"",divider:!0,onClick:()=>{}}),i.push({id:"draw-area",label:"Draw Area",icon:"📐",onClick:()=>{var d;(d=r.sceneRef.current)==null||d.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),r.showToast("info","Rectangle Tool","Click and drag on the battlefield to draw an area")}}),i.push({id:"new-building",label:"Place Building",icon:"🏢",onClick:()=>{r.openBuildingModal(null)}});const c=Array.from(s.values()).filter(d=>d.archived).length;return c>0&&i.push({id:"restore-archived",label:`Restore Archived Zone (${c})`,icon:"📦",onClick:()=>{r.openRestoreArchivedModal(n)}}),i.push({id:"divider-2",label:"",divider:!0,onClick:()=>{}}),i.push({id:"open-settings",label:"Settings",icon:"⚙️",onClick:()=>{r.openToolboxModal()}}),i.push({id:"open-commander",label:"Commander View",icon:"📊",shortcut:"⌘K",onClick:()=>{r.openCommanderModal()}}),i}const _V=Ce.lazy(()=>gt(()=>import("./index-B4lXmEKE.js"),__vite__mapDeps([33,3,1,4,34])).then(n=>({default:n.DatabasePanel}))),EV=Ce.lazy(()=>gt(()=>import("./PM2LogsModal-xYkfYrSr.js"),__vite__mapDeps([35,36,3,1,4])).then(n=>({default:n.PM2LogsModal}))),MV=Ce.lazy(()=>gt(()=>import("./DockerLogsModal-ko1qlvFd.js"),__vite__mapDeps([37,36,3,1,4])).then(n=>({default:n.DockerLogsModal}))),DV=Ce.lazy(()=>gt(()=>import("./BossLogsModal-Ymc3oi56.js"),__vite__mapDeps([38,36,3,1,4])).then(n=>({default:n.BossLogsModal}))),RV=Ce.lazy(()=>gt(()=>import("./Scene2DCanvas-Gw6nYE44.js"),__vite__mapDeps([39,3,1,4,40])).then(n=>({default:n.Scene2DCanvas}))),OV=Ce.lazy(()=>gt(()=>import("./index-D-GeyVri.js"),__vite__mapDeps([41,3,1,4,42])).then(n=>({default:n.DashboardView}))),LV=Ce.lazy(()=>gt(()=>import("./IframeModal-CUUf2I-4.js"),__vite__mapDeps([43,3,1,4,44])).then(n=>({default:n.IframeModal})));function PV(){const{t:n}=ut(["common","notifications"]),e=x.useRef(null),t=x.useRef(null),s=xs(),a=xs(),r=xs(),i=xs(),c=xs(),d=xs(),f=xs(),h=xs(),m=xs(),b=xs(),y=xs(),v=xs(),S=xs(),N=xs(),k=xs(),C=xs(),A=WD(),E=eL(),D=VD(),[_,F]=x.useState(null),P=HR(),[T,M]=x.useState(!1),[R,O]=x.useState(null),[U,H]=x.useState(null),[I,$]=x.useState(null),[z,q]=x.useState(null),[Y,B]=x.useState(null),[G,te]=x.useState(null),[V,ge]=x.useState(null),[he,J]=x.useState(null),[de,je]=x.useState(null),[xe,qe]=x.useState(null),Ke=x.useCallback(Se=>{qe(Se),Se&&localStorage.setItem("tide-commander-last-database-building",Se)},[]),We=x.useCallback(()=>Ke(null),[Ke]),{handleMouseDown:Me,handleClick:ye}=Sa(We),Fe=x.useCallback(()=>je(null),[]),{handleMouseDown:Q,handleClick:Re}=Sa(Fe),pe=x.useRef(G);pe.current=G;const Ie=x.useCallback(Se=>{te(Se)},[]),Ne=x.useCallback(()=>pe.current,[]),fe=x.useRef(null),[Ue,rt]=x.useState(bj),[ct,oe]=x.useState(0),[Z,ae]=x.useState(!1),[be,ee]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[ce,Ve]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-view")==="tracking"?"tracking":"agents"),[we,ie]=x.useState(!1),[X,_e]=x.useState(!1),me=_j(),le=Dj(),De=ox(),Qe=lx(),se=Tj(),{showToast:Ee}=Oj(),{showAgentNotification:He}=BL(),{showBackNavModal:Ye,setShowBackNavModal:tt,handleLeave:at}=dO();JR({showToast:Ee,showAgentNotification:He});const[pt,Mt]=x.useState(!1);x.useEffect(()=>{const Se=nt=>{var wt;((wt=nt.detail)==null?void 0:wt.mode)==="3d"&&Mt(!0)};return window.addEventListener("tide:viewmode-switch-pressed",Se),()=>{window.removeEventListener("tide:viewmode-switch-pressed",Se)}},[]),x.useEffect(()=>{le==="3d"&&Mt(!0)},[le]);const Ze=XR({canvasRef:e,selectionBoxRef:t,viewMode:le,sceneMountKey:ct,showToast:Ee,showAgentNotification:He,toolboxModal:i,contextMenu:D,setHoveredAgentPopup:B,setBuildingPopup:Ie,getBuildingPopup:Ne,openBuildingModal:Se=>N.open(Se),openPM2LogsModal:Se=>ge(Se),openBossLogsModal:Se=>J(Se),openDatabasePanel:Se=>Ke(Se),onSceneLoadingChange:Mt}),lt=Sj(),xt=Pa(),Tt=ix(),en=rx(),Fn=KO(),Tn=YO(),qn=GO(),is=Br(),pn=x.useMemo(()=>Array.from(en),[en]),Dn=x.useRef(!1);oj("AppContent"),ZR(Ze),eO(Ze),tO(Ze),hO(),nO(Ze,Tn),sO(Ze,is.powerSaving),x.useEffect(()=>{var Se;document.title=((Se=is.tabTitle)==null?void 0:Se.trim())||"Tide Commander"},[is.tabTitle]),x.useEffect(()=>{var ls,Rn;if(Dn.current||typeof window>"u")return;const Se=new URLSearchParams(window.location.search),nt=(ls=Se.get("agentId"))==null?void 0:ls.trim(),yt=(Rn=Se.get("agentName"))==null?void 0:Rn.trim();if(!nt&&!yt||lt===0)return;const wt=W.getState().agents,ss=Se.get("openTerminal"),hn=ss?["1","true","yes"].includes(ss.toLowerCase()):!0;let kt=nt?wt.get(nt):void 0;if(!kt&&yt){const ur=yt.toLowerCase();kt=Array.from(wt.values()).find(Ti=>Ti.name.toLowerCase()===ur)}if(!kt){console.warn("[DeepLink] No matching agent found for query params",{rawAgentId:nt,rawAgentName:yt}),Dn.current=!0;return}W.selectAgent(kt.id),hn&&W.setTerminalOpen(!0),Se.delete("agentId"),Se.delete("agentName"),Se.delete("openTerminal");const wn=Se.toString(),bs=`${window.location.pathname}${wn?`?${wn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,bs),Dn.current=!0},[lt]),uO({sceneRef:Ze,spawnModal:s,commanderModal:c,explorerModal:A,spotlightModal:f,deleteConfirmModal:d,onRequestBuildingDelete:()=>q("selected"),onOpenDatabasePanel:Ke,onCloseDatabasePanel:We,databasePanelOpen:xe!==null}),Jt("spawn-modal",s.isOpen,s.close),Jt("boss-spawn-modal",a.isOpen,a.close),Jt("subordinate-modal",r.isOpen,r.close),Jt("toolbox-modal",i.isOpen,i.close),Jt("commander-modal",c.isOpen,c.close),Jt("delete-confirm-modal",d.isOpen,d.close),Jt("spotlight-modal",f.isOpen,f.close),Jt("controls-modal",h.isOpen,h.close),Jt("skills-modal",m.isOpen,m.close),Jt("integrations-modal",b.isOpen,b.close),Jt("monitoring-modal",y.isOpen,y.close),Jt("workflow-editor-modal",v.isOpen,v.close),Jt("trigger-manager-modal",S.isOpen,S.close),Jt("building-modal",N.isOpen,N.close),Jt("agent-edit-modal",k.isOpen,k.close),Jt("explorer-modal",A.isOpen||E!==null,()=>{A.close(),W.closeFileExplorer()}),Jt("context-menu",D.isOpen,D.close),Jt("mobile-sidebar",Z,()=>ae(!1)),Jt("mobile-fab-menu",X,()=>_e(!1)),Jt("file-viewer",De!==null,()=>W.clearFileViewerPath()),Jt("context-modal",Qe!==null,()=>W.closeContextModal()),Jt("terminal",se,()=>W.setTerminalOpen(!1)),Jt("pm2-logs-modal",V!==null,()=>ge(null)),Jt("boss-logs-modal",he!==null,()=>J(null)),Jt("database-panel",xe!==null,We),Jt("terminal-modal",de!==null,Fe);const it=x.useRef(se),At=x.useRef(m),ln=x.useRef(h);At.current=m,ln.current=h,x.useEffect(()=>{it.current&&!se&&(At.current.close(),ln.current.close()),it.current=se},[se]),x.useEffect(()=>{},[]),x.useEffect(()=>{if(me!=="3d"||le!=="3d")return;const Se=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(Se)},[me,le]);const nn=x.useCallback(Se=>{var nt,yt,wt,ss,hn,kt,wn,bs,ls,Rn;rt(Se),KR(Se),(nt=Ze.current)==null||nt.setCharacterScale(Se.characterScale),(yt=Ze.current)==null||yt.setScale3D(Se.scale3d),(wt=Ze.current)==null||wt.setTimeMode(Se.timeMode),(ss=Ze.current)==null||ss.setTerrainConfig(Se.terrain),(hn=Ze.current)==null||hn.setFloorStyle(Se.terrain.floorStyle),(kt=Ze.current)==null||kt.setGridVisible(Se.gridVisible),(wn=Ze.current)==null||wn.setAgentModelStyle(Se.modelStyle),(bs=Ze.current)==null||bs.setIdleAnimation(Se.animations.idleAnimation),(ls=Ze.current)==null||ls.setWorkingAnimation(Se.animations.workingAnimation),(Rn=Ze.current)==null||Rn.setFpsLimit(Se.fpsLimit)},[Ze]),os=x.useCallback(Se=>{var nt;if((nt=Ze.current)==null||nt.setDrawingTool(Se),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(Se),Se==="rectangle"||Se==="circle"){const yt=n(Se==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");Ee("info",yt,n("notifications:drawing.clickAndDrag"),3e3)}},[Ze,Ee]),ms=x.useCallback(Se=>{var nt;(nt=Ze.current)==null||nt.focusAgent(Se)},[Ze]),ts=x.useCallback(Se=>{W.killAgent(Se)},[]),ia=x.useCallback(Se=>{var nt;(nt=Ze.current)==null||nt.callSubordinates(Se)},[Ze]),Rt=x.useCallback(Se=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(Se),W.setTerminalOpen(!0)},[]),gs=x.useCallback(Se=>{A.open(Se)},[A]),ns=x.useCallback(()=>{N.open(null)},[N]),$s=x.useCallback(()=>{var Se;(Se=Ze.current)==null||Se.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),Ee("info",n("notifications:drawing.rectangleTool"),n("notifications:drawing.clickAndDrag"),3e3)},[Ze,Ee]),Hs=x.useCallback(Se=>{F(Se)},[]),_n=x.useCallback(()=>{F(null)},[]),Fa=x.useCallback(()=>{const Se=Array.from(W.getState().selectedAgentIds);Se.forEach(nt=>{var yt;W.removeAgentFromServer(nt),(yt=Ze.current)==null||yt.removeAgent(nt)}),d.close(),Ee("info",n("notifications:toast.agentsRemoved"),n("notifications:toast.agentsRemovedMsg",{count:Se.length}))},[Ee,d,Ze,n]),Ur=x.useCallback(()=>{var Se,nt;if(z==="selected"){const yt=Fn.size;W.deleteSelectedBuildings(),(Se=Ze.current)==null||Se.syncBuildings(),Ee("info",n("notifications:toast.buildingsDeleted"),n("notifications:toast.buildingsDeletedMsg",{count:yt}))}else if(z){const yt=Tt.get(z);W.deleteBuilding(z),(nt=Ze.current)==null||nt.syncBuildings(),Ee("info",n("notifications:toast.buildingDeleted"),n("notifications:toast.buildingDeletedMsg",{name:(yt==null?void 0:yt.name)||"Building"}))}q(null)},[z,Tt,Fn.size,Ee,Ze,n]),Aa=x.useMemo(()=>TV(D.worldPosition,D.target,W.getState().agents,xt,Tt,{showToast:Ee,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:Se=>A.open(Se),openBuildingModal:Se=>N.open(Se),openAgentEditModal:Se=>k.open(Se),requestBuildingDelete:Se=>q(Se),setSpawnPosition:O,openRestoreArchivedModal:Se=>C.open(Se),sceneRef:Ze}),[D.worldPosition,D.target,xt,Tt,s,a,N,i,c,A,k,C,Ee,Ze]);x.useEffect(()=>{!s.isOpen&&!a.isOpen&&(O(null),$(null))},[s.isOpen,a.isOpen]),x.useEffect(()=>{const Se=hn=>{const kt=hn.detail;$((kt==null?void 0:kt.areaId)||null),O((kt==null?void 0:kt.position)||null),s.open()},nt=hn=>{var bs,ls;const kt=hn.detail;if(!(kt!=null&&kt.buildingId))return;const wn=W.getState().buildings.get(kt.buildingId);wn&&(wn.type==="server"&&((bs=wn.pm2)!=null&&bs.enabled)?ge(kt.buildingId):wn.type==="boss"?J(kt.buildingId):wn.type==="database"?Ke(kt.buildingId):wn.type==="folder"&&wn.folderPath?W.openFileExplorer(wn.folderPath):wn.type==="terminal"&&((ls=wn.terminalStatus)!=null&&ls.url)?je(kt.buildingId):N.open(kt.buildingId))},yt=hn=>{const kt=hn.detail;kt!=null&&kt.buildingId&&N.open(kt.buildingId)},wt=hn=>{const kt=hn.detail;H((kt==null?void 0:kt.position)||null),N.open(null)},ss=hn=>{const kt=hn.detail;kt!=null&&kt.buildingId?je(kt.buildingId):kt!=null&&kt.url&&F(kt.url)};return window.addEventListener("tide:open-spawn-modal",Se),window.addEventListener("tide:building-action",nt),window.addEventListener("tide:building-edit",yt),window.addEventListener("tide:building-create",wt),window.addEventListener("tide:open-iframe-modal",ss),()=>{window.removeEventListener("tide:open-spawn-modal",Se),window.removeEventListener("tide:building-action",nt),window.removeEventListener("tide:building-edit",yt),window.removeEventListener("tide:building-create",wt),window.removeEventListener("tide:open-iframe-modal",ss)}},[s,N]);const oa=qn==="rectangle"||qn==="circle",Il=x.useCallback(()=>{var Se;(Se=Ze.current)==null||Se.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ze]),_s=x.useCallback(()=>_e(Se=>!Se),[]),lr=x.useCallback(()=>W.setMobileView("terminal"),[]),cr=x.useCallback(()=>ae(!0),[]);return o.jsxs("div",{className:`app ${se?"terminal-open":""} ${oa?"drawing-mode":""} ${be?"sidebar-collapsed":""} mobile-view-${me} view-mode-${le}`,children:[o.jsx(CV,{}),o.jsx(AV,{onCreateAgent:s.open}),o.jsx(JW,{visible:is.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(tV,{className:"app-view-mode-toggle"}),o.jsx(hj,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:T,title:"Auto-organize all agents in their areas",onClick:()=>{M(!0),NV().then(Se=>{AT(Se,Ze),Ee("success","Organized",`Arranged ${Se.organized.length} agent${Se.organized.length!==1?"s":""}`)}).catch(Se=>{console.error("organize all error:",Se),Ee("error","Organize Failed",Se.message||"Failed to organize")}).finally(()=>M(!1))},children:[T?"⏳":"✨"," Organize"]})]}),o.jsxs("main",{className:"main-content",children:[o.jsxs("div",{className:"battlefield-container",children:[P&&o.jsxs("div",{className:"workspace-switch-overlay",children:[o.jsx("div",{className:"workspace-switch-spinner"}),o.jsx("span",{className:"workspace-switch-text",children:"Switching workspace..."})]}),o.jsx(Ce.Suspense,{fallback:null,children:le==="dashboard"?o.jsx(OV,{onSelectAgent:Se=>W.selectAgent(Se),onFocusAgent:Se=>{W.setViewMode("3d"),ms(Se)},onKillAgent:ts,onSelectBuilding:Se=>W.selectBuilding(Se),onOpenTerminal:Se=>{W.selectAgent(Se),W.setTerminalOpen(!0)},onFocusZone:Se=>{W.setViewMode("3d");const nt=W.getState().areas.get(Se);nt&&nt.assignedAgentIds.length>0&&ms(nt.assignedAgentIds[0])}}):le==="2d"?o.jsx(RV,{onAgentClick:(Se,nt)=>{nt?W.addToSelection(Se):W.selectAgent(Se)},onAgentDoubleClick:Se=>{if(window.innerWidth<=768){W.openTerminalOnMobile(Se);return}W.selectAgent(Se),W.setTerminalOpen(!0)},onBuildingClick:(Se,nt)=>{W.selectBuilding(Se);const yt=W.getState().buildings.get(Se);(yt==null?void 0:yt.type)==="folder"&&yt.folderPath?W.openFileExplorer(yt.folderPath):((yt==null?void 0:yt.type)==="server"||(yt==null?void 0:yt.type)==="boss"||(yt==null?void 0:yt.type)==="database")&&(fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>{Ie({buildingId:Se,screenPos:nt,fromClick:!0}),fe.current=null},150))},onBuildingDoubleClick:Se=>{var yt;fe.current&&(clearTimeout(fe.current),fe.current=null),Ie(null);const nt=W.getState().buildings.get(Se);(nt==null?void 0:nt.type)==="server"&&((yt=nt.pm2)!=null&&yt.enabled)?ge(Se):(nt==null?void 0:nt.type)==="boss"?J(Se):(nt==null?void 0:nt.type)==="database"?Ke(Se):(nt==null?void 0:nt.type)==="folder"&&nt.folderPath?W.openFileExplorer(nt.folderPath):N.open(Se)},onGroundClick:()=>{W.selectAgent(null),W.selectBuilding(null)},onAreaDoubleClick:Se=>{W.selectArea(Se),i.open()},onContextMenu:(Se,nt,yt)=>{const wt=yt?{type:yt.type,id:yt.id}:{type:"ground"};D.open(Se,nt,wt)},onMoveCommand:(Se,nt)=>{const wt=Se.length,ss=[];if(wt===1)ss.push({x:nt.x,y:0,z:nt.z});else if(wt<=6){const hn=1.2*Math.max(1,wt/3);for(let kt=0;kt<wt;kt++){const wn=kt/wt*Math.PI*2-Math.PI/2;ss.push({x:nt.x+Math.cos(wn)*hn,y:0,z:nt.z+Math.sin(wn)*hn})}}else{const hn=Math.ceil(Math.sqrt(wt)),kt=Math.ceil(wt/hn),wn=(hn-1)*1.2/2,bs=(kt-1)*1.2/2;for(let ls=0;ls<wt;ls++){const Rn=ls%hn,ur=Math.floor(ls/hn);ss.push({x:nt.x+Rn*1.2-wn,y:0,z:nt.z+ur*1.2-bs})}}Se.forEach((hn,kt)=>{W.moveAgent(hn,ss[kt])})},onBuildingDragMove:(Se,nt)=>{var wt;const yt=W.getState().buildings.get(Se);yt&&(W.getState().buildings.set(Se,{...yt,position:{x:nt.x,z:nt.z}}),(wt=window.__tideScene2D)==null||wt.syncBuildings())},onBuildingDragEnd:(Se,nt)=>{W.updateBuildingPosition(Se,nt)},scale2d:Ue.scale2d,showTaskLabels:Ue.show2DTaskLabels,showGrid:Ue.gridVisible,fpsLimit:Ue.fpsLimit}):o.jsxs(Ce.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:t,id:"selection-box"})]},ct)}),pt&&o.jsxs("div",{className:"scene-loading-overlay",children:[o.jsx("div",{className:"scene-loading-overlay__spinner"}),o.jsx("span",{className:"scene-loading-overlay__label",children:"Loading 3D scene…"})]})]}),o.jsx(nV,{isOpen:X,onToggle:_s,onShowTerminal:lr,onOpenSidebar:cr,onOpenToolbox:i.open,onOpenCommander:c.open,onOpenControls:h.open,onOpenSkills:m.open,mobileView:me}),Z&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>ae(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${be?"is-collapsed":""} ${we?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)ae(!Z);else{const nt=!be;ee(nt),localStorage.setItem("tide-commander-sidebar-collapsed",String(nt))}},title:be?"Open sidebar":"Close sidebar",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:we?o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"10",r:"3"}),o.jsx("line",{x1:"12",y1:"13",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]}):o.jsx("polyline",{points:be?"15 18 9 12 15 6":"9 18 15 12 9 6"})})}),o.jsxs("aside",{className:`sidebar ${Z?"sidebar-open":""} ${be?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>ae(!1),title:"Close sidebar",children:"✕"}),o.jsxs("div",{className:"sidebar-view-toggle",role:"tablist","aria-label":"Sidebar view",children:[o.jsx("button",{type:"button",role:"tab","aria-selected":ce==="agents",className:`sidebar-view-toggle-btn${ce==="agents"?" active":""}`,onClick:()=>{Ve("agents"),localStorage.setItem("tide-commander-sidebar-view","agents")},title:n("common:sidebar.agentsView",{defaultValue:"Agents"}),children:n("common:sidebar.agentsView",{defaultValue:"Agents"})}),o.jsxs("button",{type:"button",role:"tab","aria-selected":ce==="tracking",className:`sidebar-view-toggle-btn${ce==="tracking"?" active":""}`,onClick:()=>{Ve("tracking"),localStorage.setItem("tide-commander-sidebar-view","tracking")},title:n("common:sidebar.trackingBoard",{defaultValue:"Tracking Board"}),children:[o.jsx("span",{className:"sidebar-view-toggle-icon",children:"▥"}),n("common:sidebar.trackingBoard",{defaultValue:"Tracking Board"})]})]}),ce==="tracking"?o.jsx("div",{className:"sidebar-section sidebar-tracking-section",children:o.jsx("div",{className:"sidebar-tracking-body",children:o.jsx(Hj,{activeAgentId:pn[0]??"",onSelectAgent:Rt})})}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:pb,children:o.jsx(aP,{onFocusAgent:ms,onKillAgent:ts,onCallSubordinates:ia,onOpenAreaExplorer:gs})})})]}),o.jsx(x.Profiler,{id:"GuakeOutputPanel",onRender:pb,children:o.jsx(DW,{})})]}),o.jsx(sV,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenControls:h.open,onOpenSkills:m.open,onSpawnAgent:s.open,onSpawnBoss:a.open,onNewBuilding:ns,onNewArea:$s}),o.jsx(UW,{activeTool:qn,onExit:Il}),Y&&(()=>{const Se=W.getState().agents.get(Y.agentId);return Se?o.jsx(VW,{agent:Se,screenPos:Y.screenPos,onClose:()=>B(null)}):null})(),G&&(()=>{const Se=Tt.get(G.buildingId);if(!Se)return null;const nt=()=>Ie(null);return Se.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:nt}),o.jsx(QW,{building:Se,screenPos:G.screenPos,onClose:nt,onOpenSettings:()=>{nt(),N.open(G.buildingId)},onOpenLogsModal:()=>{nt(),J(G.buildingId)},onOpenUrlInModal:Hs})]}):Se.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:nt}),o.jsx(XW,{building:Se,screenPos:G.screenPos,onClose:nt,onOpenSettings:()=>{nt(),N.open(G.buildingId)},onOpenDatabasePanel:()=>{nt(),Ke(G.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:nt}),o.jsx(GW,{building:Se,screenPos:G.screenPos,onClose:nt,onOpenSettings:()=>{nt(),N.open(G.buildingId)},onOpenLogsModal:()=>{ge(G.buildingId)},onOpenUrlInModal:Hs})]})})(),V&&(()=>{var nt;const Se=Tt.get(V);return Se?(nt=Se.docker)!=null&&nt.enabled?o.jsx(MV,{building:Se,isOpen:!0,onClose:()=>ge(null)}):o.jsx(EV,{building:Se,isOpen:!0,onClose:()=>ge(null)}):null})(),he&&(()=>{const Se=Tt.get(he);return Se?o.jsx(DV,{building:Se,isOpen:!0,onClose:()=>J(null)}):null})(),xe&&(()=>{const Se=Tt.get(xe);return Se?o.jsx("div",{className:"modal-overlay visible",onMouseDown:Me,onClick:ye,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(_V,{building:Se,onClose:We})})}):null})(),de&&(()=>{var nt;const Se=Tt.get(de);return!Se||!((nt=Se.terminalStatus)!=null&&nt.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:Q,onClick:Re,children:o.jsxs("div",{className:"terminal-modal-container",children:[o.jsxs("div",{className:"terminal-modal-header",children:[o.jsxs("span",{className:"terminal-modal-title",children:["Terminal - ",Se.name]}),o.jsx("button",{className:"terminal-modal-close",onClick:Fe,children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx(Hb,{terminalUrl:Se.terminalStatus.url,visible:!0})]})})})(),o.jsx(LV,{url:_||"",title:_?`Preview - ${_}`:"",isOpen:!!_,onClose:_n}),o.jsx(HW,{onFocusAgent:ms,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:ns,onNewAreaClick:$s}),o.jsx(vV,{spawnModal:s,bossSpawnModal:a,subordinateModal:r,toolboxModal:i,commanderModal:c,deleteConfirmModal:d,spotlightModal:f,controlsModal:h,skillsModal:m,integrationsModal:b,monitoringModal:y,workflowEditorModal:v,triggerManagerModal:S,buildingModal:N,buildingInitialPosition:U,agentEditModal:k,restoreArchivedModal:C,explorerModal:A,contextMenu:D,spawnPosition:R,spawnAreaId:I,explorerFolderPath:E,contextMenuActions:Aa,sceneConfig:Ue,onConfigChange:nn,onToolChange:os,onOpenAreaExplorer:gs,onDeleteSelectedAgents:Fa,pendingBuildingDelete:z,onCancelBuildingDelete:()=>q(null),onConfirmBuildingDelete:Ur,showBackNavModal:Ye,onCloseBackNavModal:()=>tt(!1),onLeave:at,onOpenPM2LogsModal:Se=>ge(Se),onOpenBossLogsModal:Se=>J(Se),onOpenDatabasePanel:Se=>Ke(Se),onSyncScene:()=>{var Se,nt;(Se=Ze.current)==null||Se.syncAreas(),(nt=Ze.current)==null||nt.syncAgents(Array.from(W.getState().agents.values()))}})]})}function IV(){return o.jsx(CL,{children:o.jsx(IL,{children:o.jsx(PV,{})})})}class BV extends x.Component{constructor(t){super(t);et(this,"handleReload",()=>{window.location.reload()});et(this,"handleDismiss",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){console.error("[Tide] React Error:",t,s),this.setState({errorInfo:s})}render(){if(this.state.hasError){const{error:t,errorInfo:s}=this.state;return o.jsx("div",{style:{position:"fixed",inset:0,background:"#1a1a2e",color:"#fff",fontFamily:"monospace",padding:"32px",overflow:"auto",zIndex:99999},children:o.jsxs("div",{style:{maxWidth:"900px",margin:"0 auto"},children:[o.jsxs("h1",{style:{color:"#ff4a4a",fontSize:"24px",marginBottom:"16px",display:"flex",alignItems:"center",gap:"12px"},children:[o.jsx("span",{style:{fontSize:"32px"},children:"💥"}),Sn.t("errors:crash.title")]}),o.jsx("div",{style:{background:"#2a2a3e",borderRadius:"8px",padding:"16px",marginBottom:"16px"},children:o.jsxs("div",{style:{color:"#ff6b6b",fontSize:"18px",marginBottom:"8px"},children:[t==null?void 0:t.name,": ",t==null?void 0:t.message]})}),o.jsxs("div",{style:{background:"#2a2a3e",borderRadius:"8px",padding:"16px",marginBottom:"16px"},children:[o.jsx("div",{style:{color:"#888",marginBottom:"8px",fontSize:"12px"},children:Sn.t("errors:crash.stackTrace")}),o.jsx("pre",{style:{color:"#ccc",fontSize:"12px",lineHeight:"1.5",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:t==null?void 0:t.stack})]}),(s==null?void 0:s.componentStack)&&o.jsxs("div",{style:{background:"#2a2a3e",borderRadius:"8px",padding:"16px",marginBottom:"16px"},children:[o.jsx("div",{style:{color:"#888",marginBottom:"8px",fontSize:"12px"},children:Sn.t("errors:crash.componentStack")}),o.jsx("pre",{style:{color:"#ccc",fontSize:"12px",lineHeight:"1.5",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:s.componentStack})]}),o.jsxs("div",{style:{display:"flex",gap:"12px"},children:[o.jsx("button",{onClick:this.handleReload,style:{background:"#4a9eff",color:"#fff",border:"none",borderRadius:"6px",padding:"12px 24px",fontSize:"14px",cursor:"pointer"},children:Sn.t("common:buttons.reloadPage")}),o.jsx("button",{onClick:this.handleDismiss,style:{background:"#444",color:"#fff",border:"none",borderRadius:"6px",padding:"12px 24px",fontSize:"14px",cursor:"pointer"},children:Sn.t("common:buttons.tryToContinue")})]}),o.jsx("div",{style:{marginTop:"24px",color:"#666",fontSize:"12px"},children:Sn.t("errors:crash.checkConsole")})]})})}return this.props.children}}R9();document.addEventListener("wheel",n=>{if(Math.abs(n.deltaX)>Math.abs(n.deltaY)&&Math.abs(n.deltaX)>0){const e=n.target;if(e.tagName==="CANVAS"){n.preventDefault();return}let t=e;for(;t&&t!==document.documentElement;){if(t.scrollWidth>t.clientWidth)return;t=t.parentElement}n.preventDefault()}},{passive:!1});const jT=document.getElementById("app");if(!jT)throw new Error("Could not find #app container");const FV=vM.createRoot(jT);FV.render(o.jsx(Ce.StrictMode,{children:o.jsx(x.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(BV,{children:o.jsx(IV,{})})})}));console.log("[Tide] Tide Commander initialized");export{Rc as $,NL as A,ux as B,Nn as C,jL as D,zD as E,xq as F,fp as G,Vb as H,Rl as I,ix as J,Pa as K,rx as L,nL as M,Ia as N,ZV as O,TL as P,yq as Q,n9 as R,dt as S,rs as T,ka as U,fq as V,Lt as W,Fj as X,vq as Y,R2 as Z,nu as _,cx as a,sa as a$,Xd as a0,rg as a1,er as a2,bp as a3,dq as a4,mo as a5,Bf as a6,VV as a7,AL as a8,ob as a9,FD as aA,iW as aB,x6 as aC,y6 as aD,S6 as aE,nq as aF,VO as aG,Gb as aH,Yb as aI,jf as aJ,kq as aK,gt as aL,BN as aM,wq as aN,FN as aO,zN as aP,ou as aQ,Ns as aR,Ts as aS,N6 as aT,T6 as aU,Oj as aV,$g as aW,_6 as aX,co as aY,Dp as aZ,IN as a_,oq as aa,Ir as ab,WV as ac,aq as ad,Nx as ae,Xs as af,su as ag,Jf as ah,ra as ai,Ba as aj,Kb as ak,UD as al,Sn as am,RR as an,HD as ao,lq as ap,cq as aq,uq as ar,iq as as,iL as at,Ok as au,Cj as av,Jt as aw,u5 as ax,ZN as ay,fx as az,fL as b,Wj as b0,D6 as b1,qx as b2,Bb as b3,o6 as b4,tL as b5,gb as b6,eq as b7,tq as b8,oO as b9,lO as ba,D2 as bb,JV as bc,QV as bd,sq as be,ax as bf,GL as bg,T2 as bh,E2 as bi,pq as bj,Au as bk,_L as bl,hq as bm,bq as bn,mq as bo,XV as bp,KV as bq,gq as br,OR as bs,LR as bt,Ec as bu,Qb as bv,rq as c,pL as d,jx as e,Fs as f,r9 as g,Sa as h,Sl as i,o as j,fu as k,Et as l,Yk as m,xn as n,ea as o,GV as p,qV as q,x as r,W as s,qd as t,ut as u,hp as v,YV as w,zR as x,$R as y,Ce as z};
144
+ `):[],[y]),S=x.useMemo(()=>v.map(A=>Sl(A||" ")),[v]),N=x.useMemo(()=>b?f&&!y?"No log lines match the current filter.":null:"Waiting for logs...",[b,f,y]),k=Wj({count:S.length,getScrollElement:()=>i.current,estimateSize:()=>20,overscan:12,measureElement:A=>A.getBoundingClientRect().height}),C=k.getVirtualItems();return o.jsx("div",{ref:i,className:"guake-bottom-pm2-logs",onScroll:m,children:N?o.jsx("div",{className:"guake-bottom-pm2-logs-empty",children:N}):o.jsx("div",{className:"guake-bottom-pm2-logs-inner",style:{height:k.getTotalSize()},children:C.map(A=>o.jsx("div",{ref:k.measureElement,className:"guake-bottom-pm2-log-line","data-index":A.index,style:{transform:`translateY(${A.start}px)`},dangerouslySetInnerHTML:{__html:S[A.index]}},A.key))})})});x.memo(function({src:e,title:t}){const s=x.useRef(null),[a,r]=x.useState(!1),[i,c]=x.useState(null);x.useEffect(()=>{r(!1),c(null);const h=setTimeout(()=>c(e),400);return()=>clearTimeout(h)},[e]);const d=x.useCallback(()=>{var m;const h=s.current;if(h){document.activeElement===h&&h.blur();try{(m=h.contentWindow)==null||m.blur()}catch{}}},[]),f=x.useCallback(()=>{const h=document.querySelector(".guake-input-container"),m=h==null?void 0:h.querySelector("textarea, input");h==null||h.focus({preventScroll:!0}),m==null||m.focus({preventScroll:!0})},[]);return x.useEffect(()=>{if(!i)return;const h=Date.now(),m=()=>{Date.now()-h>1500||(d(),f())};return window.addEventListener("focus",m,!0),document.addEventListener("focusin",m,!0),()=>{window.removeEventListener("focus",m,!0),document.removeEventListener("focusin",m,!0)}},[f,d,i]),o.jsxs(o.Fragment,{children:[!a&&o.jsx("div",{className:"guake-bottom-terminal-starting",children:o.jsx("span",{children:"Loading terminal..."})}),o.jsx("iframe",{ref:s,src:i??void 0,className:`guake-bottom-terminal-iframe${a?"":" iframe-loading"}`,title:t,allow:"clipboard-read; clipboard-write",loading:"lazy",tabIndex:-1,onLoad:()=>{r(!0),d(),f()}})]})});const DW=x.memo(function(){var la,wo,ko,dr,fr,Fl,So,zl,Gr,ca,Co,Yr,ja;const{t:e}=ut(["terminal","common"]),t=Rl(),s=rx(),a=Tj(),r=_j(),i=ox(),c=lx(),d=Array.from(s),h=d.length===1?d[0]:null,b=mo(h)||null,y=h,v=xL(),S=x.useCallback(ne=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(ne)},[]),N=Pa(),k=ix(),C=x.useMemo(()=>{if(!y)return null;const ne=new Set,Te=[];for(const $e of N.values())$e.archived||$e.directories.length===0||$e.assignedAgentIds.includes(y)&&(ne.add($e.id),Te.push($e));const ve=t.get(y);if(ve)for(const $e of N.values())$e.archived||$e.directories.length===0||ne.has($e.id)||_W({x:ve.position.x,z:ve.position.z},$e)&&(ne.add($e.id),Te.push($e));return Te.length===0?null:Te.flatMap($e=>$e.directories.filter(ft=>ft&&ft.trim().length>0).map(ft=>({areaId:$e.id,areaName:$e.name,dir:ft})))},[y,N,t]),A=x.useMemo(()=>{var ve;if(!y)return[];const ne=W.getAreaForAgent(y);if(!ne)return[];const Te=[];for(const $e of k.values())$e.type==="terminal"&&W.isPositionInArea($e.position,ne)&&Te.push({id:$e.id,name:$e.name,hasUrl:!!((ve=$e.terminalStatus)!=null&&ve.url)});return Te},[y,k,N]),E=x.useMemo(()=>{var ve;if(!y)return[];const ne=W.getAreaForAgent(y);if(!ne)return[];const Te=[];for(const $e of k.values())$e.type==="server"&&((ve=$e.pm2)!=null&&ve.enabled)&&W.isPositionInArea($e.position,ne)&&Te.push({id:$e.id,name:$e.name});return Te},[y,k,N]),D=x.useMemo(()=>{if(!y)return[];const ne=W.getAreaForAgent(y);if(!ne)return[];const Te=[];for(const ve of k.values())ve.type==="database"&&ve.database&&W.isPositionInArea(ve.position,ne)&&Te.push({id:ve.id,name:ve.name});return Te},[y,k,N]),{branches:_,fetchRemote:F,fetchingDirs:P}=h9(C),{terminalHeight:T,terminalRef:M,handleResizeStart:R}=l9(),{mobileOverviewHeight:O,handleResizeMouseDown:U,handleResizeTouchStart:H}=d9(),I=o9(),[$,z]=x.useState(()=>{const ne=Gb(dt.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,ne))}),q=x.useRef(null),Y=x.useCallback((ne,Te)=>{ne.preventDefault(),q.current={startX:ne.clientX,startW:$},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",W.setTerminalResizing(!0);let ve=$;const $e=jt=>{if(!q.current)return;const Ft=jt.clientX-q.current.startX,zt=Te==="left"?-Ft:Ft;ve=Math.max(280,Math.min(700,q.current.startW+zt)),z(ve)},ft=()=>{q.current=null,document.body.style.cursor="",document.body.style.userSelect="",W.setTerminalResizing(!1),document.removeEventListener("mousemove",$e),document.removeEventListener("mouseup",ft),Yb(dt.SIDE_PANEL_WIDTH,ve)};document.addEventListener("mousemove",$e),document.addEventListener("mouseup",ft)},[$]),B=x.useRef(null),G=x.useRef(null),[te,V]=x.useState(()=>{const ne=ka(dt.VIEW_MODE);return ne==="simple"||ne==="chat"||ne==="advanced"?ne:ka(dt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[ge,he]=x.useState(()=>hl(dt.TERMINAL_FULLSCREEN,!1)),[J,de]=x.useState(null),[je,xe]=x.useState(null),[qe,Ke]=x.useState(null),[We,Me]=x.useState(null),[ye,Fe]=x.useState(!1);Jt("guake-image-modal",J!==null,()=>de(null)),Jt("guake-bash-modal",je!==null,()=>xe(null)),Jt("guake-response-modal",We!==null,()=>Me(null)),Jt("guake-context-confirm",qe!==null,()=>Ke(null)),Jt("guake-agent-info",ye,()=>Fe(!1));const[Q,Re]=x.useState(!1),[pe,Ie]=x.useState(()=>ps.isEnabled()),[Ne,fe]=x.useState(()=>hl(dt.GIT_PANEL_OPEN,!1)),Ue=x.useCallback(ne=>{fe(ne),to(dt.GIT_PANEL_OPEN,ne)},[]),[rt,ct]=x.useState(()=>hl(dt.BUILDINGS_PANEL_OPEN,!1)),oe=x.useCallback(ne=>{ct(ne),to(dt.BUILDINGS_PANEL_OPEN,ne)},[]),[Z,ae]=x.useState(()=>hl(dt.WORKFLOW_PANEL_OPEN,!1)),be=x.useCallback(ne=>{ae(ne),to(dt.WORKFLOW_PANEL_OPEN,ne)},[]),[ee,ce]=x.useState(!1);x.useEffect(()=>{if(!y){ce(!1);return}let ne=!1;return(async()=>{try{const Te=await Lt(Et("/api/workflows/definitions"));if(ne||!Te.ok)return;const $e=(await Te.json()).some(ft=>ft.states.some(jt=>{var Ft,zt;return((Ft=jt.action)==null?void 0:Ft.type)==="agent_task"&&((zt=jt.action)==null?void 0:zt.agentId)===y}));ne||ce($e)}catch{ne||ce(!1)}})(),()=>{ne=!0}},[y]);const Ve=bL(),we=x.useCallback(ne=>W.setOverviewPanelOpen(ne),[]),[ie,X]=x.useState([]),[_e,me]=x.useState({}),[le,De]=x.useState(()=>wj()),[Qe,se]=x.useState(()=>{try{return localStorage.getItem("tide:bottom-split-direction")==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[Ee,He]=x.useState(()=>{try{const ne=localStorage.getItem("tide:bottom-terminal-height");return ne?Math.max(120,Math.min(600,Number(ne))):250}catch{return 250}}),Ye=x.useRef(null),[tt,at]=x.useState([1]),pt=x.useRef(null),Mt=x.useRef(null),[Ze,lt]=x.useState(null),[xt,Tt]=x.useState(null),en=x.useMemo(()=>ie.filter(ne=>ne.areaId===xt),[ie,xt]),Fn=x.useMemo(()=>new Set(en.map(ne=>ne.buildingId)),[en]),Tn=x.useRef(new Map);x.useEffect(()=>{try{const ne=localStorage.getItem("tide:bottom-panels-v2");if(ne){const Te=JSON.parse(ne);Tn.current=new Map(Te.map(([ve,$e])=>[ve,$e.map(ft=>({id:ft.id??gf(),type:ft.type,buildingId:ft.buildingId}))]))}else{const Te=localStorage.getItem("tide:bottom-terminals");if(Te){const ve=JSON.parse(Te);for(const[$e,ft]of ve)Tn.current.set($e,[{id:gf(),type:"terminal",buildingId:ft}])}}}catch{}},[]);const qn=x.useCallback(ne=>{if(!y)return;const Te=W.getAreaForAgent(y);if(Te)try{ne.length>0?Tn.current.set(Te.id,ne.map($e=>({id:$e.id,type:$e.type,buildingId:$e.buildingId}))):Tn.current.delete(Te.id);const ve=Array.from(Tn.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(ve))}catch{}},[y]),is=x.useCallback(()=>{if(!y)return null;const ne=W.getAreaForAgent(y);return(ne==null?void 0:ne.id)??null},[y]),pn=x.useCallback((ne,Te)=>{const ve=is();me({}),X($e=>{for(const zt of $e)zt.areaId===ve&&zt.type==="pm2-logs"&&W.stopLogStreaming(zt.buildingId);const ft=$e.filter(zt=>zt.areaId!==ve),jt={id:gf(),type:Te,buildingId:ne,areaId:ve??void 0},Ft=[...ft,jt];return qn([jt]),Ft})},[qn,is]),Dn=x.useCallback((ne,Te,ve)=>{const $e=is();se(ve);try{localStorage.setItem("tide:bottom-split-direction",ve)}catch{}X(ft=>{const jt=ft.filter(zn=>zn.areaId===$e);if(jt.length>=4||jt.some(zn=>zn.buildingId===ne))return ft;const Ft={id:gf(),type:Te,buildingId:ne,areaId:$e??void 0},zt=[...ft,Ft];return qn(jt.concat(Ft)),zt})},[qn,is]),it=x.useCallback(ne=>{me(Te=>{if(!(ne in Te))return Te;const ve={...Te};return delete ve[ne],ve}),X(Te=>{const ve=Te.find(jt=>jt.id===ne);(ve==null?void 0:ve.type)==="pm2-logs"&&W.stopLogStreaming(ve.buildingId);const $e=Te.filter(jt=>jt.id!==ne),ft=ve==null?void 0:ve.areaId;return ft&&qn($e.filter(jt=>jt.areaId===ft)),$e})},[qn]);x.useCallback(()=>{me({}),X(ne=>{for(const Te of ne)Te.type==="pm2-logs"&&W.stopLogStreaming(Te.buildingId);return qn([]),[]})},[qn]),x.useEffect(()=>{if(!y){Tt(null);return}const ne=W.getAreaForAgent(y);if(!ne){Tt(null);return}Tt(ne.id),X(Te=>{if(Te.filter(jt=>jt.areaId===ne.id).length>0)return Te;const $e=Tn.current.get(ne.id);if(!$e||$e.length===0)return Te;const ft=$e.map(jt=>({id:jt.id,type:jt.type,buildingId:jt.buildingId,areaId:ne.id}));return[...Te,...ft]})},[y]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&pn(ve.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",ne),()=>window.removeEventListener("tide:open-bottom-terminal",ne)},[pn]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&pn(ve.buildingId,"pm2-logs")};return window.addEventListener("tide:open-bottom-pm2-logs",ne),()=>window.removeEventListener("tide:open-bottom-pm2-logs",ne)},[pn]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&pn(ve.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",ne),()=>window.removeEventListener("tide:open-bottom-database",ne)},[pn]),x.useEffect(()=>{const ne=Te=>{const ve=Te.detail;ve!=null&&ve.buildingId&&(ve!=null&&ve.type)&&(ve!=null&&ve.direction)&&(en.length===0?pn(ve.buildingId,ve.type):Dn(ve.buildingId,ve.type,ve.direction))};return window.addEventListener("tide:split-bottom-panel",ne),()=>window.removeEventListener("tide:split-bottom-panel",ne)},[en.length,pn,Dn]),x.useEffect(()=>{at(ne=>ne.length===en.length?ne:en.length<=1?[1]:(en.length>ne.length,Array(en.length).fill(1)))},[en.length]);const At=x.useCallback((ne,Te)=>{var zn;ne.preventDefault();const ve=Qe==="horizontal";pt.current={index:Te,startPos:ve?ne.clientX:ne.clientY,startRatios:[...tt]},document.body.style.cursor=ve?"col-resize":"row-resize",document.body.style.userSelect="none";const $e=(zn=Mt.current)==null?void 0:zn.querySelectorAll("iframe");$e==null||$e.forEach(On=>On.style.pointerEvents="none");const ft=Mt.current,jt=ft?ve?ft.offsetWidth:ft.offsetHeight:1,Ft=On=>{const Na=pt.current;if(!Na||!ft)return;const $l=(ve?On.clientX:On.clientY)-Na.startPos,Kr=Na.startRatios.reduce((Pp,Ip)=>Pp+Ip,0),_i=$l/jt*Kr,Ao=[...Na.startRatios],Fu=.1*Kr;Ao[Te]=Math.max(Fu,Na.startRatios[Te]+_i),Ao[Te+1]=Math.max(Fu,Na.startRatios[Te+1]-_i),at(Ao)},zt=()=>{pt.current=null,document.body.style.cursor="",document.body.style.userSelect="",$e==null||$e.forEach(On=>On.style.pointerEvents=""),document.removeEventListener("mousemove",Ft),document.removeEventListener("mouseup",zt)};document.addEventListener("mousemove",Ft),document.addEventListener("mouseup",zt)},[Qe,tt]),ln=x.useRef(new Set);x.useEffect(()=>{const ne=new Set(ie.filter(Te=>Te.type==="pm2-logs").map(Te=>Te.buildingId));for(const Te of ne)ln.current.has(Te)||W.startLogStreaming(Te,200);ln.current=ne},[ie]);const nn=x.useRef(new Set);x.useEffect(()=>{var ve;const ne=ie.filter($e=>$e.type==="terminal");for(const $e of ne){const ft=k.get($e.buildingId);!!((ve=ft==null?void 0:ft.terminalStatus)!=null&&ve.url)?nn.current.add($e.buildingId):nn.current.has($e.buildingId)&&(nn.current.delete($e.buildingId),it($e.id))}const Te=new Set(ne.map($e=>$e.buildingId));for(const $e of nn.current)Te.has($e)||nn.current.delete($e)},[ie,k,it]);const os=x.useCallback(ne=>{ne.preventDefault(),Ye.current={startY:ne.clientY,startH:Ee};let Te=Ee;const ve=ft=>{if(!Ye.current)return;const jt=Ye.current.startY-ft.clientY;Te=Math.max(120,Math.min(600,Ye.current.startH+jt)),He(Te)},$e=()=>{Ye.current=null,document.removeEventListener("mousemove",ve),document.removeEventListener("mouseup",$e);try{localStorage.setItem("tide:bottom-terminal-height",String(Te))}catch{}};document.addEventListener("mousemove",ve),document.addEventListener("mouseup",$e)},[Ee]),[ms,ts]=x.useState(!1),ia=x.useRef(0),Rt=a&&b!==null,gs=x.useRef([]),ns=x.useRef(-1),$s=x.useRef(!1),Hs=x.useRef(!1),_n=x.useRef(!1),Fa=x.useRef(null),[Ur,Aa]=x.useState(!1),[oa,Il]=x.useState(!1),_s=x.useCallback(()=>{const ne=gs.current,Te=ns.current;Aa(Te>0),Il(Te>=0&&Te<ne.length-1)},[]),lr=x.useCallback(ne=>{const Te=gs.current;if(Te.length===0)return;let ve=ns.current+ne;for(;ve>=0&&ve<Te.length;){const $e=Te[ve];if(t.has($e)){$s.current=!0,ns.current=ve,_s(),W.selectAgent($e);return}ve+=ne}},[t,_s]),cr=x.useCallback(()=>{lr(-1)},[lr]),Se=x.useCallback(()=>{lr(1)},[lr]),nt=x.useCallback((ne,Te)=>{if(typeof window>"u")return;const ve=window.history.state,ft={...typeof ve=="object"&&ve!==null?ve:{},__guakeAgentNav:{agentId:ne}};Te==="replace"?window.history.replaceState(ft,"",window.location.href):window.history.pushState(ft,"",window.location.href)},[]),yt=x.useCallback(()=>{he(ne=>{const Te=!ne;return to(dt.TERMINAL_FULLSCREEN,Te),Te})},[]),wt=f9({agents:t,selectedAgentId:y,isOpen:Rt,overviewPanelOpen:Ve,loadingHistory:((la=B.current)==null?void 0:la.historyLoader.fetchingHistory)??!1,hasModalOpen:!!(J||je||We||i||c),outputRef:((wo=B.current)==null?void 0:wo.outputScrollRef)??{current:null}});x.useEffect(()=>{const ne=M.current;if(!ne||!Rt)return;const Te=$e=>{$e.button===3?($e.preventDefault(),$e.stopPropagation(),cr()):$e.button===4&&($e.preventDefault(),$e.stopPropagation(),Se())},ve=$e=>{($e.button===3||$e.button===4)&&$e.preventDefault()};return ne.addEventListener("mouseup",Te),ne.addEventListener("mousedown",ve),()=>{ne.removeEventListener("mouseup",Te),ne.removeEventListener("mousedown",ve)}},[Rt,cr,Se]);const ss=x.useCallback(ne=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(ne)},[]),hn=typeof window<"u"&&window.innerWidth<=768&&Ve&&Rt,kt=JD({gestureRef:((ko=B.current)==null?void 0:ko.outputScrollRef)??{current:null},agentListRef:G,enabled:hn,onSelect:ss});x.useEffect(()=>{Q&&!pe&&(Ie(!0),ps.setEnabled(!0))},[Q,pe]),x.useEffect(()=>{Rt||Fe(!1)},[Rt]),x.useEffect(()=>{var Te;if(!(je!=null&&je.isLive)||!je.command)return;const ne=((Te=B.current)==null?void 0:Te.getDedupedHistory())??[];for(const ve of ne)if(ve._bashCommand===je.command&&ve._bashOutput){xe({command:je.command,output:ve._bashOutput,isLive:!1});return}},[je]);const wn=x.useCallback((ne,Te)=>{de({url:ne,name:Te})},[]),bs=x.useCallback((ne,Te)=>{const ve=fx(ne,b==null?void 0:b.cwd),$e=ve.line?{...Te||{},targetLine:ve.line}:Te;W.setFileViewerPath(ve.path,$e,b==null?void 0:b.cwd)},[b==null?void 0:b.cwd]),ls=x.useCallback((ne,Te)=>{xe({command:ne,output:Te,isLive:Te==="Running..."})},[]),Rn=x.useCallback(ne=>{Me(ne)},[]),ur=x.useCallback(()=>{Fe(ne=>!ne)},[]),[Ti,Wr]=x.useState(0),[za,xo]=x.useState(!1),Pu=x.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(xo(!0),Wr(NW),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{W.setMobileView("3d"),xo(!1),Wr(0)},TW))},[]),Vr=x.useCallback(ne=>{za||Wr(ne)},[za]);x.useEffect(()=>{Wr(0),xo(!1)},[y]),x.useEffect(()=>{if(!y){gs.current=[],ns.current=-1,_s(),_n.current=!1,Fa.current=null;return}const ne=gs.current;if($s.current){$s.current=!1,_s();return}const Te=ns.current;if(Te>=0&&ne[Te]===y){_s();return}const ve=Te<ne.length-1?ne.slice(0,Te+1):ne.slice();ve.push(y),ve.length>100&&ve.shift(),gs.current=ve,ns.current=ve.length-1,_s()},[y,_s]),x.useEffect(()=>{if(!(!Rt||!y)){if(!_n.current){nt(y,"replace"),_n.current=!0,Fa.current=y;return}if(Hs.current){Hs.current=!1,Fa.current=y;return}Fa.current!==y&&(nt(y,"push"),Fa.current=y)}},[Rt,y,nt]),x.useEffect(()=>{if(!Rt)return;const ne=Te=>{var jt,Ft;const ve=(Ft=(jt=Te.state)==null?void 0:jt.__guakeAgentNav)==null?void 0:Ft.agentId;if(!ve||typeof ve!="string"||!t.has(ve)||ve===h)return;Hs.current=!0,$s.current=!0;const $e=gs.current,ft=$e.lastIndexOf(ve);ft>=0?ns.current=ft:($e.push(ve),ns.current=$e.length-1),_s(),W.selectAgent(ve)};return window.addEventListener("popstate",ne),()=>window.removeEventListener("popstate",ne)},[Rt,t,h,_s]),x.useEffect(()=>{Rt&&h&&W.clearUnseenForAgent(h)},[Rt,h]),x.useEffect(()=>{const ne=Te=>{if(Te.key==="`"&&!Te.ctrlKey&&!Te.altKey&&b){const ve=Te.target;ve.tagName!=="INPUT"&&ve.tagName!=="TEXTAREA"&&(Te.preventDefault(),W.toggleTerminal())}};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[b]),x.useEffect(()=>{if(!Rt)return;const ne=Te=>{Te.altKey&&(Te.key!=="ArrowLeft"&&Te.key!=="ArrowRight"||(Te.key==="ArrowLeft"&&Ur?(Te.preventDefault(),cr()):Te.key==="ArrowRight"&&oa&&(Te.preventDefault(),Se())))};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[Rt,Ur,oa,cr,Se]),x.useEffect(()=>{const ne=Te=>{var ve;Te.key==="Escape"&&(i?(Te.stopImmediatePropagation(),W.clearFileViewerPath()):c?(Te.stopImmediatePropagation(),W.closeContextModal()):We?(Te.stopImmediatePropagation(),Me(null)):je?(Te.stopImmediatePropagation(),xe(null)):J?(Te.stopImmediatePropagation(),de(null)):(ve=B.current)!=null&&ve.search.searchMode&&(Te.stopImmediatePropagation(),B.current.search.closeSearch()))};return document.addEventListener("keydown",ne,!0),()=>document.removeEventListener("keydown",ne,!0)},[J,je,We,i,c]);const Iu=x.useRef(Rt),qr=x.useRef(!1);x.useEffect(()=>{Iu.current=Rt},[Rt]),x.useEffect(()=>{if(window.innerWidth<=768)return;const Te=ft=>{var On;if(!(ft instanceof Element))return!1;const jt=(On=M.current)==null?void 0:On.contains(ft),Ft=ft.closest(".agent-bar"),zt=ft.closest(".sidebar, .sidebar-collapse-edge-btn"),zn=!!ft.closest(".modal-overlay, .modal, .image-modal-overlay, .image-modal, .bash-modal-overlay, .bash-modal, .agent-info-modal-overlay, .agent-info-modal, .agent-response-modal, .pasted-text-modal-overlay, .pasted-text-modal, .file-viewer-overlay, .file-viewer-modal, .context-view-modal, .guake-context-confirm-overlay, .guake-context-confirm-modal, .pm2-logs-modal-overlay, .pm2-logs-modal, .database-panel-modal, .context-menu, .guake-git-diff-modal-overlay, .guake-git-delete-confirm, .theme-selector-dropdown");return!!jt||!!Ft||!!zt||zn},ve=ft=>{if(!Iu.current){qr.current=!1;return}if(YD("terminal")){qr.current=!1;return}qr.current=!Te(ft.target)},$e=ft=>{qr.current&&(Te(ft.target)||W.setTerminalOpen(!1),qr.current=!1)};return document.addEventListener("mousedown",ve,!0),document.addEventListener("mouseup",$e,!0),()=>{document.removeEventListener("mousedown",ve,!0),document.removeEventListener("mouseup",$e,!0)}},[]),x.useEffect(()=>{const ne=()=>{document.hidden&&I.cleanup()};return document.addEventListener("visibilitychange",ne),()=>document.removeEventListener("visibilitychange",ne)},[I]),x.useEffect(()=>()=>I.cleanup(),[y,I]);const yo=typeof window<"u"&&window.innerWidth<=768;if(!b)return yo&&r==="terminal"&&s.size===0?o.jsx("div",{ref:M,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${T}%`},children:o.jsx("div",{className:"guake-content",children:o.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:o.jsxs("div",{style:{textAlign:"center"},children:[o.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"👆"}),o.jsx("div",{style:{fontSize:"16px"},children:e("terminal:empty.tapAgent")}),o.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:e("terminal:empty.switchTo3D")})]})})})}):yo&&r==="terminal"&&s.size>0?o.jsx("div",{ref:M,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${T}%`},children:o.jsx("div",{className:"guake-content",children:o.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:o.jsxs("div",{className:"guake-empty loading",children:[e("terminal:empty.loadingTerminal"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]})})})}):null;if(!y)return null;const Bl=ne=>{ne.preventDefault(),ne.stopPropagation(),ia.current++,ne.dataTransfer.types.includes("Files")&&ts(!0)},Op=ne=>{ne.preventDefault(),ne.stopPropagation()},Lp=ne=>{ne.preventDefault(),ne.stopPropagation(),ia.current--,ia.current===0&&ts(!1)},vo=async ne=>{var ve,$e;ne.preventDefault(),ne.stopPropagation(),ia.current=0,ts(!1);const Te=ne.dataTransfer.files;if(Te.length)for(const ft of Te){const jt=await((ve=B.current)==null?void 0:ve.terminalInput.uploadFile(ft));jt&&(($e=B.current)==null||$e.terminalInput.setAttachedFiles(Ft=>[...Ft,jt]))}};return o.jsxs("div",{ref:M,className:`guake-terminal ${Rt?"open":"collapsed"} ${ge&&Rt?"fullscreen":""} ${Q&&Rt?"with-debug-panel":""} ${Ne&&Rt?"with-git-panel":""} ${rt&&Rt?"with-buildings-panel":""} ${Z&&Rt?"with-workflow-panel":""} ${v&&Rt?"with-tracking-board":""} ${Ve&&Rt?"with-overview-panel":""} ${ms?"drag-over":""} ${Ti>0?"mobile-swipe-close-active":""} ${za?"mobile-swipe-close-closing":""}`,style:{"--terminal-height":`${T}%`,"--mobile-swipe-close-offset":`${Ti}px`,"--guake-side-panel-width":`${$}px`,...O>0?{"--guake-mobile-overview-height":`${O}px`}:{}},onDragEnter:Bl,onDragOver:Op,onDragLeave:Lp,onDrop:vo,children:[o.jsxs("div",{className:"guake-drop-overlay",children:[o.jsx("div",{className:"drop-border"}),o.jsx("span",{className:"drop-icon",children:"📎"}),o.jsx("span",{className:"drop-label",children:e("terminal:input.dropToAttach")})]}),Q&&Rt&&y&&o.jsx(j6,{agentId:y,onClose:()=>Re(!1)}),Ne&&Rt&&y&&o.jsx(F6,{agentId:y,agents:t,onClose:()=>Ue(!1),branchInfoMap:_,fetchRemote:F,fetchingDirs:P}),rt&&Rt&&y&&o.jsx(pW,{agentId:y,onClose:()=>oe(!1)}),Z&&Rt&&y&&o.jsx(gW,{agentId:y,onClose:()=>be(!1)}),v&&Rt&&y&&o.jsxs("div",{className:"guake-tracking-board-panel",children:[o.jsxs("div",{className:"guake-tracking-board-header",children:[o.jsxs("div",{className:"guake-tracking-board-title",children:[o.jsx("span",{className:"guake-tracking-board-icon",children:"▥"}),o.jsx("span",{children:"Tracking Board"})]}),o.jsx("button",{type:"button",className:"guake-tracking-board-close",onClick:()=>W.setTrackingBoardVisible(!1),title:"Close tracking board",children:"✕"})]}),o.jsx("div",{className:"guake-tracking-board-body",children:o.jsx(Hj,{activeAgentId:y,onSelectAgent:S})})]}),(Q||Ne||rt||Z||v)&&Rt&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:ne=>Y(ne,"right")}),Ve&&Rt&&y&&o.jsx(s5,{activeAgentId:y,onClose:()=>we(!1),onSelectAgent:ne=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(ne)},agentListRef:G,twoFingerState:kt}),Ve&&Rt&&y&&o.jsx("div",{className:"guake-side-panel-resize left",onMouseDown:ne=>Y(ne,"left")}),Ve&&Rt&&y&&o.jsx("div",{className:"aop-resize-handle",onMouseDown:U,onTouchStart:H}),o.jsxs("div",{className:"guake-content",children:[o.jsx(O9,{selectedAgent:b,selectedAgentId:y,sortedAgents:wt.sortedAgents,swipeOffset:wt.swipeOffset,viewMode:te,setViewMode:V,searchMode:((dr=B.current)==null?void 0:dr.search.searchMode)??!1,toggleSearch:((fr=B.current)==null?void 0:fr.search.toggleSearch)??(()=>{}),closeSearch:((Fl=B.current)==null?void 0:Fl.search.closeSearch)??(()=>{}),debugPanelOpen:Q,setDebugPanelOpen:Re,debuggerEnabled:pe,setDebuggerEnabled:Ie,gitPanelOpen:Ne,setGitPanelOpen:Ue,buildingsPanelOpen:rt,setBuildingsPanelOpen:oe,workflowPanelOpen:Z,setWorkflowPanelOpen:be,hasWorkflow:ee,trackingBoardVisible:v,setTrackingBoardVisible:ne=>W.setTrackingBoardVisible(ne),overviewPanelOpen:Ve,setOverviewPanelOpen:we,agentInfoOpen:ye,onToggleAgentInfo:ur,isFullscreen:ge,onToggleFullscreen:yt,onNavigateBack:cr,onNavigateForward:Se,canNavigateBack:Ur,canNavigateForward:oa,outputsLength:((So=B.current)==null?void 0:So.outputsLength)??0,setContextConfirm:Ke,onClearContextDirect:()=>{var ne;W.clearContext(y),(ne=B.current)==null||ne.historyLoader.clearHistory()},headerRef:wt.headerRef}),o.jsxs("div",{className:`guake-swipe-container ${wt.swipeAnimationClass}`,style:wt.swipeOffset!==0?{transform:`translateX(${wt.swipeOffset*40}%)`}:void 0,children:[wt.sortedAgents.length>1&&wt.swipeOffset!==0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`swipe-indicator left ${wt.swipeOffset>.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-icon",children:"←"}),o.jsx("span",{className:"indicator-name",children:(zl=wt.nextAgent)==null?void 0:zl.name})]}),o.jsxs("div",{className:`swipe-indicator right ${wt.swipeOffset<-.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-name",children:(Gr=wt.prevAgent)==null?void 0:Gr.name}),o.jsx("span",{className:"indicator-icon",children:"→"})]})]}),wt.sortedAgents.length>1&&wt.sortedAgents.length<=8&&wt.swipeOffset!==0&&o.jsx("div",{className:`swipe-dots ${Math.abs(wt.swipeOffset)>.1?"visible":""}`,children:wt.sortedAgents.map((ne,Te)=>o.jsx("div",{className:`swipe-dot ${Te===wt.currentAgentIndex?"active":""}`},ne.id))}),o.jsx(dW,{activeAgentId:y,activeAgent:b,paneRef:B,viewMode:te,isOpen:Rt,onImageClick:wn,onFileClick:bs,onBashClick:ls,onViewMarkdown:Rn,keyboard:I,canSwipeClose:yo&&r==="terminal"&&!((ca=B.current)!=null&&ca.search.searchMode)&&!((Co=B.current)!=null&&Co.historyLoader.fetchingHistory),onSwipeCloseOffsetChange:Vr,onSwipeClose:Pu,hasModalOpen:!!(J||je||We||i)})]}),o.jsxs("div",{className:"guake-agent-status-bar",children:[(b==null?void 0:b.isDetached)&&o.jsx(Un,{content:o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",e("terminal:empty.reattachingSessionTitle")]}),o.jsxs("div",{className:"tide-tooltip__text",children:[e("terminal:empty.reattachingSessionDesc"),o.jsx("br",{}),o.jsx("br",{}),o.jsxs("strong",{children:[e("common:labels.status"),":"]})," ",e("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:o.jsxs("span",{className:"guake-detached-badge",title:e("terminal:empty.reattachingBadge"),children:[o.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",e("terminal:empty.reattaching")]})}),(b==null?void 0:b.cwd)&&o.jsxs("span",{className:"guake-agent-cwd",title:b.cwd,children:["📁 ",b.cwd.split("/").filter(Boolean).slice(-2).join("/")||b.cwd]}),C&&C.map(({areaId:ne,areaName:Te,dir:ve})=>{const $e=_.get(ve),ft=P.has(ve);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${Te}: ${ve}${$e?` (${$e.branch}${$e.ahead?` ↑${$e.ahead}`:""}${$e.behind?` ↓${$e.behind}`:""})`:""}`,onClick:()=>W.openFileExplorerForAreaFolder(ne,ve),children:["📂 ",ve.split("/").filter(Boolean).pop()||ve,$e&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",$e.branch]}),$e.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${$e.ahead} ahead`,children:["↑",$e.ahead]}),$e.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${$e.behind} behind`,children:["↓",$e.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${ft?"fetching":""}`,title:"Git fetch",onClick:jt=>{jt.stopPropagation(),F(ve)},children:ft?"⏳":"⇣"})]})]},`${ne}:${ve}`)}),b&&(()=>{const ne=b.contextStats,Te=!!ne,ve=ne?ne.totalTokens:b.contextUsed||0,$e=ne?ne.contextWindow:b.contextLimit||2e5,ft=ne?ne.usedPercent:Math.round(ve/$e*100),jt=Math.max(0,Math.min(100,ft)),Ft=Math.max(0,100-jt),zt=jt>=80?"#ff4a4a":jt>=60?"#ff9e4a":jt>=40?"#ffd700":"#4aff9e",zn=(ve/1e3).toFixed(1),On=($e/1e3).toFixed(1);return o.jsxs("span",{className:"guake-agent-context",onClick:()=>W.setContextModalAgentId(y),title:e(Te?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[o.jsx("span",{className:"context-icon",children:"📊"}),o.jsxs("span",{className:"context-label",children:[e("terminal:agentInfo.context"),":"]}),o.jsx("span",{className:"context-bar-mini",children:o.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,jt)}%`,backgroundColor:zt}})}),o.jsxs("span",{className:"context-tokens",style:{color:zt},children:[zn,"k/",On,"k"]}),o.jsxs("span",{className:"context-free",children:["(",e("terminal:context.percentFree",{percent:Ft}),")"]}),!Te&&o.jsx("span",{className:"context-warning",title:e("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),o.jsxs("span",{className:"guake-status-right",children:[A.length>0&&o.jsx("span",{className:"guake-status-terminals",children:A.map(ne=>{const Te=Fn.has(ne.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""} ${ne.hasUrl?"":"offline"}`,title:`${Te?"Hide":"Show"} terminal: ${ne.name}${ne.hasUrl?"":" (starting...)"}`,onClick:()=>{if(Te){const ve=ie.find($e=>$e.buildingId===ne.id);ve&&it(ve.id)}else ne.hasUrl||W.sendBuildingCommand(ne.id,"start"),pn(ne.id,"terminal")},onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),Fn.has(ne.id)||lt({position:{x:ve.clientX,y:ve.clientY},buildingId:ne.id,type:"terminal"})},children:"💻"},ne.id)})}),E.length>0&&o.jsx("span",{className:"guake-status-terminals",children:E.map(ne=>{const Te=Fn.has(ne.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} logs: ${ne.name}`,onClick:()=>{if(Te){const ve=ie.find($e=>$e.buildingId===ne.id);ve&&it(ve.id)}else pn(ne.id,"pm2-logs")},onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),Fn.has(ne.id)||lt({position:{x:ve.clientX,y:ve.clientY},buildingId:ne.id,type:"pm2-logs"})},children:"📜"},ne.id)})}),D.length>0&&o.jsx("span",{className:"guake-status-terminals",children:D.map(ne=>{const Te=Fn.has(ne.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} database: ${ne.name}`,onClick:()=>{if(Te){const ve=ie.find($e=>$e.buildingId===ne.id);ve&&it(ve.id)}else pn(ne.id,"database")},onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),Fn.has(ne.id)||lt({position:{x:ve.clientX,y:ve.clientY},buildingId:ne.id,type:"database"})},children:"🗄️"},ne.id)})}),o.jsx(kW,{})]})]}),(()=>{const ne=[];return Ze&&(ne.push({id:"open",label:"Open",icon:"⬇",onClick:()=>pn(Ze.buildingId,Ze.type)}),en.length>0&&(ne.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Dn(Ze.buildingId,Ze.type,"horizontal")}),ne.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Dn(Ze.buildingId,Ze.type,"vertical")}))),o.jsx(Ba,{children:o.jsx(co,{isOpen:Ze!==null,position:(Ze==null?void 0:Ze.position)||{x:0,y:0},worldPosition:{x:0,z:0},actions:ne,onClose:()=>lt(null)})})})(),en.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:os}),o.jsx("div",{ref:Mt,className:`guake-bottom-panels-container ${Qe}`,style:{height:Ee},onWheel:ne=>ne.stopPropagation(),children:en.map((ne,Te)=>{const ve=k.get(ne.buildingId);if(!ve)return null;const $e=tt[Te]??1,ft=(()=>{var jt;if(ne.type==="terminal")return(jt=ve.terminalStatus)!=null&&jt.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ve.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx(Hb,{terminalUrl:ve.terminalStatus.url,visible:!0})]},ne.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ve.name," (starting...)"]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx("div",{className:"guake-bottom-terminal-starting",children:o.jsx("span",{children:"Starting terminal..."})})]},ne.id);if(ne.type==="pm2-logs"){const Ft=_e[ne.id]||"";return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",ve.name]}),o.jsxs("div",{className:"guake-bottom-terminal-controls",children:[o.jsx("input",{type:"text",className:"guake-bottom-terminal-filter",value:Ft,onChange:zt=>{const zn=zt.target.value;me(On=>{if(!zn.trim()){if(!(ne.id in On))return On;const Na={...On};return delete Na[ne.id],Na}return{...On,[ne.id]:zn}})},placeholder:"Filter logs","aria-label":`Filter logs for ${ve.name}`,spellCheck:!1}),o.jsx("select",{className:"guake-bottom-terminal-retention",value:le===null?"unlimited":String(le),onChange:zt=>{const zn=zt.target.value==="unlimited"?null:Number(zt.target.value);De(zn),TO(zn)},"aria-label":`Max log retention for ${ve.name}`,children:NO.map(zt=>o.jsx("option",{value:zt===null?"unlimited":String(zt),children:zt===null?"Unlimited":`${zt.toLocaleString()} lines`},zt===null?"unlimited":zt))}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>W.clearStreamingLogs(ne.buildingId),title:"Clear logs",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"})})}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>W.sendBuildingCommand(ne.buildingId,"restart"),title:"Restart",children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M1 4v6h6"}),o.jsx("path",{d:"M3.51 15a9 9 0 105.64-11.36L3 10"})]})}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),o.jsx(MW,{buildingId:ne.buildingId,filterText:Ft,maxRetention:le})]},ne.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:$e},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",ve.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>it(ne.id),children:o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx(i9,{building:ve})]},ne.id)})();return Te>0?o.jsxs(Ce.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${Qe}`,onMouseDown:jt=>At(jt,Te-1)}),ft]},ne.id):ft})})]}),ie.filter(ne=>ne.areaId!==xt&&ne.type==="terminal").map(ne=>{var ve;const Te=k.get(ne.buildingId);return(ve=Te==null?void 0:Te.terminalStatus)!=null&&ve.url?o.jsx(Hb,{terminalUrl:Te.terminalStatus.url,visible:!1},ne.id):null})]}),Rt&&!ge&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:R,title:e("common:rightPanel.dragToResize")}),!(Rt&&ge)&&o.jsxs("div",{className:"guake-handle",onClick:()=>{Rt&&W.toggleTerminal()},onDoubleClick:()=>{Rt||W.toggleTerminal()},style:{top:Rt?`min(${T}%, calc(100vh - 72px))`:"0"},children:[o.jsx("span",{className:"guake-handle-icon",children:Rt?"▲":"▼"}),o.jsx("span",{className:"guake-handle-text",children:b.name})]}),J&&o.jsx(x6,{url:J.url,name:J.name,onClose:()=>de(null)}),je&&o.jsx(y6,{state:je,onClose:()=>xe(null)}),qe&&o.jsx(v6,{action:qe,selectedAgentId:y,subordinateCount:((Yr=b==null?void 0:b.subordinateIds)==null?void 0:Yr.length)||0,onClose:()=>Ke(null),onClearHistory:((ja=B.current)==null?void 0:ja.historyLoader.clearHistory)??(()=>{})}),o.jsx(w6,{}),o.jsx(k6,{}),o.jsx(A6,{agent:b,isOpen:ye,onClose:()=>Fe(!1)}),o.jsx(S6,{agent:b,content:We,onClose:()=>Me(null)})]})});function RW(n){return n.trim().replace(/^v/i,"")}function CA(n){const t=RW(n).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!t)return null;const s=t[1].split(".").map(r=>Number.parseInt(r,10));if(s.some(Number.isNaN))return null;const a=t[2]?t[2].split("."):[];return{core:s,prerelease:a}}function OW(n,e){if(n.length===0&&e.length===0)return 0;if(n.length===0)return 1;if(e.length===0)return-1;const t=Math.max(n.length,e.length);for(let s=0;s<t;s+=1){const a=n[s],r=e[s];if(a===void 0)return-1;if(r===void 0)return 1;const i=/^\d+$/.test(a)?Number.parseInt(a,10):null,c=/^\d+$/.test(r)?Number.parseInt(r,10):null;if(i!==null&&c!==null){if(i>c)return 1;if(i<c)return-1;continue}if(i!==null)return-1;if(c!==null)return 1;const d=a.localeCompare(r);if(d!==0)return d>0?1:-1}return 0}function LW(n,e){const t=CA(n),s=CA(e);if(!t||!s)return null;const a=Math.max(t.core.length,s.core.length);for(let r=0;r<a;r+=1){const i=t.core[r]??0,c=s.core[r]??0;if(i>c)return 1;if(i<c)return-1}return OW(t.prerelease,s.prerelease)}function PW(n,e){const t=LW(n,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function IW(n,e={}){const{timeoutMs:t=5e3,fetchImpl:s=fetch}=e;try{const a=new AbortController,r=setTimeout(()=>a.abort(),t),i=Date.now(),c=await s(`https://registry.npmjs.org/${encodeURIComponent(n)}/latest?t=${i}`,{signal:a.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!c.ok)return null;const d=await c.json();return typeof d.version=="string"?d.version:null}catch{return null}}async function BW(n,e,t={}){const s=await IW(n,t);return s?{currentVersion:e,latestVersion:s,relation:PW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const FW="tide-commander",Yg="1.53.0";function zW(){const[n,e]=x.useState({currentVersion:Yg,latestVersion:null,relation:"unknown",isChecking:!1}),t=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await BW(FW,Yg);e({currentVersion:Yg,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return x.useEffect(()=>{t()},[t]),{...n,refresh:t}}const $W=x.memo(function({agent:e,currentIndex:t,agentIndex:s,isTouchInput:a,isTouchDragEnabled:r,isSelected:i,hasUnseenOutput:c,isDragging:d,isDragOver:f,customClasses:h,onDragStart:m,onDragEnd:b,onDragOver:y,onDragEnter:v,onDragLeave:S,onDrop:N,onAgentClick:k,onAgentDoubleClick:C,onTouchStart:A,onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onHoverEnter:F,onHoverLeave:P,onItemRef:T}){const M=!a||r,R=x.useCallback(O=>{T(e.id,O)},[e.id,T]);return o.jsxs("div",{ref:R,className:`agent-bar-item ${i?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${d?"dragging":""} ${f?"drag-over":""} ${r?"touch-drag-enabled":""}`,draggable:M,onDragStart:O=>m(O,e),onDragEnd:b,onDragOver:O=>y(O,s),onDragEnter:O=>v(O,s),onDragLeave:S,onDrop:O=>N(O,s),onTouchStart:O=>A(O,e.id),onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onClick:O=>k(e,O),onDoubleClick:()=>C(e),onMouseEnter:()=>F(e),onMouseLeave:P,title:a?`${e.name} (${t+1}) - Long press to reorder`:`${e.name} (${t+1}) - Drag to reorder within group`,children:[o.jsxs("div",{className:"agent-bar-avatar",children:[o.jsx(Nn,{classId:e.class,size:"100%",className:"agent-bar-icon"}),o.jsx("span",{className:"agent-bar-status",style:{backgroundColor:qb(e.status)}}),c&&o.jsx("span",{className:"agent-bar-notification-badge",title:"New output available - click to view"}),e.status==="idle"&&e.lastActivity>0&&o.jsx("span",{className:"agent-bar-idle-clock",style:{color:Vb(e.lastActivity)},title:fp(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${t+1}`,children:["^",t+1]})]})}),HW=x.memo(function({onFocusAgent:e,onSpawnClick:t,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=ut(["common"]),c=Rl(),d=Pa(),f=rx(),h=$O(),m=Aj(),b=Br(),y=Ia(),v=ux(),[S]=tx(),[N,k]=x.useState(!1);oj("AgentBar");const C=x.useRef(null),A=x.useRef(null),E=x.useRef(null),D=x.useRef(new Map);x.useEffect(()=>{{k(!1);return}},[b.experimental2DView]),x.useEffect(()=>{const le=A.current;if(!le)return;const De=Qe=>{le.scrollWidth<=le.clientWidth||(Qe.preventDefault(),Math.abs(Qe.deltaX)>Math.abs(Qe.deltaY)?le.scrollLeft+=Qe.deltaX:le.scrollLeft+=Qe.deltaY)};return le.addEventListener("wheel",De,{passive:!1}),()=>le.removeEventListener("wheel",De)},[]);const[_,F]=x.useState(null),[P,T]=x.useState(new Map),[M,R]=x.useState(null),[O,U]=x.useState(null),H=x.useRef(0),[I,$]=x.useState(null),z=x.useRef(null),q=x.useRef(null),Y=x.useRef(null),B=x.useRef(null),G=350,te=8,V=x.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),ge=x.useMemo(()=>Array.from(c.values()).filter(le=>{if(W.isAgentInArchivedArea(le.id))return!1;if(S){const De=W.getAreaForAgent(le.id);if(!hp((De==null?void 0:De.id)??null))return!1}return!0}).sort((le,De)=>(le.createdAt||0)-(De.createdAt||0)),[c,d,S]),{orderedAgents:he,moveAgent:J}=fO(ge),de=he,je=x.useMemo(()=>{const le=new Map;for(const De of de)le.set(De.id,W.getAreaForAgent(De.id));return le},[de,d]),xe=x.useMemo(()=>{const le=new Map;for(const Qe of de){const se=je.get(Qe.id)||null,Ee=(se==null?void 0:se.id)||null;le.has(Ee)||le.set(Ee,{area:se,agents:[]}),le.get(Ee).agents.push(Qe)}const De=Array.from(le.values());return De.sort((Qe,se)=>{var Ee,He;return!Qe.area&&se.area?1:Qe.area&&!se.area?-1:!Qe.area&&!se.area?0:(((Ee=Qe.area)==null?void 0:Ee.name)||"").localeCompare(((He=se.area)==null?void 0:He.name)||"")}),De},[de,je]),qe=x.useRef(e);qe.current=e;const Ke=x.useRef(M);Ke.current=M;const We=x.useRef(de);We.current=de;const Me=x.useRef(je);Me.current=je;const ye=x.useRef(J);ye.current=J,x.useEffect(()=>{const le=new Map(P);let De=!1;for(const Qe of de){const se=P.get(Qe.id);Qe.currentTool?(!se||se.tool!==Qe.currentTool)&&(le.set(Qe.id,{tool:Qe.currentTool,key:Date.now()}),De=!0):se&&setTimeout(()=>{T(Ee=>{const He=new Map(Ee);return He.delete(Qe.id),He})},1500)}De&&T(le)},[de.map(le=>le.currentTool).join(",")]),x.useEffect(()=>{const le=h;if(!le)return;const De=D.current.get(le),Qe=A.current;De&&Qe&&requestAnimationFrame(()=>{const se=De.getBoundingClientRect(),Ee=Qe.getBoundingClientRect(),Ye=se.left-Ee.left+Qe.scrollLeft+se.width/2,tt=Qe.clientWidth;Qe.scrollTo({left:Ye-tt/2,behavior:"smooth"})})},[h]);const Fe=x.useCallback((le,De)=>{if(Y.current===le.id){Y.current=null,De.preventDefault(),De.stopPropagation();return}W.setLastSelectionViaDirectClick(!0),De.shiftKey?W.addToSelection(le.id):W.selectAgent(le.id),W.setTerminalOpen(!0)},[]),Q=x.useCallback(le=>{var De;(De=qe.current)==null||De.call(qe,le.id),W.setTerminalOpen(!0)},[]),Re=x.useCallback(()=>F(null),[]),pe=x.useCallback((le,De)=>{De?D.current.set(le,De):D.current.delete(le)},[]),Ie=x.useCallback((le,De)=>{R(De),$(De.id),le.dataTransfer.effectAllowed="move",le.dataTransfer.setData("text/plain",De.id),requestAnimationFrame(()=>{le.target.classList.add("dragging")})},[]),Ne=x.useCallback(le=>{R(null),U(null),$(null),H.current=0,le.target.classList.remove("dragging")},[]),fe=x.useCallback((le,De)=>{le.preventDefault();const Qe=Ke.current;if(Qe){const se=Me.current.get(Qe.id),Ee=We.current[De],He=Ee?Me.current.get(Ee.id):null,Ye=(se==null?void 0:se.id)??null,tt=(He==null?void 0:He.id)??null;le.dataTransfer.dropEffect=Ye===tt?"move":"none"}else le.dataTransfer.dropEffect="move"},[]),Ue=x.useCallback((le,De)=>{le.preventDefault(),H.current++;const Qe=Ke.current;if(Qe){const se=Me.current.get(Qe.id),Ee=We.current[De],He=Ee?Me.current.get(Ee.id):null,Ye=(se==null?void 0:se.id)??null,tt=(He==null?void 0:He.id)??null;U(Ye===tt?De:null)}else U(De)},[]),rt=x.useCallback(le=>{H.current--,H.current===0&&U(null)},[]),ct=x.useCallback((le,De)=>{le.preventDefault();const Qe=Ke.current;if(!Qe)return;const se=We.current,Ee=Me.current,He=se.findIndex(Ye=>Ye.id===Qe.id);if(He!==-1&&He!==De){const Ye=Ee.get(Qe.id),tt=se[De],at=tt?Ee.get(tt.id):null,pt=(Ye==null?void 0:Ye.id)??null,Mt=(at==null?void 0:at.id)??null;pt===Mt&&ye.current(He,De)}R(null),U(null),$(null),H.current=0},[]),oe=x.useCallback(()=>{z.current&&(clearTimeout(z.current),z.current=null)},[]),Z=x.useCallback(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),ae=x.useCallback((le,De)=>{if(!V||le.touches.length!==1)return;oe(),Z(),$(null);const Qe=le.touches[0];q.current={agentId:De,x:Qe.clientX,y:Qe.clientY},z.current=setTimeout(()=>{$(De),Y.current=De,z.current=null},G)},[oe,Z,V]),be=x.useCallback(le=>{if(!V||le.touches.length!==1)return;const De=q.current;if(!De||!z.current)return;const Qe=le.touches[0],se=Qe.clientX-De.x,Ee=Qe.clientY-De.y;Math.sqrt(se*se+Ee*Ee)>te&&(oe(),q.current=null)},[oe,V]),ee=x.useCallback(()=>{oe(),q.current=null,Ke.current||$(null),Z(),B.current=setTimeout(()=>{Y.current=null,B.current=null},450)},[oe,Z]);x.useEffect(()=>()=>{oe(),Z()},[oe,Z]);const ce=le=>{const De=`common:status.${le}`;return i(De,{defaultValue:i("common:status.unknown")})},{currentVersion:Ve,latestVersion:we,relation:ie,isChecking:X}=zW(),_e=Ve;let me=0;return o.jsxs("div",{className:"agent-bar",ref:C,children:[o.jsxs("div",{className:"agent-bar-scroll",ref:A,children:[o.jsxs("div",{className:"agent-bar-version",title:we?`Tide Commander v${_e} (npm: v${we})`:`Tide Commander v${_e}`,children:[o.jsxs("span",{children:["v",_e]}),ie==="behind"&&we?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${we}`,children:["npm v",we]}):ie==="ahead"&&we?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${we}`,children:["npm v",we]}):null,ie==="behind"?o.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status agent-bar-version-status-behind",title:i("common:agentBar.behindNpmTooltip",{defaultValue:"Current version is behind npm latest"}),children:i("common:agentBar.behindNpm",{defaultValue:"(behind npm)"})}):ie==="ahead"?o.jsx("span",{className:"agent-bar-version-status agent-bar-version-status-ahead",title:i("common:agentBar.aheadNpmTooltip",{defaultValue:"Current version is newer than npm latest"}),children:i("common:agentBar.aheadNpm",{defaultValue:"(ahead of npm)"})}):ie==="equal"?o.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status",children:i("common:agentBar.updated")}):X?o.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.checkingNpm",{defaultValue:"(checking npm)"})}):o.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.unknownNpm",{defaultValue:"(npm unknown)"})}),N&&o.jsx(Un,{content:"Refresh 3D Scene (HMR changes pending)",position:"bottom",children:o.jsx("button",{className:"agent-bar-hmr-refresh",onClick:xj,children:"↻"})})]}),o.jsxs("div",{className:"agent-bar-list",ref:E,children:[o.jsx(Un,{content:i("common:agentBar.spawnNewAgent"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn",onClick:t,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"+"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newAgent")})]})}),o.jsx(Un,{content:i("common:agentBar.spawnBoss"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-boss-btn",onClick:s,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"👑"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBoss")})]})}),o.jsx(Un,{content:i("common:agentBar.addNewBuilding"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-building-btn",onClick:a,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"🏢"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBuilding")})]})}),o.jsx(Un,{content:i("common:agentBar.drawNewArea"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-area-btn",onClick:r,children:[o.jsx("span",{className:"agent-bar-spawn-icon",children:"🔲"}),o.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newArea")})]})}),xe.map(le=>{var se,Ee,He,Ye,tt;const De=le.agents,Qe=!le.area;return o.jsxs("div",{className:`agent-bar-group ${Qe?"unassigned":""}`,style:{borderColor:((se=le.area)==null?void 0:se.color)||void 0,background:le.area?`${le.area.color}15`:void 0},children:[o.jsx("div",{className:"agent-bar-area-label",children:o.jsx("span",{className:"agent-bar-area-name",style:{color:((Ee=le.area)==null?void 0:Ee.color)||"#888"},children:((He=le.area)==null?void 0:He.name)||i("common:agentBar.unassigned")})}),((Ye=le.area)==null?void 0:Ye.directories)&&le.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:le.area.directories.map((at,pt)=>o.jsxs("div",{className:"agent-bar-folder-item",onClick:Mt=>{Mt.stopPropagation(),W.openFileExplorer(at)},children:[o.jsx("span",{className:"agent-bar-folder-icon",children:"📁"}),o.jsxs("div",{className:"agent-bar-folder-tooltip",children:[o.jsx("div",{className:"agent-bar-folder-tooltip-path",children:at}),o.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},pt))}),De.map(at=>{const pt=me++,Mt=de.findIndex(Ze=>Ze.id===at.id);return o.jsx($W,{agent:at,currentIndex:pt,agentIndex:Mt,isTouchInput:V,isTouchDragEnabled:I===at.id,isSelected:f.has(at.id),hasUnseenOutput:v.has(at.id),isDragging:(M==null?void 0:M.id)===at.id,isDragOver:O===Mt,customClasses:y,onDragStart:Ie,onDragEnd:Ne,onDragOver:fe,onDragEnter:Ue,onDragLeave:rt,onDrop:ct,onAgentClick:Fe,onAgentDoubleClick:Q,onTouchStart:ae,onTouchMove:be,onTouchEnd:ee,onTouchCancel:ee,onHoverEnter:F,onHoverLeave:Re,onItemRef:pe},at.id)})]},((tt=le.area)==null?void 0:tt.id)||"unassigned")})]})]}),Array.from(P.entries()).map(([le,De])=>{const Qe=D.current.get(le);if(!Qe)return null;const se=Qe.getBoundingClientRect(),Ee=rs[De.tool]||rs.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:De.tool,style:{position:"fixed",left:se.left+se.width/2,bottom:window.innerHeight-se.top+8},children:[o.jsx("span",{className:"agent-bar-tool-icon",children:Ee}),o.jsx("span",{className:"agent-bar-tool-name",children:De.tool})]},`tool-${le}-${De.key}`)}),_&&(()=>{const le=W.getAreaForAgent(_.id),De=m.get(_.id),Qe=Fr(_.class,y),se=Date.now()-(_.createdAt||Date.now()),Ee=Math.floor(se/6e4),He=Math.floor(Ee/60),Ye=He>0?`${He}h ${Ee%60}m`:`${Ee}m`,tt=Ze=>Ze>=1e6?`${(Ze/1e6).toFixed(1)}M`:Ze>=1e3?`${(Ze/1e3).toFixed(1)}K`:Ze.toString(),at=_.contextLimit>0?Math.round(_.contextUsed/_.contextLimit*100):0,pt=D.current.get(_.id),Mt={};if(pt){const Ze=pt.getBoundingClientRect();Mt.position="fixed",Mt.left=Ze.left+Ze.width/2,Mt.bottom=window.innerHeight-Ze.top+12}return o.jsxs("div",{className:"agent-bar-tooltip",style:Mt,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:o.jsx(Nn,{classId:_.class,size:18})}),o.jsxs("span",{className:"agent-bar-tooltip-name",children:[o.jsx("img",{src:_.provider==="codex"?"/assets/codex.png":_.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:_.provider,className:"agent-bar-provider-icon",title:_.provider==="codex"?"Codex Agent":_.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),_.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:qb(_.status)},children:ce(_.status)})]}),o.jsxs("div",{className:"agent-bar-tooltip-info",children:[o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.class"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.class," — ",Qe.description]})]}),le&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.area"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:le.color},children:le.name})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.directory"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:_.cwd})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.uptime"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",children:Ye})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.tokens"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[tt(_.tokensUsed)," ",i("common:agentPopup.used")]})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.context"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:at>80?"#ff4a4a":at>60?"#ff9e4a":void 0},children:[tt(_.contextUsed)," / ",tt(_.contextLimit)," (",at,"%)"]})]}),_.currentTool&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.tool"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[rs[_.currentTool]||rs.default," ",_.currentTool]})]}),_.taskLabel&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsx("span",{className:"agent-bar-tooltip-label",children:"📋 Task:"}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:_.taskLabel})]}),_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.task"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.currentTask.substring(0,150),_.currentTask.length>150?"...":""]})]}),_.lastAssignedTask&&!_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.assignedTask"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[_.lastAssignedTask.substring(0,200),_.lastAssignedTask.length>200?"...":""]})]}),De&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.lastQuery"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[De.text.substring(0,300),De.text.length>300?"...":""]})]})]})]})})()]})});function UW({activeTool:n,onExit:e}){const{t}=ut(["notifications","terminal"]);if(!n||n==="select")return null;const s=t(n==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=n==="rectangle"?"▭":"○";return o.jsxs("div",{className:"drawing-mode-indicator",children:[o.jsxs("div",{className:"drawing-mode-content",children:[o.jsx("span",{className:"drawing-mode-icon",children:a}),o.jsxs("div",{className:"drawing-mode-text",children:[o.jsxs("span",{className:"drawing-mode-title",children:[t("terminal:drawingMode.drawingArea"),": ",s]}),o.jsxs("span",{className:"drawing-mode-hint",children:[t("terminal:drawingMode.clickAndDrag")," • ",t("terminal:drawingMode.pressEscape")]})]})]}),o.jsx("button",{className:"drawing-mode-exit",onClick:e,title:t("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const WW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Kg=n=>n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}K`:n.toString(),VW=x.memo(function({agent:e,screenPos:t,onClose:s}){const{t:a}=ut(["common"]),r=Ia(),i=W.getAreaForAgent(e.id),c=W.getState().lastPrompts.get(e.id),d=Fr(e.class,r),f=Date.now()-(e.createdAt||Date.now()),h=Math.floor(f/6e4),m=Math.floor(h/60),b=m>0?`${m}h ${h%60}m`:`${h}m`,y=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,v=x.useMemo(()=>{let k=t.x-150,C=t.y-320-10;return typeof window<"u"&&(k<10?k=10:k+300>window.innerWidth-10&&(k=window.innerWidth-300-10),C<10&&(C=t.y+10)),{position:"fixed",left:k,top:C,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[t.x,t.y]);return o.jsxs("div",{className:"agent-hover-popup",style:v,onMouseLeave:s,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:o.jsx(Nn,{agent:e,size:18})}),o.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:qb(e.status)},children:a(WW[e.status]||"common:status.unknown")})]}),o.jsxs("div",{className:"agent-bar-tooltip-info",children:[o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.class"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.class," — ",d.description]})]}),i&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.area"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:i.color},children:i.name})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.directory"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:e.cwd})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.uptime"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",children:b})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.tokens"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[Kg(e.tokensUsed)," ",a("common:agentPopup.used")]})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.context"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:y>80?"#ff4a4a":y>60?"#ff9e4a":void 0},children:[Kg(e.contextUsed)," / ",Kg(e.contextLimit)," (",y,"%)"]})]}),e.currentTool&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.tool"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[rs[e.currentTool]||rs.default," ",e.currentTool]})]}),e.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.task"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.currentTask.substring(0,150),e.currentTask.length>150?"...":""]})]}),e.lastAssignedTask&&!e.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.assignedTask"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[e.lastAssignedTask.substring(0,200),e.lastAssignedTask.length>200?"...":""]})]}),c&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.lastQuery"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[c.text.substring(0,300),c.text.length>300?"...":""]})]})]})]})});function AA(n){if(n===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,s)).toFixed(1))+" "+t[s]}function jA(n){const t=Date.now()-n,s=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const NA={30:"#1a1a1a",31:"#e74c3c",32:"#2ecc71",33:"#f39c12",34:"#3498db",35:"#9b59b6",36:"#00bcd4",37:"#ecf0f1",90:"#7f8c8d",91:"#ff6b6b",92:"#4ade80",93:"#fbbf24",94:"#60a5fa",95:"#c084fc",96:"#22d3ee",97:"#ffffff"};function qW(n){const e=[],t=/\x1B\[([0-9;]*)m/g;let s=0,a=null,r;for(;(r=t.exec(n))!==null;){if(r.index>s){const c=n.slice(s,r.index);a?e.push(o.jsx("span",{style:{color:a},children:c},e.length)):e.push(c)}const i=r[1].split(";").map(Number);for(const c of i)c===0||c===39?a=null:NA[c]&&(a=NA[c]);s=t.lastIndex}if(s<n.length){const i=n.slice(s);a?e.push(o.jsx("span",{style:{color:a},children:i},e.length)):e.push(i)}return e.length>0?e:[n]}const GW=x.memo(function({building:e,screenPos:t,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var $,z,q,Y,B,G,te,V,ge,he,J,de,je,xe,qe,Ke,We,Me,ye,Fe;const{t:c}=ut(["terminal","common"]),[d,f]=x.useState(!1),[h,m]=x.useState(null),[b,y]=x.useState(!1),v=x.useRef(null),S=x.useRef(h);S.current=h;const{buildingLogs:N}=Fs(),k=W.getBuildingLogs(e.id),C=($=e.pm2)==null?void 0:$.enabled,A=(z=e.docker)==null?void 0:z.enabled,E=x.useRef(null),D=x.useRef(null),_=x.useCallback(Q=>{Q.preventDefault();const Re=S.current?S.current.x:0,pe=S.current?S.current.y:0;v.current={mouseX:Q.clientX,mouseY:Q.clientY,popupX:Re,popupY:pe},y(!0),E.current=Ie=>{if(!v.current)return;const Ne=Ie.clientX-v.current.mouseX,fe=Ie.clientY-v.current.mouseY;m({x:v.current.popupX+Ne,y:v.current.popupY+fe})},D.current=()=>{y(!1),v.current=null,E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",E.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const F=Q=>{if(Q==="logs"){if((C||A)&&r){r();return}W.sendBuildingCommand(e.id,Q),f(!0)}else W.sendBuildingCommand(e.id,Q)},P=(Q,Re)=>{if(Q){const pe=`http://localhost:${Q}`;Re&&i?i(pe):window.open(pe,"_blank")}},T=((q=e.pm2Status)==null?void 0:q.ports)||[],M=((B=(Y=e.dockerStatus)==null?void 0:Y.ports)==null?void 0:B.map(Q=>Q.host))||[],R=C?T:A?M:[],O=C?!!((G=e.pm2)!=null&&G.script):A?!!((te=e.docker)!=null&&te.image)||((V=e.docker)==null?void 0:V.mode)==="compose"||((ge=e.docker)==null?void 0:ge.mode)==="existing":!!((he=e.commands)!=null&&he.start),U=C?!!((J=e.pm2)!=null&&J.script):A?!0:!!((de=e.commands)!=null&&de.stop),H=C?!!((je=e.pm2)!=null&&je.script):A?!0:!!((xe=e.commands)!=null&&xe.restart),I=x.useMemo(()=>{const Re=d?400:250;let pe=t.x+20,Ie=t.y-80;return typeof window<"u"&&!h&&(t.x+20+280>window.innerWidth&&(pe=t.x-280-20),t.y-80<0?Ie=10:t.y-80+Re>window.innerHeight&&(Ie=window.innerHeight-Re-10)),{position:"fixed",left:pe+((h==null?void 0:h.x)||0),top:Ie+((h==null?void 0:h.y)||0),zIndex:1e3,cursor:b?"grabbing":void 0}},[t.x,t.y,d,h,b]);return o.jsxs("div",{className:"building-action-popup",style:I,onClick:Q=>Q.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header ${b?"dragging":""}`,onMouseDown:_,children:[o.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&o.jsx("span",{className:"building-popup-ports",children:R.map(Q=>o.jsxs("a",{href:`http://localhost:${Q}`,className:"building-popup-port-link",onClick:Re=>{Re.preventDefault(),Re.stopPropagation(),P(Q,Re.altKey)},onMouseDown:Re=>Re.stopPropagation(),title:`Open http://localhost:${Q} (Alt+Click for modal)`,children:[":",Q]},Q))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:ob[e.status]},children:e.status}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),C&&e.pm2Status&&o.jsxs("div",{className:"building-popup-metrics",children:[o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"PID"}),o.jsx("span",{className:"value",children:e.pm2Status.pid||"-"})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"CPU"}),o.jsxs("span",{className:"value",children:[((qe=e.pm2Status.cpu)==null?void 0:qe.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:AA(e.pm2Status.memory||0)})]}),e.pm2Status.restarts!==void 0&&e.pm2Status.restarts>0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"RST"}),o.jsx("span",{className:"value",children:e.pm2Status.restarts})]}),e.pm2Status.uptime&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"UP"}),o.jsx("span",{className:"value",children:jA(e.pm2Status.uptime)})]})]}),A&&e.dockerStatus&&o.jsxs("div",{className:"building-popup-metrics",children:[o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"ID"}),o.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"CPU"}),o.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:AA(e.dockerStatus.memory)})]}),e.dockerStatus.health&&e.dockerStatus.health!=="none"&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"HEALTH"}),o.jsx("span",{className:"value",style:{color:e.dockerStatus.health==="healthy"?"#4ade80":e.dockerStatus.health==="unhealthy"?"#f87171":"#fbbf24"},children:e.dockerStatus.health==="healthy"?"✓":e.dockerStatus.health==="unhealthy"?"✗":"..."})]}),e.dockerStatus.startedAt&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"UP"}),o.jsx("span",{className:"value",children:jA(e.dockerStatus.startedAt)})]})]}),A&&((Ke=e.dockerStatus)==null?void 0:Ke.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Q,Re)=>o.jsxs("span",{className:"service-item",title:`${Q.name}: ${Q.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:Q.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:Q.name})]},Re))}),(e.lastError||C&&((We=e.pm2Status)==null?void 0:We.status)==="errored"||A&&((Me=e.dockerStatus)==null?void 0:Me.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),C&&((ye=e.pm2Status)==null?void 0:ye.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),A&&((Fe=e.dockerStatus)==null?void 0:Fe.health)==="unhealthy"&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.healthCheckFailing")]})]}),o.jsxs("div",{className:"building-popup-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>F("start"),disabled:!O||e.status==="running"||e.status==="starting",title:c(O?"terminal:buildingAction.start":"terminal:buildingAction.noStartCommand"),children:[o.jsx("span",{className:"icon",children:"▶"}),c("terminal:buildingAction.start")]}),o.jsxs("button",{className:"action-btn stop",onClick:()=>F("stop"),disabled:!U||e.status==="stopped"||e.status==="stopping",title:c(U?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:buildingAction.stop")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>F("restart"),disabled:!H,title:c(H?"terminal:buildingAction.restart":"terminal:buildingAction.noRestartCommand"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:buildingAction.restart")]}),o.jsxs("button",{className:"action-btn logs",onClick:()=>F("logs"),title:c("terminal:buildingAction.viewLogs"),children:[o.jsx("span",{className:"icon",children:"📄"}),c("terminal:logs.title")]}),R.length===1&&o.jsxs("button",{className:"action-btn open-url",onClick:Q=>P(R[0],Q.altKey),title:`Open http://localhost:${R[0]} (Alt+Click for modal)`,children:[o.jsx("span",{className:"icon",children:"🔗"}),c("terminal:buildingAction.openInBrowser")]}),R.length>1&&o.jsxs("div",{className:"action-btn-group",children:[o.jsxs("span",{className:"action-btn-label",children:[c("terminal:buildingAction.openInBrowser"),":"]}),R.map(Q=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:Re=>P(Q,Re.altKey),title:`Open http://localhost:${Q} (Alt+Click for modal)`,children:[":",Q]},Q))]})]}),d&&k.length>0&&o.jsxs("div",{className:"building-popup-logs",children:[o.jsxs("div",{className:"logs-header",children:[o.jsx("span",{children:c("terminal:logs.title")}),o.jsx("button",{onClick:()=>W.clearBuildingLogs(e.id),children:c("terminal:logs.clear")})]}),o.jsx("div",{className:"logs-content",children:k.slice(-50).map((Q,Re)=>o.jsx("pre",{children:qW(Q)},Re))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function YW(n){if(n===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,s)).toFixed(1))+" "+t[s]}function KW(n){const t=Date.now()-n,s=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const QW=x.memo(function({building:e,screenPos:t,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){const{t:c}=ut(["terminal","common"]),[d,f]=x.useState(null),[h,m]=x.useState(!1),b=x.useRef(null),y=x.useRef(d);y.current=d;const{buildings:v}=Fs(),N=(e.subordinateBuildingIds||[]).map(T=>v.get(T)).filter(T=>T!==void 0),k=x.useRef(null),C=x.useRef(null),A=x.useCallback(T=>{T.preventDefault();const M=y.current?y.current.x:0,R=y.current?y.current.y:0;b.current={mouseX:T.clientX,mouseY:T.clientY,popupX:M,popupY:R},m(!0),k.current=O=>{if(!b.current)return;const U=O.clientX-b.current.mouseX,H=O.clientY-b.current.mouseY;f({x:b.current.popupX+U,y:b.current.popupY+H})},C.current=()=>{m(!1),b.current=null,k.current&&document.removeEventListener("mousemove",k.current),C.current&&document.removeEventListener("mouseup",C.current)},document.addEventListener("mousemove",k.current),document.addEventListener("mouseup",C.current)},[]);x.useEffect(()=>()=>{k.current&&document.removeEventListener("mousemove",k.current),C.current&&document.removeEventListener("mouseup",C.current)},[]);const E=T=>{W.sendBossBuildingCommand(e.id,T)},D=N.reduce((T,M)=>(T[M.status]=(T[M.status]||0)+1,T),{}),_=N.some(T=>{var M;return(M=T.pm2)==null?void 0:M.enabled}),F=(T,M)=>{const R=`http://localhost:${T}`;M&&i?i(R):window.open(R,"_blank")},P=x.useMemo(()=>{let R=t.x+20,O=t.y-80;return typeof window<"u"&&!d&&(t.x+20+340>window.innerWidth&&(R=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:R+((d==null?void 0:d.x)||0),top:O+((d==null?void 0:d.y)||0),zIndex:1e3,cursor:h?"grabbing":void 0}},[t.x,t.y,d,h]);return o.jsxs("div",{className:"building-action-popup boss-building-popup",style:P,onClick:T=>T.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header boss-header ${h?"dragging":""}`,onMouseDown:A,children:[o.jsx("span",{className:"boss-icon",children:"👑"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"subordinate-count",children:c("terminal:building.unitsCount",{count:N.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),o.jsxs("div",{className:"boss-status-overview",children:[Object.entries(D).map(([T,M])=>o.jsxs("span",{className:"status-badge",style:{backgroundColor:ob[T]||"#666"},children:[M," ",T]},T)),N.length===0&&o.jsx("span",{className:"no-subordinates",children:c("terminal:building.noSubordinates")})]}),N.length>0&&o.jsx("div",{className:"subordinate-list",children:N.map(T=>{var M,R,O;return o.jsxs("div",{className:"subordinate-item",children:[o.jsx("span",{className:"sub-status-dot",style:{backgroundColor:ob[T.status]}}),o.jsx("span",{className:"sub-name",children:T.name}),((M=T.pm2Status)==null?void 0:M.ports)&&T.pm2Status.ports.length>0&&o.jsx("span",{className:"sub-port",children:T.pm2Status.ports.map(U=>o.jsxs("a",{href:`http://localhost:${U}`,className:"building-popup-port-link",onClick:H=>{H.preventDefault(),H.stopPropagation(),F(U,H.altKey)},title:`Open http://localhost:${U} (Alt+Click for modal)`,children:[":",U]},U))}),T.pm2Status&&o.jsxs("span",{className:"sub-metrics",children:[(R=T.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",YW(T.pm2Status.memory||0)]}),((O=T.pm2Status)==null?void 0:O.uptime)&&o.jsx("span",{className:"sub-uptime",children:KW(T.pm2Status.uptime)})]},T.id)})}),o.jsxs("div",{className:"building-popup-actions boss-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>E("start_all"),disabled:N.length===0,title:c("terminal:building.startAllSubs"),children:[o.jsx("span",{className:"icon",children:"▶"}),c("terminal:building.startAll")]}),o.jsxs("button",{className:"action-btn stop",onClick:()=>E("stop_all"),disabled:N.length===0,title:c("terminal:building.stopAllSubs"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:building.stopAll")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>E("restart_all"),disabled:N.length===0,title:c("terminal:building.restartAllSubs"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:building.restartAll")]}),_&&o.jsxs("button",{className:"action-btn logs",onClick:r,title:c("terminal:building.viewUnifiedLogs"),children:[o.jsx("span",{className:"icon",children:"📄"}),c("terminal:building.logs")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:building.fullSettings")})]})}),XW=x.memo(function({building:e,screenPos:t,onClose:s,onOpenSettings:a,onOpenDatabasePanel:r}){var D;const{t:i}=ut(["terminal","common"]),[c,d]=x.useState(null),[f,h]=x.useState(!1),m=x.useRef(null),b=x.useRef(c);b.current=c;const y=cx(e.id),v=((D=e.database)==null?void 0:D.connections)??[],S=x.useRef(null),N=x.useRef(null),k=x.useCallback(_=>{_.preventDefault();const F=b.current?b.current.x:0,P=b.current?b.current.y:0;m.current={mouseX:_.clientX,mouseY:_.clientY,popupX:F,popupY:P},h(!0),S.current=T=>{if(!m.current)return;const M=T.clientX-m.current.mouseX,R=T.clientY-m.current.mouseY;d({x:m.current.popupX+M,y:m.current.popupY+R})},N.current=()=>{h(!1),m.current=null,S.current&&document.removeEventListener("mousemove",S.current),N.current&&document.removeEventListener("mouseup",N.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",N.current)},[]);x.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),N.current&&document.removeEventListener("mouseup",N.current)},[]);const C=_=>{W.testDatabaseConnection(e.id,_)},A=_=>y.connectionStatus.get(_),E=x.useMemo(()=>{let P=t.x+20,T=t.y-80;return typeof window<"u"&&!c&&(t.x+20+320>window.innerWidth&&(P=t.x-320-20),t.y-80<0?T=10:t.y-80+300>window.innerHeight&&(T=window.innerHeight-300-10)),{position:"fixed",left:P+((c==null?void 0:c.x)||0),top:T+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,f]);return o.jsxs("div",{className:"building-action-popup database-building-popup",style:E,onClick:_=>_.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header database-header ${f?"dragging":""}`,onMouseDown:k,children:[o.jsx("span",{className:"database-icon",children:"🗄️"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"connection-count",children:i("terminal:building.connCount",{count:v.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),v.length>0?o.jsx("div",{className:"database-connection-list",children:v.map(_=>{var P;const F=A(_.id);return o.jsxs("div",{className:"database-connection-item",children:[o.jsx("span",{className:"conn-engine",children:((P=jL[_.engine])==null?void 0:P.icon)??"🗄️"}),o.jsx("span",{className:"conn-name",children:_.name}),o.jsx("span",{className:"conn-host",children:_.engine==="sqlite"?_.filepath||_.database||":memory:":`${_.host}:${_.port}`}),F&&o.jsx("span",{className:`conn-status ${F.connected?"connected":"disconnected"}`,children:F.connected?"●":"○"}),o.jsx("button",{className:"conn-test-btn",onClick:()=>C(_.id),title:i("terminal:building.testConnection"),children:"↻"})]},_.id)})}):o.jsxs("div",{className:"database-no-connections",children:[o.jsx("p",{children:i("terminal:building.noConnections")}),o.jsx("p",{className:"hint",children:i("terminal:building.clickSettingsToAdd")})]}),o.jsxs("div",{className:"building-popup-actions database-actions",children:[o.jsxs("button",{className:"action-btn query",onClick:r,disabled:v.length===0,title:i("terminal:building.openDbExplorer"),children:[o.jsx("span",{className:"icon",children:"⌨"}),i("terminal:building.query")]}),o.jsxs("button",{className:"action-btn test-all",onClick:()=>v.forEach(_=>C(_.id)),disabled:v.length===0,title:i("terminal:building.testAllConnections"),children:[o.jsx("span",{className:"icon",children:"↻"}),i("terminal:building.testAll")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:i("common:buttons.settings")})]})});function JW({visible:n=!0,position:e="top-right"}){const[t,s]=x.useState(0),[a,r]=x.useState([]),[i,c]=x.useState(null),[d,f]=x.useState([]),[h,m]=x.useState(null),[b,y]=x.useState(null),[v,S]=x.useState(!1),[N,k]=x.useState("fps"),[C,A]=x.useState(null),[E,D]=x.useState(null),[_,F]=x.useState(null),[P,T]=x.useState(typeof window<"u"?window.innerWidth:1024),[M,R]=x.useState(null);x.useEffect(()=>{const J=()=>T(window.innerWidth);return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]);const O=ax(),U=x.useMemo(()=>{const J=O.filter(je=>je.memoryUsageMB!==void 0&&je.memoryUsageMB>0);return{totalMB:J.reduce((je,xe)=>je+(xe.memoryUsageMB||0),0),agentCount:J.length,agents:J.map(je=>({name:je.name,memoryMB:je.memoryUsageMB||0,status:je.status})).sort((je,xe)=>xe.memoryMB-je.memoryMB)}},[O]),H=x.useRef([]),I=x.useRef(null);if(x.useEffect(()=>{H.current=d},[d]),x.useEffect(()=>{I.current=h},[h]),x.useEffect(()=>{if(!n)return;const J=async()=>{try{const je=await Lt(Et("/api/perf"));if(je.ok){const xe=await je.json();D(xe)}}catch{}};J();const de=setInterval(J,v?3e3:1e4);return()=>clearInterval(de)},[n,v]),x.useEffect(()=>{if(!n)return;const J=Ec.getUsage();J&&M===null&&R(J.usedMB);const de=setInterval(()=>{var Re,pe;qd.update();const je=qd.getStats();s(je.current),r(Ie=>[...Ie,je.current].slice(-60));const xe=Ec.getUsage();xe&&c(xe);const qe=window.__tideScene;if(qe){const Ie=(Re=qe.getMemoryDiagnostics)==null?void 0:Re.call(qe);Ie!=null&&Ie.threeJs&&m(Ie.threeJs);const Ne=qe.renderer;if((pe=Ne==null?void 0:Ne.info)!=null&&pe.memory){const fe=Ne.info.memory.textures||0,Ue=Math.round(fe*1);F({count:fe,estimatedMB:Ue})}}const Ke=document.getElementsByTagName("*"),We=document.getElementsByTagName("canvas"),Me=document.getElementsByTagName("img"),ye=document.getElementsByTagName("video");let Fe=0;for(let Ie=0;Ie<Math.min(Ke.length,500);Ie++){const Ne=Ke[Ie];Ne.onclick&&Fe++,Ne.onmousedown&&Fe++,Ne.onkeydown&&Fe++}Fe+=10,A({nodeCount:Ke.length,listenerCount:Fe,canvasCount:We.length,imageCount:Me.length,videoCount:ye.length}),xe&&f(Ie=>{const Ne=I.current,fe={timestamp:Date.now(),heapMB:xe.usedMB,geometries:(Ne==null?void 0:Ne.geometries)??0,textures:(Ne==null?void 0:Ne.textures)??0};return[...Ie,fe].slice(-120)});const Q=H.current;if(Q.length>=10){const Ie=Q[0],Ne=Q[Q.length-1],fe=(Ne.timestamp-Ie.timestamp)/1e3/60;fe>.1&&y((Ne.heapMB-Ie.heapMB)/fe)}},1e3);return()=>{clearInterval(de)}},[n,M]),!n)return null;const $=J=>{const de=Math.floor(J/3600),je=Math.floor(J%3600/60),xe=J%60;return de>0?`${de}h ${je}m`:je>0?`${je}m ${xe}s`:`${xe}s`},z=J=>J>=55?"#4aff9e":J>=30?"#ffcc00":"#ff4a4a",q=(J,de)=>{const je=J/de;return je<.5?"#4aff9e":je<.8?"#ffcc00":"#ff4a4a"},Y=J=>J===null?"#888":J<1?"#4aff9e":J<5?"#ffcc00":"#ff4a4a",B=qd.getStats(),te=P<=768?80:10,V={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:te,left:10},"bottom-right":{bottom:te,right:10}},ge=M&&i?i.usedMB-M:0,he=J=>({padding:"2px 8px",fontSize:"9px",border:"none",background:N===J?"rgba(74, 158, 255, 0.4)":"rgba(255, 255, 255, 0.1)",color:N===J?"#4a9eff":"#888",borderRadius:"3px",cursor:"pointer"});return o.jsxs("div",{style:{position:"fixed",...V[e],zIndex:99999,fontFamily:"monospace",fontSize:"11px",background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",padding:"6px 10px",color:"#fff",userSelect:"none",minWidth:v?"260px":"120px",maxWidth:"calc(100vw - 20px)",maxHeight:v?"calc(100vh - 100px)":"auto",overflowY:v?"auto":"visible",transition:"all 0.2s ease"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:()=>S(!v),children:[o.jsx("span",{style:{color:z(t),fontWeight:"bold",fontSize:"14px"},children:t}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"FPS"}),i&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:q(i.usedMB,i.totalMB),fontWeight:"bold"},children:i.usedMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"MB"})]}),b!==null&&Math.abs(b)>.5&&o.jsxs("span",{style:{color:Y(b),fontSize:"10px",marginLeft:"4px"},children:[b>0?"+":"",b.toFixed(1),"/m"]}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:"#ff9e4a",fontWeight:"bold"},children:E.process.rssMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"SRV"})]}),o.jsx("span",{style:{color:"#444",marginLeft:"auto",fontSize:"10px"},children:v?"▼":"▶"})]}),v&&o.jsxs("div",{style:{marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px"},children:[o.jsxs("div",{style:{display:"flex",gap:"4px",marginBottom:"8px",flexWrap:"wrap"},children:[o.jsx("button",{style:he("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:he("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:he("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:he("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:he("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:he("http"),onClick:()=>k("http"),children:"HTTP"})]}),N==="fps"&&o.jsxs("div",{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Current:"}),o.jsx("span",{style:{color:z(B.current)},children:B.current}),o.jsx("span",{style:{color:"#888"},children:"Min:"}),o.jsx("span",{style:{color:z(B.min)},children:B.min}),o.jsx("span",{style:{color:"#888"},children:"Max:"}),o.jsx("span",{style:{color:z(B.max)},children:B.max}),o.jsx("span",{style:{color:"#888"},children:"Avg:"}),o.jsx("span",{style:{color:z(B.avg)},children:B.avg})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"60s History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"30px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:a.slice(-60).map((J,de)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,J/60*100)}%`,background:z(J),opacity:.8}},de))})]})]}),N==="memory"&&i&&o.jsxs("div",{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Used:"}),o.jsxs("span",{style:{color:q(i.usedMB,i.totalMB)},children:[i.usedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Total:"}),o.jsxs("span",{children:[i.totalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Limit:"}),o.jsxs("span",{children:[i.limitMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Baseline:"}),o.jsxs("span",{children:[M??"—"," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Growth:"}),o.jsxs("span",{style:{color:ge>50?"#ff4a4a":ge>20?"#ffcc00":"#4aff9e"},children:[ge>0?"+":"",ge," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Rate:"}),o.jsx("span",{style:{color:Y(b)},children:b!==null?`${b.toFixed(2)} MB/min`:"—"})]}),o.jsx("div",{style:{marginBottom:"8px"},children:o.jsx("div",{style:{height:"8px",background:"rgba(255,255,255,0.1)",borderRadius:"4px",overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:`${i.usedMB/i.limitMB*100}%`,background:q(i.usedMB,i.totalMB),transition:"width 0.3s ease"}})})}),d.length>1&&o.jsxs("div",{children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"Memory History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"40px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:d.slice(-60).map((J,de)=>{const je=Math.min(...d.map(We=>We.heapMB)),qe=Math.max(...d.map(We=>We.heapMB))-je||1,Ke=(J.heapMB-je)/qe*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,Ke)}%`,background:J.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${J.heapMB}MB`},de)})})]}),U.agentCount>0&&o.jsxs("div",{style:{marginTop:"8px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:["Agent Memory (",U.agentCount,"):"]}),o.jsxs("div",{style:{fontSize:"10px"},children:[o.jsxs("div",{style:{color:"#4aff9e",fontWeight:"bold",marginBottom:"2px"},children:["Total: ",U.totalMB,"MB"]}),o.jsx("div",{style:{maxHeight:"50px",overflowY:"auto"},children:U.agents.slice(0,4).map((J,de)=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":"#666",maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB,"MB"]})]},de))})]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[i.usedMB," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsxs("span",{style:{color:"#9e4aff"},children:["DOM (",(C==null?void 0:C.nodeCount.toLocaleString())??0," nodes)"]}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",i.usedMB+((_==null?void 0:_.estimatedMB)??0)+Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)," MB"]})]})]})]})]}),N==="threejs"&&o.jsx("div",{children:h?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Geometries:"}),o.jsx("span",{style:{color:"#4aff9e"},children:h.geometries}),o.jsx("span",{style:{color:"#888"},children:"Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:h.textures}),o.jsx("span",{style:{color:"#888"},children:"Programs:"}),o.jsx("span",{style:{color:"#9e4aff"},children:h.programs})]}),d.length>1&&o.jsxs("div",{children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"Resource History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"40px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:d.slice(-60).map((J,de)=>{const je=Math.max(...d.map(xe=>xe.textures))||1;return o.jsx("div",{style:{width:"3px",height:`${J.textures/je*100}%`,background:"#ff9e4a",opacity:.8},title:`${J.textures} textures`},de)})})]}),o.jsx("div",{style:{color:"#666",fontSize:"9px",marginTop:"8px"},children:"Tip: Watch textures count. If it keeps increasing, there's a leak."})]}):o.jsxs("div",{style:{color:"#666",fontSize:"10px"},children:["Three.js stats unavailable.",o.jsx("br",{}),"SceneManager not exposed."]})}),N==="dom"&&o.jsx("div",{children:C?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"DOM Nodes:"}),o.jsx("span",{style:{color:C.nodeCount>5e3?"#ff4a4a":C.nodeCount>2e3?"#ffcc00":"#4aff9e"},children:C.nodeCount.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Canvases:"}),o.jsx("span",{style:{color:"#4a9eff"},children:C.canvasCount}),o.jsx("span",{style:{color:"#888"},children:"Images:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:C.imageCount}),o.jsx("span",{style:{color:"#888"},children:"Videos:"}),o.jsx("span",{style:{color:"#9e4aff"},children:C.videoCount})]}),_&&o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("span",{style:{color:"#888"},children:"GPU Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:_.count}),o.jsx("span",{style:{color:"#888"},children:"Est. VRAM:"}),o.jsxs("span",{style:{color:_.estimatedMB>100?"#ff4a4a":"#4aff9e"},children:["~",_.estimatedMB," MB"]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[(i==null?void 0:i.usedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#9e4aff"},children:"DOM (~0.5KB/node)"}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(C.nodeCount*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",((i==null?void 0:i.usedMB)??0)+((_==null?void 0:_.estimatedMB)??0)+Math.round(C.nodeCount*.5/1024)," MB"]})]})]})]}),o.jsx("div",{style:{color:"#666",fontSize:"9px",marginTop:"8px"},children:"Note: Task Manager shows more due to browser overhead, decoded images, and WebGL buffers."})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading DOM stats..."})}),N==="server"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Uptime:"}),o.jsx("span",{style:{color:"#4aff9e"},children:$(E.uptime)}),o.jsx("span",{style:{color:"#888"},children:"Heap Used:"}),o.jsxs("span",{style:{color:E.process.heapUsedMB>500?"#ff4a4a":"#4aff9e"},children:[E.process.heapUsedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Heap Total:"}),o.jsxs("span",{children:[E.process.heapTotalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"RSS:"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.rssMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"External:"}),o.jsxs("span",{children:[E.process.externalMB," MB"]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"System:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Load Avg:"}),o.jsx("span",{style:{color:E.system.loadAvg[0]>E.system.cpuCount?"#ff4a4a":"#4aff9e"},children:E.system.loadAvg.join(" ")}),o.jsx("span",{style:{color:"#888"},children:"CPUs:"}),o.jsx("span",{children:E.system.cpuCount}),o.jsx("span",{style:{color:"#888"},children:"Sys Memory:"}),o.jsxs("span",{children:[E.system.totalMemMB-E.system.freeMemMB," / ",E.system.totalMemMB," MB"]})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"WebSocket:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Clients:"}),o.jsx("span",{style:{color:"#4a9eff"},children:E.websocket.clients}),o.jsx("span",{style:{color:"#888"},children:"Sent:"}),o.jsx("span",{children:E.websocket.messagesSent.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Received:"}),o.jsx("span",{children:E.websocket.messagesReceived.toLocaleString()})]})]}),E.agents.total>0&&o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:["Agents (",E.agents.working,"w / ",E.agents.idle,"i / ",E.agents.total,"t):"]}),o.jsx("div",{style:{maxHeight:"80px",overflowY:"auto",fontSize:"10px"},children:E.agents.processes.map(J=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":J.status==="idle"?"#888":"#ff4a4a",maxWidth:"100px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB!=null?`${J.memoryMB}MB`:"—",J.pid?` (${J.pid})`:""]})]},J.id))})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading server metrics..."})}),N==="http"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Req/sec (30s):"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.http.reqPerSec}),o.jsx("span",{style:{color:"#888"},children:"Avg Latency:"}),o.jsxs("span",{style:{color:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e"},children:[E.http.avgLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Max Latency:"}),o.jsxs("span",{style:{color:E.http.maxLatencyMs>500?"#ff4a4a":E.http.maxLatencyMs>200?"#ffcc00":"#4aff9e"},children:[E.http.maxLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Recent Reqs:"}),o.jsx("span",{children:E.http.recentRequests})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Avg Latency:"}),o.jsx("div",{style:{height:"8px",background:"rgba(255,255,255,0.1)",borderRadius:"4px",overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:`${Math.min(100,E.http.avgLatencyMs/500*100)}%`,background:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e",transition:"width 0.3s ease"}})}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"8px",color:"#444",marginTop:"2px"},children:[o.jsx("span",{children:"0ms"}),o.jsx("span",{children:"500ms"})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Server Process:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"CPU (user):"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.cpuUser," ms"]}),o.jsx("span",{style:{color:"#888"},children:"CPU (system):"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:[E.process.cpuSystem," ms"]}),o.jsx("span",{style:{color:"#888"},children:"WS Clients:"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.websocket.clients})]})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading HTTP metrics..."})}),o.jsxs("div",{style:{display:"flex",gap:"4px",marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px",flexWrap:"wrap"},children:[o.jsx("button",{onClick:J=>{J.stopPropagation();const de=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&de.push("","--- Memory ---",`Heap Used: ${i.usedMB} MB`,`Heap Total: ${i.totalMB} MB`,`Heap Limit: ${i.limitMB} MB`,`Baseline: ${M??"N/A"} MB`,`Growth: ${ge>0?"+":""}${ge} MB`,`Growth Rate: ${b!==null?`${b.toFixed(2)} MB/min`:"N/A"}`),h&&de.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),U.agentCount>0&&(de.push("","--- Agent Memory ---",`Total: ${U.totalMB} MB`,`Agents: ${U.agentCount}`),U.agents.slice(0,5).forEach(xe=>{de.push(` ${xe.name}: ${xe.memoryMB} MB (${xe.status})`)})),C&&de.push("","--- DOM ---",`DOM Nodes: ${C.nodeCount.toLocaleString()}`,`Canvases: ${C.canvasCount}`,`Images: ${C.imageCount}`,`Videos: ${C.videoCount}`),_&&de.push("","--- Estimated Memory ---",`GPU Textures: ${_.count}`,`Est. VRAM: ~${_.estimatedMB} MB`,`Est. DOM: ~${Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)} MB`,`Est. Total: ~${((i==null?void 0:i.usedMB)??0)+_.estimatedMB+Math.round(((C==null?void 0:C.nodeCount)??0)*.5/1024)} MB`),E&&(de.push("","--- Server ---",`Uptime: ${$(E.uptime)}`,`Heap: ${E.process.heapUsedMB}/${E.process.heapTotalMB} MB`,`RSS: ${E.process.rssMB} MB`,`Load Avg: ${E.system.loadAvg.join(" ")}`,`System Memory: ${E.system.totalMemMB-E.system.freeMemMB}/${E.system.totalMemMB} MB`,"","--- WebSocket ---",`Clients: ${E.websocket.clients}`,`Sent: ${E.websocket.messagesSent}`,`Received: ${E.websocket.messagesReceived}`,"","--- HTTP ---",`Req/sec: ${E.http.reqPerSec}`,`Avg Latency: ${E.http.avgLatencyMs} ms`,`Max Latency: ${E.http.maxLatencyMs} ms`),E.agents.processes.length>0&&(de.push("","--- Agent Processes ---",`Total: ${E.agents.total} (${E.agents.working} working, ${E.agents.idle} idle)`),E.agents.processes.forEach(xe=>{de.push(` ${xe.name}: ${xe.memoryMB!=null?`${xe.memoryMB}MB`:"N/A"} (${xe.status})${xe.pid?` PID:${xe.pid}`:""}`)})));const je=de.join(`
145
+ `);navigator.clipboard.writeText(je).then(()=>{const xe=J.currentTarget,qe=xe.textContent;xe.textContent="Copied!",setTimeout(()=>{xe.textContent=qe},1e3)})},style:{flex:1,background:"rgba(74, 255, 158, 0.3)",border:"1px solid rgba(74, 255, 158, 0.5)",color:"#4aff9e",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Copy Stats"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),Ec.report();const de=window.__tideScene;de!=null&&de.logMemoryDiagnostics&&de.logMemoryDiagnostics()},style:{flex:1,background:"rgba(74, 158, 255, 0.3)",border:"1px solid rgba(74, 158, 255, 0.5)",color:"#4a9eff",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Console"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),fb.clear(),qd.reset(),Ec.reset(),r([]),f([]);const de=Ec.getUsage();de&&R(de.usedMB)},style:{flex:1,background:"rgba(255, 74, 74, 0.3)",border:"1px solid rgba(255, 74, 74, 0.5)",color:"#ff4a4a",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Reset"})]})]})]})}function ZW(){const n=Dj(),e=x.useCallback(t=>{W.setViewMode(t)},[]);return[n,e]}const eV=["3d","2d","dashboard"],tV=x.memo(function({className:e=""}){const{t}=ut(["common"]),[s,a]=ZW(),r=x.useRef(null),[i,c]=x.useState(null);x.useLayoutEffect(()=>{const f=r.current;if(!f)return;const h=f.querySelector(".view-mode-toggle__btn--active");h&&c({left:h.offsetLeft,width:h.offsetWidth})},[s]);const d=x.useCallback(f=>{if(f!==s){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:f}})),f==="3d"){requestAnimationFrame(()=>a(f));return}a(f)}},[s,a]);return o.jsxs("div",{className:`view-mode-toggle ${e}`,ref:r,children:[i&&o.jsx("div",{className:"view-mode-toggle__indicator",style:{left:i.left,width:i.width}}),eV.map(f=>o.jsxs("button",{className:`view-mode-toggle__btn ${s===f?"view-mode-toggle__btn--active":""}`,onClick:()=>d(f),title:t(`common:viewMode.descriptions.${f}`),children:[o.jsxs("span",{className:"view-mode-toggle__icon",children:[f==="2d"&&o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),o.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),o.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),f==="3d"&&o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),o.jsx("path",{d:"M2 17l10 5 10-5"}),o.jsx("path",{d:"M2 12l10 5 10-5"})]}),f==="dashboard"&&o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),o.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),o.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),o.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),o.jsx("span",{className:"view-mode-toggle__label",children:t(`common:viewMode.labels.${f}`)})]},f))]})});function ST({className:n}){const{t:e}=ut(["terminal"]),[t,s]=x.useState(!1),[a,r]=x.useState(null),i=Kx(),c=x.useCallback(async y=>{if(y.trim()){console.log("[VoiceAssistant] Transcribed:",y),s(!0),r(null);try{const S=await(await Lt(Et("/api/voice-assistant/process"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:y})})).json();if(S.success&&S.response)console.log("[VoiceAssistant] Response:",S.response),i.speak(S.response);else{const N=S.error||e("terminal:voiceAssistant.failedToProcess");console.error("[VoiceAssistant] Error:",N),r(N),i.speak(N)}}catch(v){console.error("[VoiceAssistant] Request failed:",v);const S=e("terminal:voiceAssistant.unavailable");r(S),i.speak(S)}finally{s(!1)}}},[i]),d=wT({language:"Spanish",model:"medium",onTranscription:c}),f=d.recording||d.transcribing||t||i.speaking,h=()=>d.error?`${e("terminal:voiceAssistant.error")}: ${d.error}`:a?`${e("terminal:voiceAssistant.error")}: ${a}`:d.recording?e("terminal:voiceAssistant.recording"):d.transcribing?e("terminal:voiceAssistant.transcribing"):t?e("terminal:voiceAssistant.processing"):i.speaking?e("terminal:voiceAssistant.speaking"):e("terminal:voiceAssistant.title"),m=()=>{const y=["voice-assistant-btn",n].filter(Boolean);return d.recording&&y.push("recording"),(d.transcribing||t)&&y.push("processing"),i.speaking&&y.push("speaking"),(a||d.error)&&y.push("error"),y.join(" ")},b=()=>{if(r(null),i.speaking){i.stop();return}d.transcribing||t||d.toggleRecording()};return o.jsxs("button",{className:m(),onClick:b,title:d.supported?h():e("terminal:voiceAssistant.notSupported"),disabled:!d.supported||d.transcribing||t,children:[d.recording?o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor",children:[o.jsx("path",{d:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"}),o.jsx("path",{d:"M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"})]}):i.speaking?o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5",fill:"currentColor"}),o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),o.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),o.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),o.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),f&&o.jsx("span",{className:"voice-assistant-indicator"})]})}const nV=x.memo(function({isOpen:e,onToggle:t,onShowTerminal:s,onOpenSidebar:a,onOpenToolbox:r,onOpenCommander:i,onOpenControls:c,onOpenSkills:d,mobileView:f}){const{t:h}=ut(["terminal","common"]),m=Br(),b=y=>{y(),t()};return o.jsxs(o.Fragment,{children:[m.experimentalVoiceAssistant&&o.jsx(ST,{className:"mobile-voice-assistant"}),f!=="terminal"&&o.jsx("button",{className:`mobile-fab-toggle ${e?"open":""}`,onClick:t,onTouchStart:y=>y.stopPropagation(),title:h(e?"terminal:mobileFab.closeMenu":"terminal:mobileFab.openMenu"),children:e?"✕":"☰"}),f==="3d"&&o.jsxs("div",{className:`mobile-fab-menu ${e?"open":""}`,children:[o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(s),onTouchEnd:y=>{y.preventDefault(),b(s)},title:h("terminal:mobileFab.showTerminal"),children:"💬"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(a),onTouchEnd:y=>{y.preventDefault(),b(a)},title:h("terminal:header.openSidebar"),children:"📋"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(r),onTouchEnd:y=>{y.preventDefault(),b(r)},title:h("common:floatingButtons.settingsAndTools"),children:"⚙️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(i),onTouchEnd:y=>{y.preventDefault(),b(i)},title:h("common:floatingButtons.commanderView"),children:"📊"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(c),onTouchEnd:y=>{y.preventDefault(),b(c)},title:h("common:floatingButtons.controls"),children:"⌨️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>b(d),onTouchEnd:y=>{y.preventDefault(),b(d)},title:h("common:floatingButtons.manageSkills"),children:"⭐"})]})]})}),sV=x.memo(function({onOpenToolbox:e,onOpenCommander:t,onOpenControls:s,onOpenSkills:a,onSpawnAgent:r,onSpawnBoss:i,onNewBuilding:c,onNewArea:d}){const{t:f}=ut(["common","terminal"]),h=Br();return o.jsxs(o.Fragment,{children:[h.experimentalVoiceAssistant&&o.jsx(ST,{}),o.jsx(Un,{content:f("common:floatingButtons.settingsAndTools"),position:"right",children:o.jsx("button",{className:"floating-settings-btn",onClick:e,"aria-label":f("common:floatingButtons.settingsAndTools"),children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})}),o.jsx(Un,{content:f("common:floatingButtons.commanderView"),position:"right",children:o.jsx("button",{className:"commander-toggle-btn",onClick:t,"aria-label":f("common:floatingButtons.commanderView"),children:o.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"3",y:"3",width:"7",height:"7"}),o.jsx("rect",{x:"14",y:"3",width:"7",height:"7"}),o.jsx("rect",{x:"3",y:"14",width:"7",height:"7"}),o.jsx("rect",{x:"14",y:"14",width:"7",height:"7"})]})})}),o.jsx(Un,{content:f("common:floatingButtons.controls"),position:"right",children:o.jsx("button",{className:"shortcuts-toggle-btn",onClick:s,"aria-label":f("common:floatingButtons.controls"),children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"4",y1:"21",x2:"4",y2:"14"}),o.jsx("line",{x1:"4",y1:"10",x2:"4",y2:"3"}),o.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"12"}),o.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"3"}),o.jsx("line",{x1:"20",y1:"21",x2:"20",y2:"16"}),o.jsx("line",{x1:"20",y1:"12",x2:"20",y2:"3"}),o.jsx("line",{x1:"1",y1:"14",x2:"7",y2:"14"}),o.jsx("line",{x1:"9",y1:"8",x2:"15",y2:"8"}),o.jsx("line",{x1:"17",y1:"16",x2:"23",y2:"16"})]})})}),o.jsx(Un,{content:f("common:floatingButtons.manageSkills"),position:"right",children:o.jsx("button",{className:"skills-toggle-btn",onClick:a,"aria-label":f("common:floatingButtons.manageSkills"),children:o.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"})})})}),o.jsx(Un,{content:f("common:agentBar.spawnNewAgent"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-agent-btn",onClick:r,"aria-label":f("common:agentBar.spawnNewAgent"),children:o.jsx("span",{className:"fab-spawn-icon",children:"+"})})}),o.jsx(Un,{content:f("common:agentBar.spawnBoss"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-boss-btn",onClick:i,"aria-label":f("common:agentBar.spawnBoss"),children:o.jsx("span",{className:"fab-spawn-icon",children:"👑"})})}),o.jsx(Un,{content:f("common:agentBar.addNewBuilding"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-building-btn",onClick:c,"aria-label":f("common:agentBar.addNewBuilding"),children:o.jsx("span",{className:"fab-spawn-icon",children:"🏢"})})}),o.jsx(Un,{content:f("common:agentBar.drawNewArea"),position:"right",children:o.jsx("button",{className:"fab-spawn-btn fab-spawn-area-btn",onClick:d,"aria-label":f("common:agentBar.drawNewArea"),children:o.jsx("span",{className:"fab-spawn-icon",children:"🔲"})})})]})}),aV=Ce.lazy(()=>gt(()=>import("./SpawnModal-IkjbZFhe.js"),__vite__mapDeps([17,3,1,4])).then(n=>({default:n.SpawnModal}))),rV=Ce.lazy(()=>gt(()=>import("./BossSpawnModal-BYeEp5OI.js"),__vite__mapDeps([18,3,1,4])).then(n=>({default:n.BossSpawnModal}))),iV=Ce.lazy(()=>gt(()=>import("./SubordinateAssignmentModal-fzxC42PS.js"),__vite__mapDeps([19,3,1,4])).then(n=>({default:n.SubordinateAssignmentModal}))),oV=Ce.lazy(()=>gt(()=>import("./index-FrQm2j1t.js"),__vite__mapDeps([20,3,1,4,21])).then(n=>({default:n.Toolbox}))),lV=Ce.lazy(()=>gt(()=>import("./index-IvXUXoCa.js"),__vite__mapDeps([22,3,1,4])).then(n=>({default:n.BuildingConfigModal}))),cV=Ce.lazy(()=>gt(()=>import("./index-CJXUPevi.js"),__vite__mapDeps([23,24,3,1,4])).then(n=>({default:n.CommanderView}))),uV=Ce.lazy(()=>gt(()=>import("./index-CMwlYuij.js").then(n=>n.y),[]).then(n=>({default:n.FileExplorerPanel}))),dV=Ce.lazy(()=>gt(()=>import("./index-CDC9XyS8.js"),__vite__mapDeps([25,3,1,4])).then(n=>({default:n.Spotlight}))),fV=Ce.lazy(()=>gt(()=>import("./ControlsModal-COpfbGtj.js"),__vite__mapDeps([26,3,1,4])).then(n=>({default:n.ControlsModal}))),pV=Ce.lazy(()=>gt(()=>import("./SkillsPanel-BrCcIF3N.js"),__vite__mapDeps([27,3,1,4])).then(n=>({default:n.SkillsPanel}))),hV=Ce.lazy(()=>gt(()=>Promise.resolve().then(()=>O2),void 0).then(n=>({default:n.AgentEditModal}))),mV=Ce.lazy(()=>gt(()=>import("./RestoreArchivedAreaModal-Dbc4G6uO.js"),__vite__mapDeps([28,3,1,4])).then(n=>({default:n.RestoreArchivedAreaModal}))),gV=Ce.lazy(()=>gt(()=>import("./IntegrationsPanel-sQyZpWqW.js"),__vite__mapDeps([29,3,1,4])).then(n=>({default:n.IntegrationsPanel}))),bV=Ce.lazy(()=>gt(()=>import("./MonitoringModal-Dw90UKnf.js"),__vite__mapDeps([30,3,1,4])).then(n=>({default:n.MonitoringModal}))),xV=Ce.lazy(()=>gt(()=>import("./WorkflowEditorPanel-CxAWtPcO.js"),__vite__mapDeps([31,3,1,4])).then(n=>({default:n.WorkflowEditorPanel}))),yV=Ce.lazy(()=>gt(()=>import("./TriggerManagerPanel-D9zIVYkR.js"),__vite__mapDeps([32,3,1,4])).then(n=>({default:n.TriggerManagerPanel})));function vV({spawnModal:n,bossSpawnModal:e,subordinateModal:t,toolboxModal:s,commanderModal:a,deleteConfirmModal:r,spotlightModal:i,controlsModal:c,skillsModal:d,integrationsModal:f,monitoringModal:h,workflowEditorModal:m,triggerManagerModal:b,buildingModal:y,agentEditModal:v,restoreArchivedModal:S,explorerModal:N,contextMenu:k,spawnPosition:C,spawnAreaId:A,explorerFolderPath:E,contextMenuActions:D,buildingInitialPosition:_,sceneConfig:F,onConfigChange:P,onToolChange:T,onOpenAreaExplorer:M,onDeleteSelectedAgents:R,pendingBuildingDelete:O,onCancelBuildingDelete:U,onConfirmBuildingDelete:H,showBackNavModal:I,onCloseBackNavModal:$,onLeave:z,onOpenPM2LogsModal:q,onOpenBossLogsModal:Y,onOpenDatabasePanel:B,onSyncScene:G}){const te=Fs(),V=O==="selected",ge=O&&O!=="selected"?te.buildings.get(O):null,he=te.selectedBuildingIds.size;return o.jsxs(x.Suspense,{fallback:null,children:[o.jsx(oV,{config:F,onConfigChange:P,onToolChange:T,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:J=>y.open(J||null),onOpenAreaExplorer:M,onOpenIntegrationsModal:J=>f.open(J),onOpenMonitoringModal:()=>h.open(),onOpenWorkflowEditor:()=>m.open(),onOpenTriggerManager:()=>b.open()}),o.jsx(lV,{isOpen:y.isOpen,onClose:y.close,buildingId:y.data,initialPosition:_||void 0}),o.jsx(aV,{isOpen:n.isOpen,onClose:n.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:C,spawnAreaId:A}),o.jsx(rV,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:C}),o.jsx(iV,{isOpen:t.isOpen,bossId:t.data||"",onClose:t.close}),v.isOpen&&v.data&&(()=>{const J=te.agents.get(v.data);return J?o.jsx(hV,{agent:J,isOpen:v.isOpen,onClose:v.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:J=>{J.key==="Escape"&&r.close(),J.key==="Enter"&&R()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:J=>J.stopPropagation(),children:[o.jsx("div",{className:"modal-header",children:"Remove Agents"}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[o.jsxs("p",{children:["Remove ",te.selectedAgentIds.size," selected agent",te.selectedAgentIds.size>1?"s":""," from the battlefield?"]}),o.jsx("p",{className:"confirm-modal-note",children:"Claude Code sessions will continue running in the background."})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:r.close,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:R,autoFocus:!0,children:"Remove"})]})]})}),(ge||V)&&o.jsx("div",{className:"modal-overlay visible",onClick:U,onKeyDown:J=>{J.key==="Escape"&&U(),J.key==="Enter"&&H()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:J=>J.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",V&&he>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[V?o.jsxs("p",{children:["Delete ",he," selected building",he>1?"s":"","?"]}):o.jsxs("p",{children:["Delete ",o.jsx("strong",{children:ge==null?void 0:ge.name}),"?"]}),o.jsxs("p",{className:"confirm-modal-note",children:["This will permanently remove the building",V&&he>1?"s":""," and ",V&&he>1?"their":"its"," configuration."]})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:U,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:H,autoFocus:!0,children:"Delete"})]})]})}),I&&o.jsx("div",{className:"modal-overlay navigation-confirm-overlay visible",onClick:$,onKeyDown:J=>{J.key==="Escape"&&$()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:J=>J.stopPropagation(),children:[o.jsx("div",{className:"modal-header",children:"Leave Tide Commander?"}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[o.jsx("p",{children:"Are you sure you want to leave this page?"}),o.jsx("p",{className:"confirm-modal-note",children:"Active Claude Code sessions will continue running in the background."})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:$,autoFocus:!0,children:"Stay"}),o.jsx("button",{className:"btn btn-danger",onClick:z,children:"Leave"})]})]})}),o.jsx(x.Profiler,{id:"CommanderView",onRender:pb,children:o.jsx(cV,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(uV,{isOpen:N.isOpen||E!==null||te.explorerAreaId!==null,areaId:N.id||te.explorerAreaId||null,folderPath:E,onChangeArea:J=>N.open(J),onClose:()=>{N.close(),W.closeFileExplorer()}}),o.jsx(dV,{isOpen:i.isOpen,onClose:i.close,onOpenSpawnModal:()=>n.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenFileExplorer:J=>N.open(J),onOpenPM2LogsModal:q,onOpenBossLogsModal:Y,onOpenDatabasePanel:B,onOpenMonitoringModal:()=>h.open()}),o.jsx(fV,{isOpen:c.isOpen,onClose:c.close}),o.jsx(pV,{isOpen:d.isOpen,onClose:d.close}),o.jsx(gV,{isOpen:f.isOpen,onClose:f.close,initialTab:f.data}),o.jsx(bV,{isOpen:h.isOpen,onClose:h.close}),o.jsx(xV,{isOpen:m.isOpen,onClose:m.close}),o.jsx(yV,{isOpen:b.isOpen,onClose:b.close}),o.jsx(mV,{isOpen:S.isOpen,restorePosition:S.data??null,onClose:S.close,onRestored:G}),o.jsx(co,{isOpen:k.isOpen,position:k.screenPosition,worldPosition:k.worldPosition,actions:D,onClose:k.close})]})}function wV(n){const e=n.trim();if(!e)return{ok:!0,normalizedUrl:""};let t;try{t=new URL(e)}catch{return{ok:!1,normalizedUrl:"",error:"Invalid URL format. Use http://host:port"}}return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,normalizedUrl:"",error:"Unsupported protocol. Use http or https"}:{ok:!0,normalizedUrl:e}}async function kV(n,e=5e3,t=fetch){if(!n)return{ok:!0};const a=`${n.replace(/\/$/,"")}/api/health`,r=new AbortController,i=setTimeout(()=>r.abort(),e);try{const c=await t(a,{method:"GET",cache:"no-store",signal:r.signal});return c.ok?{ok:!0}:{ok:!1,error:`Host reachable but unhealthy (${c.status})`}}catch(c){return c instanceof Error&&c.name==="AbortError"?{ok:!1,error:"Connection timed out while checking host"}:{ok:!1,error:"Host unreachable. Check URL, host, and port"}}finally{clearTimeout(i)}}const SV=4e3;function CV(){const n=jj(),[e,t]=x.useState(!1),[s,a]=x.useState(!1),[r,i]=x.useState(!0),[c,d]=x.useState(!1),[f,h]=x.useState(()=>Kb()),[m,b]=x.useState(!1),[y,v]=x.useState(null),[S,N]=x.useState(null),k=x.useRef(!0),C=x.useRef(!1),A=x.useCallback((P=7e3)=>W.getState().isConnected?Promise.resolve(!0):new Promise(T=>{let M=!1;const R=H=>{M||(M=!0,clearTimeout(U),O(),T(H))},O=W.subscribe(()=>{W.getState().isConnected&&R(!0)}),U=setTimeout(()=>R(!1),P)}),[]);x.useEffect(()=>{const P=setTimeout(()=>i(!1),3e3);return()=>clearTimeout(P)},[]),x.useEffect(()=>{if(n){C.current=!0,d(!1);return}if(C.current){i(!0),d(!0);const P=setTimeout(()=>{i(!1),d(!1)},1e4);return()=>clearTimeout(P)}},[n]),x.useEffect(()=>()=>{k.current=!1},[]),x.useEffect(()=>UD(P=>{h(P)}),[]);const E=x.useCallback(()=>{navigator.clipboard.writeText("bunx tide-commander").then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(()=>{})},[]),D=x.useCallback(async()=>{if(m)return;const P=Date.now(),T=()=>SV-(Date.now()-P);v(null),N("Validating URL");const M=f.trim()||"http://localhost:6200",R=wV(M);if(!R.ok){N(null),v(R.error||"Invalid backend URL");return}b(!0),N("Checking host reachability");const O=T();if(O<=0){b(!1),N(null),v("Connection timeout after 4 seconds");return}const U=await kV(R.normalizedUrl,O);if(!U.ok){if(!k.current)return;b(!1),N(null),T()<=0?v("Connection timeout after 4 seconds"):v(U.error||"Failed to reach host");return}HD(R.normalizedUrl),N("Connecting to server"),RR();const H=T();if(H<=0){b(!1),N(null),v("Connection timeout after 4 seconds");return}const I=await A(H);if(k.current){if(!I){b(!1),N(null),T()<=0?v("Connection timeout after 4 seconds"):v("Could not establish WebSocket connection. Verify host and auth token, then retry");return}b(!1),N("Connected"),v(null)}},[f,m,A]),_=x.useCallback(P=>{P.key==="Enter"&&!m&&D()},[D,m]),F=x.useCallback(()=>{t(!0)},[]);return n||e?null:r&&c?o.jsxs("div",{className:"reconnecting-toast",children:[o.jsx("span",{className:"reconnecting-spinner"}),"Reconnecting..."]}):r?null:o.jsx("div",{className:"not-connected-overlay",children:o.jsxs("div",{className:"not-connected-panel",children:[o.jsx("h2",{className:"not-connected-title",children:"Tide Commander"}),o.jsx("p",{className:"not-connected-description",children:"A visual multi-agent orchestrator for Claude Code and Codex. Deploy, control, and monitor your AI team from an RTS-inspired interface."}),o.jsx("p",{className:"not-connected-privacy",children:"Tide Commander syncs with Claude Code instances running on your local machine. No files or code are sent to this server."}),o.jsxs("div",{className:"not-connected-setup",children:[o.jsx("p",{className:"not-connected-setup-label",children:"Get started:"}),o.jsxs("div",{className:"not-connected-code",onClick:E,title:"Click to copy",children:[o.jsx("span",{children:"bunx tide-commander"}),o.jsx("span",{className:"not-connected-copy-icon",children:s?"✓":"⧉"})]})]}),o.jsxs("div",{className:"not-connected-url-section",children:[o.jsx("label",{className:"not-connected-url-label",htmlFor:"backend-url",children:"Backend URL"}),o.jsx("div",{className:"not-connected-url-row",children:o.jsx("input",{id:"backend-url",type:"text",className:"not-connected-url-input",placeholder:"http://localhost:6200",value:f,disabled:m,onChange:P=>{const T=P.target.value;h(T),y&&v(null)},onKeyDown:_})}),o.jsx("span",{className:"config-hint",children:"Leave empty for auto-detect"}),S&&!y&&o.jsx("div",{className:"not-connected-status","aria-live":"polite",children:S}),y&&o.jsx("div",{className:"not-connected-error","aria-live":"assertive",children:y})]}),o.jsxs("div",{className:"not-connected-actions",children:[o.jsx("button",{className:"not-connected-btn not-connected-btn-retry",onClick:()=>{D()},disabled:m,children:m?"Connecting...":"↻ Connect"}),o.jsx("button",{className:"not-connected-btn not-connected-btn-explore",onClick:F,children:"Explore"})]})]})})}const TA="tide-onboarding-dismissed";function AV({onCreateAgent:n}){const{t:e}=ut("common"),t=jj(),s=Sj(),[a,r]=x.useState(()=>sessionStorage.getItem(TA)==="1"),i=t&&!a&&s===0,c=x.useCallback(()=>{r(!0),sessionStorage.setItem(TA,"1")},[]),d=x.useCallback(()=>{c(),n()},[c,n]),f=x.useCallback(h=>{h.key==="Escape"&&c()},[c]);return i?o.jsx(Ba,{children:o.jsx("div",{className:"modal-overlay visible",onClick:c,onKeyDown:f,children:o.jsxs("div",{className:"modal onboarding-modal",onClick:h=>h.stopPropagation(),children:[o.jsxs("div",{className:"onboarding-header",children:[o.jsx("h2",{children:e("onboarding.title")}),o.jsx("p",{className:"onboarding-subtitle",children:e("onboarding.subtitle")})]}),o.jsxs("div",{className:"onboarding-steps",children:[o.jsxs("div",{className:"onboarding-step",children:[o.jsx("span",{className:"onboarding-step-number",children:"1"}),o.jsxs("div",{children:[o.jsx("strong",{children:e("onboarding.step1Title")}),o.jsx("p",{children:e("onboarding.step1Desc")})]})]}),o.jsxs("div",{className:"onboarding-step",children:[o.jsx("span",{className:"onboarding-step-number",children:"2"}),o.jsxs("div",{children:[o.jsx("strong",{children:e("onboarding.step2Title")}),o.jsx("p",{children:e("onboarding.step2Desc")})]})]}),o.jsxs("div",{className:"onboarding-step",children:[o.jsx("span",{className:"onboarding-step-number",children:"3"}),o.jsxs("div",{children:[o.jsx("strong",{children:e("onboarding.step3Title")}),o.jsx("p",{children:e("onboarding.step3Desc")})]})]})]}),o.jsxs("div",{className:"onboarding-actions",children:[o.jsx("button",{className:"btn onboarding-cta",onClick:d,autoFocus:!0,children:e("onboarding.createFirst")}),o.jsx("button",{className:"btn btn-secondary",onClick:c,children:e("onboarding.explore")})]})]})})}):null}function CT(){return{"Content-Type":"application/json","X-Auth-Token":Ir()}}async function jV(n){const e=await fetch(`${ra()}/api/areas/${n}/organize`,{method:"POST",headers:CT()});if(!e.ok)throw new Error(`Failed to organize area: ${e.statusText}`);const t=await e.json();return{organized:Array.isArray(t.organized)?t.organized:[],buildings:Array.isArray(t.buildings)?t.buildings:[]}}async function NV(){const n=await fetch(`${ra()}/api/areas/organize-all`,{method:"POST",headers:CT()});if(!n.ok)throw new Error(`Failed to organize all areas: ${n.statusText}`);const e=await n.json();return Array.isArray(e.organized)?{organized:e.organized,buildings:Array.isArray(e.buildings)?e.buildings:[]}:(Array.isArray(e.results)?e.results:[]).reduce((t,s)=>(t.organized.push(...s.organized),t.buildings.push(...s.buildings),t),{organized:[],buildings:[]})}function AT(n,e){var s,a;const t=W.getState();for(const r of n.organized){const i=t.agents.get(r.agentId);if(i){const c={...i,position:r.position};W.updateAgent(c),(s=e.current)==null||s.updateAgent(c,!0)}}for(const r of n.buildings){const i=t.buildings.get(r.buildingId);i&&(W.updateBuilding(r.buildingId,{position:r.position}),(a=e.current)==null||a.updateBuilding({...i,position:r.position}))}}function TV(n,e,t,s,a,r){const i=[];if(e.type==="agent"&&e.id){const d=t.get(e.id);if(d)return i.push({id:"select-agent",label:`Select ${d.name}`,icon:"👆",onClick:()=>{var f;W.selectAgent(e.id),(f=r.sceneRef.current)==null||f.refreshSelectionVisuals()}}),i.push({id:"focus-agent",label:"Focus Camera",icon:"🎯",onClick:()=>{var f;(f=r.sceneRef.current)==null||f.focusAgent(e.id)}}),i.push({id:"open-terminal",label:"Open Terminal",icon:"💬",onClick:()=>{W.selectAgent(e.id),W.setTerminalOpen(!0)}}),i.push({id:"edit-agent",label:"Edit Agent",icon:"✏️",onClick:()=>{r.openAgentEditModal(e.id)}}),i.push({id:"divider-agent",label:"",divider:!0,onClick:()=>{}}),i.push({id:"delete-agent",label:`Remove ${d.name}`,icon:"❌",danger:!0,onClick:()=>{var f;W.removeAgentFromServer(e.id),(f=r.sceneRef.current)==null||f.removeAgent(e.id),r.showToast("info","Agent Removed",`${d.name} removed from view`)}}),i}if(e.type==="area"&&e.id){const d=s.get(e.id);if(d)return i.push({id:"select-area",label:`Select "${d.name}"`,icon:"📐",onClick:()=>{W.selectArea(e.id),r.openToolboxModal()}}),d.directories&&d.directories.length>0&&i.push({id:"open-explorer",label:"Open File Explorer",icon:"📁",onClick:()=>{r.openExplorerModal(e.id)}}),i.push({id:"spawn-in-area",label:"Spawn Agent",icon:"🤖",onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-spawn-modal",{detail:{areaId:e.id,position:{x:d.center.x,z:d.center.z}}}))}}),i.push({id:"divider-area-layer",label:"",divider:!0,onClick:()=>{}}),i.push({id:"bring-to-front",label:"Bring to Front",icon:"⬆️",onClick:()=>{var f;W.bringAreaToFront(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),i.push({id:"send-to-back",label:"Send to Back",icon:"⬇️",onClick:()=>{var f;W.sendAreaToBack(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),d.assignedAgentIds.length>0&&i.push({id:"organize-area",label:"Organize Area",icon:"✨",onClick:()=>{jV(e.id).then(f=>{AT(f,r.sceneRef),r.showToast("success","Area Organized",`Arranged ${f.organized.length} agent${f.organized.length!==1?"s":""} in "${d.name}"`)}).catch(f=>{console.error("organize area error:",f),r.showToast("error","Organize Failed",f.message||"Failed to organize area")})}}),i.push({id:"divider-area",label:"",divider:!0,onClick:()=>{}}),i.push({id:"archive-area",label:`Archive "${d.name}"`,icon:"📦",onClick:()=>{var m,b;const f=d.assignedAgentIds.length;W.archiveArea(e.id,y=>W.stopAgent(y)),(m=r.sceneRef.current)==null||m.syncAreas(),(b=r.sceneRef.current)==null||b.syncAgents(Array.from(W.getState().agents.values()));const h=f>0?` (${f} agent${f>1?"s":""} stopped)`:"";r.showToast("info","Zone Archived",`"${d.name}" has been archived${h}`)}}),i.push({id:"delete-area",label:`Delete "${d.name}"`,icon:"🗑️",danger:!0,onClick:()=>{var f;W.deleteArea(e.id),(f=r.sceneRef.current)==null||f.syncAreas(),r.showToast("info","Area Deleted",`"${d.name}" has been deleted`)}}),i}if(e.type==="building"&&e.id){const d=a.get(e.id);if(d)return i.push({id:"select-building",label:`Select "${d.name}"`,icon:"🏢",onClick:()=>{W.selectBuilding(e.id),r.openToolboxModal()}}),i.push({id:"edit-building",label:"Edit Building",icon:"✏️",onClick:()=>{r.openBuildingModal(e.id)}}),i.push({id:"clone-building",label:"Clone Building",icon:"📋",onClick:()=>{const f={name:`${d.name} (Copy)`,type:d.type,style:d.style,color:d.color,scale:d.scale,position:{x:d.position.x+2,z:d.position.z+2},cwd:d.cwd,folderPath:d.folderPath,commands:d.commands,pm2:d.pm2,docker:d.docker,database:d.database,urls:d.urls,subordinateBuildingIds:d.subordinateBuildingIds};W.createBuilding(f),r.showToast("success","Building Cloned",`Created "${f.name}"`)}}),d.type==="folder"&&d.folderPath&&i.push({id:"open-folder",label:"Open Folder",icon:"📁",onClick:()=>{W.openFileExplorer(d.folderPath)}}),i.push({id:"divider-building",label:"",divider:!0,onClick:()=>{}}),i.push({id:"delete-building",label:`Delete "${d.name}"`,icon:"🗑️",danger:!0,onClick:()=>{r.requestBuildingDelete(e.id)}}),i}i.push({id:"spawn-agent",label:"Spawn Agent Here",icon:"🤖",shortcut:"N",onClick:()=>{r.setSpawnPosition(n),r.openSpawnModal()}}),i.push({id:"spawn-boss",label:"Spawn Boss Here",icon:"👑",onClick:()=>{r.setSpawnPosition(n),r.openBossSpawnModal()}}),i.push({id:"divider-1",label:"",divider:!0,onClick:()=>{}}),i.push({id:"draw-area",label:"Draw Area",icon:"📐",onClick:()=>{var d;(d=r.sceneRef.current)==null||d.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),r.showToast("info","Rectangle Tool","Click and drag on the battlefield to draw an area")}}),i.push({id:"new-building",label:"Place Building",icon:"🏢",onClick:()=>{r.openBuildingModal(null)}});const c=Array.from(s.values()).filter(d=>d.archived).length;return c>0&&i.push({id:"restore-archived",label:`Restore Archived Zone (${c})`,icon:"📦",onClick:()=>{r.openRestoreArchivedModal(n)}}),i.push({id:"divider-2",label:"",divider:!0,onClick:()=>{}}),i.push({id:"open-settings",label:"Settings",icon:"⚙️",onClick:()=>{r.openToolboxModal()}}),i.push({id:"open-commander",label:"Commander View",icon:"📊",shortcut:"⌘K",onClick:()=>{r.openCommanderModal()}}),i}const _V=Ce.lazy(()=>gt(()=>import("./index-Crfe-OV4.js"),__vite__mapDeps([33,3,1,4,34])).then(n=>({default:n.DatabasePanel}))),EV=Ce.lazy(()=>gt(()=>import("./PM2LogsModal-Bya_5RuS.js"),__vite__mapDeps([35,36,3,1,4])).then(n=>({default:n.PM2LogsModal}))),MV=Ce.lazy(()=>gt(()=>import("./DockerLogsModal-CwQx-3bW.js"),__vite__mapDeps([37,36,3,1,4])).then(n=>({default:n.DockerLogsModal}))),DV=Ce.lazy(()=>gt(()=>import("./BossLogsModal-B9STSmb6.js"),__vite__mapDeps([38,36,3,1,4])).then(n=>({default:n.BossLogsModal}))),RV=Ce.lazy(()=>gt(()=>import("./Scene2DCanvas-VknyyTen.js"),__vite__mapDeps([39,3,1,4,40])).then(n=>({default:n.Scene2DCanvas}))),OV=Ce.lazy(()=>gt(()=>import("./index-8bWbGeBs.js"),__vite__mapDeps([41,3,1,4,42])).then(n=>({default:n.DashboardView}))),LV=Ce.lazy(()=>gt(()=>import("./IframeModal-Cx0TmGPl.js"),__vite__mapDeps([43,3,1,4,44])).then(n=>({default:n.IframeModal})));function PV(){const{t:n}=ut(["common","notifications"]),e=x.useRef(null),t=x.useRef(null),s=xs(),a=xs(),r=xs(),i=xs(),c=xs(),d=xs(),f=xs(),h=xs(),m=xs(),b=xs(),y=xs(),v=xs(),S=xs(),N=xs(),k=xs(),C=xs(),A=WD(),E=eL(),D=VD(),[_,F]=x.useState(null),P=HR(),[T,M]=x.useState(!1),[R,O]=x.useState(null),[U,H]=x.useState(null),[I,$]=x.useState(null),[z,q]=x.useState(null),[Y,B]=x.useState(null),[G,te]=x.useState(null),[V,ge]=x.useState(null),[he,J]=x.useState(null),[de,je]=x.useState(null),[xe,qe]=x.useState(null),Ke=x.useCallback(Se=>{qe(Se),Se&&localStorage.setItem("tide-commander-last-database-building",Se)},[]),We=x.useCallback(()=>Ke(null),[Ke]),{handleMouseDown:Me,handleClick:ye}=Sa(We),Fe=x.useCallback(()=>je(null),[]),{handleMouseDown:Q,handleClick:Re}=Sa(Fe),pe=x.useRef(G);pe.current=G;const Ie=x.useCallback(Se=>{te(Se)},[]),Ne=x.useCallback(()=>pe.current,[]),fe=x.useRef(null),[Ue,rt]=x.useState(bj),[ct,oe]=x.useState(0),[Z,ae]=x.useState(!1),[be,ee]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[ce,Ve]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-view")==="tracking"?"tracking":"agents"),[we,ie]=x.useState(!1),[X,_e]=x.useState(!1),me=_j(),le=Dj(),De=ox(),Qe=lx(),se=Tj(),{showToast:Ee}=Oj(),{showAgentNotification:He}=BL(),{showBackNavModal:Ye,setShowBackNavModal:tt,handleLeave:at}=dO();JR({showToast:Ee,showAgentNotification:He});const[pt,Mt]=x.useState(!1);x.useEffect(()=>{const Se=nt=>{var wt;((wt=nt.detail)==null?void 0:wt.mode)==="3d"&&Mt(!0)};return window.addEventListener("tide:viewmode-switch-pressed",Se),()=>{window.removeEventListener("tide:viewmode-switch-pressed",Se)}},[]),x.useEffect(()=>{le==="3d"&&Mt(!0)},[le]);const Ze=XR({canvasRef:e,selectionBoxRef:t,viewMode:le,sceneMountKey:ct,showToast:Ee,showAgentNotification:He,toolboxModal:i,contextMenu:D,setHoveredAgentPopup:B,setBuildingPopup:Ie,getBuildingPopup:Ne,openBuildingModal:Se=>N.open(Se),openPM2LogsModal:Se=>ge(Se),openBossLogsModal:Se=>J(Se),openDatabasePanel:Se=>Ke(Se),onSceneLoadingChange:Mt}),lt=Sj(),xt=Pa(),Tt=ix(),en=rx(),Fn=KO(),Tn=YO(),qn=GO(),is=Br(),pn=x.useMemo(()=>Array.from(en),[en]),Dn=x.useRef(!1);oj("AppContent"),ZR(Ze),eO(Ze),tO(Ze),hO(),nO(Ze,Tn),sO(Ze,is.powerSaving),x.useEffect(()=>{var Se;document.title=((Se=is.tabTitle)==null?void 0:Se.trim())||"Tide Commander"},[is.tabTitle]),x.useEffect(()=>{var ls,Rn;if(Dn.current||typeof window>"u")return;const Se=new URLSearchParams(window.location.search),nt=(ls=Se.get("agentId"))==null?void 0:ls.trim(),yt=(Rn=Se.get("agentName"))==null?void 0:Rn.trim();if(!nt&&!yt||lt===0)return;const wt=W.getState().agents,ss=Se.get("openTerminal"),hn=ss?["1","true","yes"].includes(ss.toLowerCase()):!0;let kt=nt?wt.get(nt):void 0;if(!kt&&yt){const ur=yt.toLowerCase();kt=Array.from(wt.values()).find(Ti=>Ti.name.toLowerCase()===ur)}if(!kt){console.warn("[DeepLink] No matching agent found for query params",{rawAgentId:nt,rawAgentName:yt}),Dn.current=!0;return}W.selectAgent(kt.id),hn&&W.setTerminalOpen(!0),Se.delete("agentId"),Se.delete("agentName"),Se.delete("openTerminal");const wn=Se.toString(),bs=`${window.location.pathname}${wn?`?${wn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,bs),Dn.current=!0},[lt]),uO({sceneRef:Ze,spawnModal:s,commanderModal:c,explorerModal:A,spotlightModal:f,deleteConfirmModal:d,onRequestBuildingDelete:()=>q("selected"),onOpenDatabasePanel:Ke,onCloseDatabasePanel:We,databasePanelOpen:xe!==null}),Jt("spawn-modal",s.isOpen,s.close),Jt("boss-spawn-modal",a.isOpen,a.close),Jt("subordinate-modal",r.isOpen,r.close),Jt("toolbox-modal",i.isOpen,i.close),Jt("commander-modal",c.isOpen,c.close),Jt("delete-confirm-modal",d.isOpen,d.close),Jt("spotlight-modal",f.isOpen,f.close),Jt("controls-modal",h.isOpen,h.close),Jt("skills-modal",m.isOpen,m.close),Jt("integrations-modal",b.isOpen,b.close),Jt("monitoring-modal",y.isOpen,y.close),Jt("workflow-editor-modal",v.isOpen,v.close),Jt("trigger-manager-modal",S.isOpen,S.close),Jt("building-modal",N.isOpen,N.close),Jt("agent-edit-modal",k.isOpen,k.close),Jt("explorer-modal",A.isOpen||E!==null,()=>{A.close(),W.closeFileExplorer()}),Jt("context-menu",D.isOpen,D.close),Jt("mobile-sidebar",Z,()=>ae(!1)),Jt("mobile-fab-menu",X,()=>_e(!1)),Jt("file-viewer",De!==null,()=>W.clearFileViewerPath()),Jt("context-modal",Qe!==null,()=>W.closeContextModal()),Jt("terminal",se,()=>W.setTerminalOpen(!1)),Jt("pm2-logs-modal",V!==null,()=>ge(null)),Jt("boss-logs-modal",he!==null,()=>J(null)),Jt("database-panel",xe!==null,We),Jt("terminal-modal",de!==null,Fe);const it=x.useRef(se),At=x.useRef(m),ln=x.useRef(h);At.current=m,ln.current=h,x.useEffect(()=>{it.current&&!se&&(At.current.close(),ln.current.close()),it.current=se},[se]),x.useEffect(()=>{},[]),x.useEffect(()=>{if(me!=="3d"||le!=="3d")return;const Se=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(Se)},[me,le]);const nn=x.useCallback(Se=>{var nt,yt,wt,ss,hn,kt,wn,bs,ls,Rn;rt(Se),KR(Se),(nt=Ze.current)==null||nt.setCharacterScale(Se.characterScale),(yt=Ze.current)==null||yt.setScale3D(Se.scale3d),(wt=Ze.current)==null||wt.setTimeMode(Se.timeMode),(ss=Ze.current)==null||ss.setTerrainConfig(Se.terrain),(hn=Ze.current)==null||hn.setFloorStyle(Se.terrain.floorStyle),(kt=Ze.current)==null||kt.setGridVisible(Se.gridVisible),(wn=Ze.current)==null||wn.setAgentModelStyle(Se.modelStyle),(bs=Ze.current)==null||bs.setIdleAnimation(Se.animations.idleAnimation),(ls=Ze.current)==null||ls.setWorkingAnimation(Se.animations.workingAnimation),(Rn=Ze.current)==null||Rn.setFpsLimit(Se.fpsLimit)},[Ze]),os=x.useCallback(Se=>{var nt;if((nt=Ze.current)==null||nt.setDrawingTool(Se),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(Se),Se==="rectangle"||Se==="circle"){const yt=n(Se==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");Ee("info",yt,n("notifications:drawing.clickAndDrag"),3e3)}},[Ze,Ee]),ms=x.useCallback(Se=>{var nt;(nt=Ze.current)==null||nt.focusAgent(Se)},[Ze]),ts=x.useCallback(Se=>{W.killAgent(Se)},[]),ia=x.useCallback(Se=>{var nt;(nt=Ze.current)==null||nt.callSubordinates(Se)},[Ze]),Rt=x.useCallback(Se=>{W.setLastSelectionViaDirectClick(!0),W.selectAgent(Se),W.setTerminalOpen(!0)},[]),gs=x.useCallback(Se=>{A.open(Se)},[A]),ns=x.useCallback(()=>{N.open(null)},[N]),$s=x.useCallback(()=>{var Se;(Se=Ze.current)==null||Se.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),Ee("info",n("notifications:drawing.rectangleTool"),n("notifications:drawing.clickAndDrag"),3e3)},[Ze,Ee]),Hs=x.useCallback(Se=>{F(Se)},[]),_n=x.useCallback(()=>{F(null)},[]),Fa=x.useCallback(()=>{const Se=Array.from(W.getState().selectedAgentIds);Se.forEach(nt=>{var yt;W.removeAgentFromServer(nt),(yt=Ze.current)==null||yt.removeAgent(nt)}),d.close(),Ee("info",n("notifications:toast.agentsRemoved"),n("notifications:toast.agentsRemovedMsg",{count:Se.length}))},[Ee,d,Ze,n]),Ur=x.useCallback(()=>{var Se,nt;if(z==="selected"){const yt=Fn.size;W.deleteSelectedBuildings(),(Se=Ze.current)==null||Se.syncBuildings(),Ee("info",n("notifications:toast.buildingsDeleted"),n("notifications:toast.buildingsDeletedMsg",{count:yt}))}else if(z){const yt=Tt.get(z);W.deleteBuilding(z),(nt=Ze.current)==null||nt.syncBuildings(),Ee("info",n("notifications:toast.buildingDeleted"),n("notifications:toast.buildingDeletedMsg",{name:(yt==null?void 0:yt.name)||"Building"}))}q(null)},[z,Tt,Fn.size,Ee,Ze,n]),Aa=x.useMemo(()=>TV(D.worldPosition,D.target,W.getState().agents,xt,Tt,{showToast:Ee,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:Se=>A.open(Se),openBuildingModal:Se=>N.open(Se),openAgentEditModal:Se=>k.open(Se),requestBuildingDelete:Se=>q(Se),setSpawnPosition:O,openRestoreArchivedModal:Se=>C.open(Se),sceneRef:Ze}),[D.worldPosition,D.target,xt,Tt,s,a,N,i,c,A,k,C,Ee,Ze]);x.useEffect(()=>{!s.isOpen&&!a.isOpen&&(O(null),$(null))},[s.isOpen,a.isOpen]),x.useEffect(()=>{const Se=hn=>{const kt=hn.detail;$((kt==null?void 0:kt.areaId)||null),O((kt==null?void 0:kt.position)||null),s.open()},nt=hn=>{var bs,ls;const kt=hn.detail;if(!(kt!=null&&kt.buildingId))return;const wn=W.getState().buildings.get(kt.buildingId);wn&&(wn.type==="server"&&((bs=wn.pm2)!=null&&bs.enabled)?ge(kt.buildingId):wn.type==="boss"?J(kt.buildingId):wn.type==="database"?Ke(kt.buildingId):wn.type==="folder"&&wn.folderPath?W.openFileExplorer(wn.folderPath):wn.type==="terminal"&&((ls=wn.terminalStatus)!=null&&ls.url)?je(kt.buildingId):N.open(kt.buildingId))},yt=hn=>{const kt=hn.detail;kt!=null&&kt.buildingId&&N.open(kt.buildingId)},wt=hn=>{const kt=hn.detail;H((kt==null?void 0:kt.position)||null),N.open(null)},ss=hn=>{const kt=hn.detail;kt!=null&&kt.buildingId?je(kt.buildingId):kt!=null&&kt.url&&F(kt.url)};return window.addEventListener("tide:open-spawn-modal",Se),window.addEventListener("tide:building-action",nt),window.addEventListener("tide:building-edit",yt),window.addEventListener("tide:building-create",wt),window.addEventListener("tide:open-iframe-modal",ss),()=>{window.removeEventListener("tide:open-spawn-modal",Se),window.removeEventListener("tide:building-action",nt),window.removeEventListener("tide:building-edit",yt),window.removeEventListener("tide:building-create",wt),window.removeEventListener("tide:open-iframe-modal",ss)}},[s,N]);const oa=qn==="rectangle"||qn==="circle",Il=x.useCallback(()=>{var Se;(Se=Ze.current)==null||Se.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ze]),_s=x.useCallback(()=>_e(Se=>!Se),[]),lr=x.useCallback(()=>W.setMobileView("terminal"),[]),cr=x.useCallback(()=>ae(!0),[]);return o.jsxs("div",{className:`app ${se?"terminal-open":""} ${oa?"drawing-mode":""} ${be?"sidebar-collapsed":""} mobile-view-${me} view-mode-${le}`,children:[o.jsx(CV,{}),o.jsx(AV,{onCreateAgent:s.open}),o.jsx(JW,{visible:is.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(tV,{className:"app-view-mode-toggle"}),o.jsx(hj,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:T,title:"Auto-organize all agents in their areas",onClick:()=>{M(!0),NV().then(Se=>{AT(Se,Ze),Ee("success","Organized",`Arranged ${Se.organized.length} agent${Se.organized.length!==1?"s":""}`)}).catch(Se=>{console.error("organize all error:",Se),Ee("error","Organize Failed",Se.message||"Failed to organize")}).finally(()=>M(!1))},children:[T?"⏳":"✨"," Organize"]})]}),o.jsxs("main",{className:"main-content",children:[o.jsxs("div",{className:"battlefield-container",children:[P&&o.jsxs("div",{className:"workspace-switch-overlay",children:[o.jsx("div",{className:"workspace-switch-spinner"}),o.jsx("span",{className:"workspace-switch-text",children:"Switching workspace..."})]}),o.jsx(Ce.Suspense,{fallback:null,children:le==="dashboard"?o.jsx(OV,{onSelectAgent:Se=>W.selectAgent(Se),onFocusAgent:Se=>{W.setViewMode("3d"),ms(Se)},onKillAgent:ts,onSelectBuilding:Se=>W.selectBuilding(Se),onOpenTerminal:Se=>{W.selectAgent(Se),W.setTerminalOpen(!0)},onFocusZone:Se=>{W.setViewMode("3d");const nt=W.getState().areas.get(Se);nt&&nt.assignedAgentIds.length>0&&ms(nt.assignedAgentIds[0])}}):le==="2d"?o.jsx(RV,{onAgentClick:(Se,nt)=>{nt?W.addToSelection(Se):W.selectAgent(Se)},onAgentDoubleClick:Se=>{if(window.innerWidth<=768){W.openTerminalOnMobile(Se);return}W.selectAgent(Se),W.setTerminalOpen(!0)},onBuildingClick:(Se,nt)=>{W.selectBuilding(Se);const yt=W.getState().buildings.get(Se);(yt==null?void 0:yt.type)==="folder"&&yt.folderPath?W.openFileExplorer(yt.folderPath):((yt==null?void 0:yt.type)==="server"||(yt==null?void 0:yt.type)==="boss"||(yt==null?void 0:yt.type)==="database")&&(fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>{Ie({buildingId:Se,screenPos:nt,fromClick:!0}),fe.current=null},150))},onBuildingDoubleClick:Se=>{var yt;fe.current&&(clearTimeout(fe.current),fe.current=null),Ie(null);const nt=W.getState().buildings.get(Se);(nt==null?void 0:nt.type)==="server"&&((yt=nt.pm2)!=null&&yt.enabled)?ge(Se):(nt==null?void 0:nt.type)==="boss"?J(Se):(nt==null?void 0:nt.type)==="database"?Ke(Se):(nt==null?void 0:nt.type)==="folder"&&nt.folderPath?W.openFileExplorer(nt.folderPath):N.open(Se)},onGroundClick:()=>{W.selectAgent(null),W.selectBuilding(null)},onAreaDoubleClick:Se=>{W.selectArea(Se),i.open()},onContextMenu:(Se,nt,yt)=>{const wt=yt?{type:yt.type,id:yt.id}:{type:"ground"};D.open(Se,nt,wt)},onMoveCommand:(Se,nt)=>{const wt=Se.length,ss=[];if(wt===1)ss.push({x:nt.x,y:0,z:nt.z});else if(wt<=6){const hn=1.2*Math.max(1,wt/3);for(let kt=0;kt<wt;kt++){const wn=kt/wt*Math.PI*2-Math.PI/2;ss.push({x:nt.x+Math.cos(wn)*hn,y:0,z:nt.z+Math.sin(wn)*hn})}}else{const hn=Math.ceil(Math.sqrt(wt)),kt=Math.ceil(wt/hn),wn=(hn-1)*1.2/2,bs=(kt-1)*1.2/2;for(let ls=0;ls<wt;ls++){const Rn=ls%hn,ur=Math.floor(ls/hn);ss.push({x:nt.x+Rn*1.2-wn,y:0,z:nt.z+ur*1.2-bs})}}Se.forEach((hn,kt)=>{W.moveAgent(hn,ss[kt])})},onBuildingDragMove:(Se,nt)=>{var wt;const yt=W.getState().buildings.get(Se);yt&&(W.getState().buildings.set(Se,{...yt,position:{x:nt.x,z:nt.z}}),(wt=window.__tideScene2D)==null||wt.syncBuildings())},onBuildingDragEnd:(Se,nt)=>{W.updateBuildingPosition(Se,nt)},scale2d:Ue.scale2d,showTaskLabels:Ue.show2DTaskLabels,showGrid:Ue.gridVisible,fpsLimit:Ue.fpsLimit}):o.jsxs(Ce.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:t,id:"selection-box"})]},ct)}),pt&&o.jsxs("div",{className:"scene-loading-overlay",children:[o.jsx("div",{className:"scene-loading-overlay__spinner"}),o.jsx("span",{className:"scene-loading-overlay__label",children:"Loading 3D scene…"})]})]}),o.jsx(nV,{isOpen:X,onToggle:_s,onShowTerminal:lr,onOpenSidebar:cr,onOpenToolbox:i.open,onOpenCommander:c.open,onOpenControls:h.open,onOpenSkills:m.open,mobileView:me}),Z&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>ae(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${be?"is-collapsed":""} ${we?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)ae(!Z);else{const nt=!be;ee(nt),localStorage.setItem("tide-commander-sidebar-collapsed",String(nt))}},title:be?"Open sidebar":"Close sidebar",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:we?o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"10",r:"3"}),o.jsx("line",{x1:"12",y1:"13",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]}):o.jsx("polyline",{points:be?"15 18 9 12 15 6":"9 18 15 12 9 6"})})}),o.jsxs("aside",{className:`sidebar ${Z?"sidebar-open":""} ${be?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>ae(!1),title:"Close sidebar",children:"✕"}),o.jsxs("div",{className:"sidebar-view-toggle",role:"tablist","aria-label":"Sidebar view",children:[o.jsx("button",{type:"button",role:"tab","aria-selected":ce==="agents",className:`sidebar-view-toggle-btn${ce==="agents"?" active":""}`,onClick:()=>{Ve("agents"),localStorage.setItem("tide-commander-sidebar-view","agents")},title:n("common:sidebar.agentsView",{defaultValue:"Agents"}),children:n("common:sidebar.agentsView",{defaultValue:"Agents"})}),o.jsxs("button",{type:"button",role:"tab","aria-selected":ce==="tracking",className:`sidebar-view-toggle-btn${ce==="tracking"?" active":""}`,onClick:()=>{Ve("tracking"),localStorage.setItem("tide-commander-sidebar-view","tracking")},title:n("common:sidebar.trackingBoard",{defaultValue:"Tracking Board"}),children:[o.jsx("span",{className:"sidebar-view-toggle-icon",children:"▥"}),n("common:sidebar.trackingBoard",{defaultValue:"Tracking Board"})]})]}),ce==="tracking"?o.jsx("div",{className:"sidebar-section sidebar-tracking-section",children:o.jsx("div",{className:"sidebar-tracking-body",children:o.jsx(Hj,{activeAgentId:pn[0]??"",onSelectAgent:Rt})})}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:pb,children:o.jsx(aP,{onFocusAgent:ms,onKillAgent:ts,onCallSubordinates:ia,onOpenAreaExplorer:gs})})})]}),o.jsx(x.Profiler,{id:"GuakeOutputPanel",onRender:pb,children:o.jsx(DW,{})})]}),o.jsx(sV,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenControls:h.open,onOpenSkills:m.open,onSpawnAgent:s.open,onSpawnBoss:a.open,onNewBuilding:ns,onNewArea:$s}),o.jsx(UW,{activeTool:qn,onExit:Il}),Y&&(()=>{const Se=W.getState().agents.get(Y.agentId);return Se?o.jsx(VW,{agent:Se,screenPos:Y.screenPos,onClose:()=>B(null)}):null})(),G&&(()=>{const Se=Tt.get(G.buildingId);if(!Se)return null;const nt=()=>Ie(null);return Se.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:nt}),o.jsx(QW,{building:Se,screenPos:G.screenPos,onClose:nt,onOpenSettings:()=>{nt(),N.open(G.buildingId)},onOpenLogsModal:()=>{nt(),J(G.buildingId)},onOpenUrlInModal:Hs})]}):Se.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:nt}),o.jsx(XW,{building:Se,screenPos:G.screenPos,onClose:nt,onOpenSettings:()=>{nt(),N.open(G.buildingId)},onOpenDatabasePanel:()=>{nt(),Ke(G.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:nt}),o.jsx(GW,{building:Se,screenPos:G.screenPos,onClose:nt,onOpenSettings:()=>{nt(),N.open(G.buildingId)},onOpenLogsModal:()=>{ge(G.buildingId)},onOpenUrlInModal:Hs})]})})(),V&&(()=>{var nt;const Se=Tt.get(V);return Se?(nt=Se.docker)!=null&&nt.enabled?o.jsx(MV,{building:Se,isOpen:!0,onClose:()=>ge(null)}):o.jsx(EV,{building:Se,isOpen:!0,onClose:()=>ge(null)}):null})(),he&&(()=>{const Se=Tt.get(he);return Se?o.jsx(DV,{building:Se,isOpen:!0,onClose:()=>J(null)}):null})(),xe&&(()=>{const Se=Tt.get(xe);return Se?o.jsx("div",{className:"modal-overlay visible",onMouseDown:Me,onClick:ye,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(_V,{building:Se,onClose:We})})}):null})(),de&&(()=>{var nt;const Se=Tt.get(de);return!Se||!((nt=Se.terminalStatus)!=null&&nt.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:Q,onClick:Re,children:o.jsxs("div",{className:"terminal-modal-container",children:[o.jsxs("div",{className:"terminal-modal-header",children:[o.jsxs("span",{className:"terminal-modal-title",children:["Terminal - ",Se.name]}),o.jsx("button",{className:"terminal-modal-close",onClick:Fe,children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx(Hb,{terminalUrl:Se.terminalStatus.url,visible:!0})]})})})(),o.jsx(LV,{url:_||"",title:_?`Preview - ${_}`:"",isOpen:!!_,onClose:_n}),o.jsx(HW,{onFocusAgent:ms,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:ns,onNewAreaClick:$s}),o.jsx(vV,{spawnModal:s,bossSpawnModal:a,subordinateModal:r,toolboxModal:i,commanderModal:c,deleteConfirmModal:d,spotlightModal:f,controlsModal:h,skillsModal:m,integrationsModal:b,monitoringModal:y,workflowEditorModal:v,triggerManagerModal:S,buildingModal:N,buildingInitialPosition:U,agentEditModal:k,restoreArchivedModal:C,explorerModal:A,contextMenu:D,spawnPosition:R,spawnAreaId:I,explorerFolderPath:E,contextMenuActions:Aa,sceneConfig:Ue,onConfigChange:nn,onToolChange:os,onOpenAreaExplorer:gs,onDeleteSelectedAgents:Fa,pendingBuildingDelete:z,onCancelBuildingDelete:()=>q(null),onConfirmBuildingDelete:Ur,showBackNavModal:Ye,onCloseBackNavModal:()=>tt(!1),onLeave:at,onOpenPM2LogsModal:Se=>ge(Se),onOpenBossLogsModal:Se=>J(Se),onOpenDatabasePanel:Se=>Ke(Se),onSyncScene:()=>{var Se,nt;(Se=Ze.current)==null||Se.syncAreas(),(nt=Ze.current)==null||nt.syncAgents(Array.from(W.getState().agents.values()))}})]})}function IV(){return o.jsx(CL,{children:o.jsx(IL,{children:o.jsx(PV,{})})})}class BV extends x.Component{constructor(t){super(t);et(this,"handleReload",()=>{window.location.reload()});et(this,"handleDismiss",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){console.error("[Tide] React Error:",t,s),this.setState({errorInfo:s})}render(){if(this.state.hasError){const{error:t,errorInfo:s}=this.state;return o.jsx("div",{style:{position:"fixed",inset:0,background:"#1a1a2e",color:"#fff",fontFamily:"monospace",padding:"32px",overflow:"auto",zIndex:99999},children:o.jsxs("div",{style:{maxWidth:"900px",margin:"0 auto"},children:[o.jsxs("h1",{style:{color:"#ff4a4a",fontSize:"24px",marginBottom:"16px",display:"flex",alignItems:"center",gap:"12px"},children:[o.jsx("span",{style:{fontSize:"32px"},children:"💥"}),Sn.t("errors:crash.title")]}),o.jsx("div",{style:{background:"#2a2a3e",borderRadius:"8px",padding:"16px",marginBottom:"16px"},children:o.jsxs("div",{style:{color:"#ff6b6b",fontSize:"18px",marginBottom:"8px"},children:[t==null?void 0:t.name,": ",t==null?void 0:t.message]})}),o.jsxs("div",{style:{background:"#2a2a3e",borderRadius:"8px",padding:"16px",marginBottom:"16px"},children:[o.jsx("div",{style:{color:"#888",marginBottom:"8px",fontSize:"12px"},children:Sn.t("errors:crash.stackTrace")}),o.jsx("pre",{style:{color:"#ccc",fontSize:"12px",lineHeight:"1.5",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:t==null?void 0:t.stack})]}),(s==null?void 0:s.componentStack)&&o.jsxs("div",{style:{background:"#2a2a3e",borderRadius:"8px",padding:"16px",marginBottom:"16px"},children:[o.jsx("div",{style:{color:"#888",marginBottom:"8px",fontSize:"12px"},children:Sn.t("errors:crash.componentStack")}),o.jsx("pre",{style:{color:"#ccc",fontSize:"12px",lineHeight:"1.5",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:s.componentStack})]}),o.jsxs("div",{style:{display:"flex",gap:"12px"},children:[o.jsx("button",{onClick:this.handleReload,style:{background:"#4a9eff",color:"#fff",border:"none",borderRadius:"6px",padding:"12px 24px",fontSize:"14px",cursor:"pointer"},children:Sn.t("common:buttons.reloadPage")}),o.jsx("button",{onClick:this.handleDismiss,style:{background:"#444",color:"#fff",border:"none",borderRadius:"6px",padding:"12px 24px",fontSize:"14px",cursor:"pointer"},children:Sn.t("common:buttons.tryToContinue")})]}),o.jsx("div",{style:{marginTop:"24px",color:"#666",fontSize:"12px"},children:Sn.t("errors:crash.checkConsole")})]})})}return this.props.children}}R9();document.addEventListener("wheel",n=>{if(Math.abs(n.deltaX)>Math.abs(n.deltaY)&&Math.abs(n.deltaX)>0){const e=n.target;if(e.tagName==="CANVAS"){n.preventDefault();return}let t=e;for(;t&&t!==document.documentElement;){if(t.scrollWidth>t.clientWidth)return;t=t.parentElement}n.preventDefault()}},{passive:!1});const jT=document.getElementById("app");if(!jT)throw new Error("Could not find #app container");const FV=vM.createRoot(jT);FV.render(o.jsx(Ce.StrictMode,{children:o.jsx(x.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(BV,{children:o.jsx(IV,{})})})}));console.log("[Tide] Tide Commander initialized");export{Rc as $,NL as A,ux as B,Nn as C,jL as D,zD as E,xq as F,fp as G,Vb as H,Rl as I,ix as J,Pa as K,rx as L,nL as M,Ia as N,ZV as O,TL as P,yq as Q,n9 as R,dt as S,rs as T,ka as U,fq as V,Lt as W,Fj as X,vq as Y,R2 as Z,nu as _,cx as a,sa as a$,Xd as a0,rg as a1,er as a2,bp as a3,dq as a4,mo as a5,Bf as a6,VV as a7,AL as a8,ob as a9,FD as aA,iW as aB,x6 as aC,y6 as aD,S6 as aE,nq as aF,VO as aG,Gb as aH,Yb as aI,jf as aJ,kq as aK,gt as aL,BN as aM,wq as aN,FN as aO,zN as aP,ou as aQ,Ns as aR,Ts as aS,N6 as aT,T6 as aU,Oj as aV,$g as aW,_6 as aX,co as aY,Dp as aZ,IN as a_,oq as aa,Ir as ab,WV as ac,aq as ad,Nx as ae,Xs as af,su as ag,Jf as ah,ra as ai,Ba as aj,Kb as ak,UD as al,Sn as am,RR as an,HD as ao,lq as ap,cq as aq,uq as ar,iq as as,iL as at,Ok as au,Cj as av,Jt as aw,u5 as ax,ZN as ay,fx as az,fL as b,Wj as b0,D6 as b1,qx as b2,Bb as b3,o6 as b4,tL as b5,gb as b6,eq as b7,tq as b8,oO as b9,lO as ba,D2 as bb,JV as bc,QV as bd,sq as be,ax as bf,GL as bg,T2 as bh,E2 as bi,pq as bj,Au as bk,_L as bl,hq as bm,bq as bn,mq as bo,XV as bp,KV as bq,gq as br,OR as bs,LR as bt,Ec as bu,Qb as bv,rq as c,pL as d,jx as e,Fs as f,r9 as g,Sa as h,Sl as i,o as j,fu as k,Et as l,Yk as m,xn as n,ea as o,GV as p,qV as q,x as r,W as s,qd as t,ut as u,hp as v,YV as w,zR as x,$R as y,Ce as z};