tide-commander 1.37.2 → 1.38.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 (41) hide show
  1. package/dist/assets/{BossLogsModal-C9c6b6JM.js → BossLogsModal-Bn3z56OP.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-dSXYldID.js → BossSpawnModal-CWxP-MSv.js} +1 -1
  3. package/dist/assets/{ControlsModal-C_W0XTlE.js → ControlsModal-B5r9l6t1.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-CUweGxhz.js → DockerLogsModal-CWwOgxQG.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-DU_lcIBD.js → EmbeddedEditor-CePY44FJ.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-DTAkTnzL.js → GmailOAuthSetup-zVmKkZLJ.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-B83vPcAW.js → GoogleOAuthSetup-DXSCMIOU.js} +1 -1
  8. package/dist/assets/{IframeModal-3rIUuKKu.js → IframeModal-BsbB4AMI.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-CJviFK3q.js → IntegrationsPanel-1xcUvOle.js} +2 -2
  10. package/dist/assets/{LogViewerModal-C9qFaC8V.js → LogViewerModal-DVS-zxfP.js} +1 -1
  11. package/dist/assets/{MonitoringModal-DRZrxL7t.js → MonitoringModal-DWk0piqs.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-BLzKH4ql.js → PM2LogsModal-GxDWxG5c.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-DHH8QKkx.js → RestoreArchivedAreaModal-DvbQVeiA.js} +1 -1
  14. package/dist/assets/{SaveSnapshotModal-BTvvgNqk.js → SaveSnapshotModal-DpONGDMt.js} +1 -1
  15. package/dist/assets/{Scene2DCanvas-Gu0Pplgl.js → Scene2DCanvas-DLvMkm2q.js} +1 -1
  16. package/dist/assets/{SceneManager-BD0UwiqS.js → SceneManager-BgjRQCpO.js} +1 -1
  17. package/dist/assets/{SkillsPanel-Btfm8DLY.js → SkillsPanel-DqqJjbX5.js} +1 -1
  18. package/dist/assets/{SnapshotManager-BgCuvtUx.js → SnapshotManager-4ig8bV_o.js} +1 -1
  19. package/dist/assets/{SpawnModal-ByhvPfN7.js → SpawnModal-D2e4lCt9.js} +1 -1
  20. package/dist/assets/{SubordinateAssignmentModal-5Re0nGK9.js → SubordinateAssignmentModal-B_rjqVum.js} +1 -1
  21. package/dist/assets/{SupervisorPanel-DtNzjH1r.js → SupervisorPanel-BAXOUwAk.js} +1 -1
  22. package/dist/assets/{TriggerManagerPanel-DUXzcjBS.js → TriggerManagerPanel-D48mxJNq.js} +1 -1
  23. package/dist/assets/{WorkflowEditorPanel-CCauefUO.js → WorkflowEditorPanel-DkzFKMCZ.js} +1 -1
  24. package/dist/assets/{index-DtDea-zV.js → index-BoWUyxxn.js} +1 -1
  25. package/dist/assets/{index-CPBP46l5.js → index-BrgM4K8j.js} +1 -1
  26. package/dist/assets/{index-BG-fI4o6.js → index-CdlqvN8h.js} +1 -1
  27. package/dist/assets/{index-DTO0LlmC.js → index-CsBPIIxt.js} +1 -1
  28. package/dist/assets/{index-BakRazz4.js → index-D3k7Y2rz.js} +1 -1
  29. package/dist/assets/{index-Bma1pZ6y.js → index-DENcwRRk.js} +2 -2
  30. package/dist/assets/{index-DfBVuA_K.js → index-DHFWfrE-.js} +1 -1
  31. package/dist/assets/{index-Bl5TthnX.js → index-DWfphUcy.js} +3 -3
  32. package/dist/assets/{main-lr_lRuBZ.js → main-sZyyVmvr.js} +4 -4
  33. package/dist/assets/{web-DOowQZI5.js → web-CmQWPACi.js} +1 -1
  34. package/dist/assets/{web-CV2dsnZj.js → web-GvCQTLgg.js} +1 -1
  35. package/dist/index.html +1 -1
  36. package/dist/src/packages/server/integrations/slack/index.js +17 -0
  37. package/dist/src/packages/server/integrations/slack/slack-client.js +63 -0
  38. package/dist/src/packages/server/integrations/slack/slack-config.js +1 -1
  39. package/dist/src/packages/server/integrations/slack/slack-routes.js +49 -1
  40. package/dist/src/packages/server/integrations/slack/slack-skill.js +31 -0
  41. 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-Bma1pZ6y.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-Chj50gSY.js","assets/web-DOowQZI5.js","assets/SceneManager-BD0UwiqS.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-ByhvPfN7.js","assets/BossSpawnModal-dSXYldID.js","assets/SubordinateAssignmentModal-5Re0nGK9.js","assets/index-DfBVuA_K.js","assets/index-Bykeknjl.css","assets/index-DtDea-zV.js","assets/index-DTO0LlmC.js","assets/index-Bl5TthnX.js","assets/SupervisorPanel-DtNzjH1r.js","assets/index-BakRazz4.js","assets/ControlsModal-C_W0XTlE.js","assets/SkillsPanel-Btfm8DLY.js","assets/SnapshotManager-BgCuvtUx.js","assets/RestoreArchivedAreaModal-DHH8QKkx.js","assets/IntegrationsPanel-CJviFK3q.js","assets/MonitoringModal-DRZrxL7t.js","assets/WorkflowEditorPanel-CCauefUO.js","assets/TriggerManagerPanel-DUXzcjBS.js","assets/index-CPBP46l5.js","assets/index-CprCD9du.css","assets/PM2LogsModal-BLzKH4ql.js","assets/LogViewerModal-C9qFaC8V.js","assets/DockerLogsModal-CUweGxhz.js","assets/BossLogsModal-C9c6b6JM.js","assets/Scene2DCanvas-Gu0Pplgl.js","assets/Scene2DCanvas-DwXbvB-b.css","assets/index-BG-fI4o6.js","assets/index-BZyCMBzi.css","assets/IframeModal-3rIUuKKu.js","assets/IframeModal-DJkCGwT6.css","assets/SaveSnapshotModal-BTvvgNqk.js"])))=>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-DENcwRRk.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-Chj50gSY.js","assets/web-CmQWPACi.js","assets/SceneManager-BgjRQCpO.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-D2e4lCt9.js","assets/BossSpawnModal-CWxP-MSv.js","assets/SubordinateAssignmentModal-B_rjqVum.js","assets/index-DHFWfrE-.js","assets/index-Bykeknjl.css","assets/index-BoWUyxxn.js","assets/index-CsBPIIxt.js","assets/index-DWfphUcy.js","assets/SupervisorPanel-BAXOUwAk.js","assets/index-D3k7Y2rz.js","assets/ControlsModal-B5r9l6t1.js","assets/SkillsPanel-DqqJjbX5.js","assets/SnapshotManager-4ig8bV_o.js","assets/RestoreArchivedAreaModal-DvbQVeiA.js","assets/IntegrationsPanel-1xcUvOle.js","assets/MonitoringModal-DWk0piqs.js","assets/WorkflowEditorPanel-DkzFKMCZ.js","assets/TriggerManagerPanel-D48mxJNq.js","assets/index-BrgM4K8j.js","assets/index-CprCD9du.css","assets/PM2LogsModal-GxDWxG5c.js","assets/LogViewerModal-DVS-zxfP.js","assets/DockerLogsModal-CWwOgxQG.js","assets/BossLogsModal-Bn3z56OP.js","assets/Scene2DCanvas-DLvMkm2q.js","assets/Scene2DCanvas-DwXbvB-b.css","assets/index-CdlqvN8h.js","assets/index-BZyCMBzi.css","assets/IframeModal-BsbB4AMI.js","assets/IframeModal-DJkCGwT6.css","assets/SaveSnapshotModal-DpONGDMt.js"])))=>i.map(i=>d[i]);
2
2
  var TE=Object.defineProperty;var _E=(t,e,n)=>e in t?TE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Xe=(t,e,n)=>_E(t,typeof e!="symbol"?e+"":e,n);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as jx,g as Xu,a as ej,c as J0}from"./vendor-react--Eh9ivFN.js";import{T as EE,a as Ob,b as tj,L as nj,c as Cu,F as up,M as cr,V as sj,C as Hr,d as lr,S as Br,e as ME,P as DE,D as Lb,f as dp,g as wo,I as RE,Q as aj,h as OE,O as rj,i as LE,j as IE,B as Au,k as PE,l as ij,N as BE,m as FE,n as zE,o as Ib,p as oj,R as Pb,q as $E,r as UE,s as HE,t as Jf,u as WE,v as Nx,w as lj,x as Fl,y as qE,z as cj,A as VE,E as Il,G as YE,H as GE,J as KE,K as QE,U as xg,W as uj,X as XE,Y as JE,Z as ZE,_ as eM,$ as tM,a0 as nM,a1 as dj,a2 as sM,a3 as Z0,a4 as ek,a5 as tk,a6 as nk,a7 as Bb,a8 as aM,a9 as rM,aa as iM,ab as oM,ac as lM,ad as cM,ae as uM,af as dM,ag as fM,ah as pM,ai as hM,aj as mM}from"./vendor-three-Chj50gSY.js";function gM(t,e){for(var n=0;n<e.length;n++){const s=e[n];if(typeof s!="string"&&!Array.isArray(s)){for(const a in s)if(a!=="default"&&!(a in t)){const r=Object.getOwnPropertyDescriptor(s,a);r&&Object.defineProperty(t,a,r.get?r:{enumerable:!0,get:()=>s[a]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var yg={exports:{}},Jc={};/**
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 Sk;function sD(){if(Sk)return Ng;Sk=1;var t=jx();function e(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var n=typeof Object.is=="function"?Object.is:e,s=t.useState,a=t.useEffect,r=t.useLayoutEffect,i=t.useDebugValue;function c(m,b){var y=b(),w=s({inst:{value:y,getSnapshot:b}}),C=w[0].inst,N=w[1];return r(function(){C.value=y,C.getSnapshot=b,d(C)&&N({inst:C})},[m,y,b]),a(function(){return d(C)&&N({inst:C}),m(function(){d(C)&&N({inst:C})})},[m]),i(y),y}function d(m){var b=m.getSnapshot;m=m.value;try{var y=b();return!n(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 Ng.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h,Ng}var Ck;function aD(){return Ck||(Ck=1,jg.exports=sD()),jg.exports}var rD=aD();const iD=(t,e)=>{if(No(e))return e;if(qM(e)&&No(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const n=t[t.length-1];return typeof n=="function"?"":n}return t},oD={t:iD,ready:!1},lD=()=>()=>{},dt=(t,e={})=>{var _,M,R;const{i18n:n}=e,{i18n:s,defaultNS:a}=x.useContext(tD)||{},r=n||s||ZM();r&&!r.reportNamespaces&&(r.reportNamespaces=new nD),r||zb(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=x.useMemo(()=>{var z;return{...XM(),...(z=r==null?void 0:r.options)==null?void 0:z.react,...e}},[r,e]),{useSuspense:c,keyPrefix:d}=i,f=t||a||((_=r==null?void 0:r.options)==null?void 0:_.defaultNS),h=No(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(z=>{if(!r)return lD;const{bindI18n:$,bindI18nStore:W}=i,L=()=>{b.current+=1,z()};return $&&r.on($,L),W&&r.store.on(W,L),()=>{$&&$.split(" ").forEach(F=>r.off(F,L)),W&&W.split(" ").forEach(F=>r.store.off(F,L))}},[r,i]),w=x.useRef(),C=x.useCallback(()=>{if(!r)return oD;const z=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(V=>WM(V,r,i)),$=e.lng||r.language,W=b.current,L=w.current;if(L&&L.ready===z&&L.lng===$&&L.keyPrefix===d&&L.revision===W)return L;const H={t:r.getFixedT($,i.nsMode==="fallback"?m:m[0],d),ready:z,lng:$,keyPrefix:d,revision:W};return w.current=H,H},[r,m,d,i,e.lng]),[N,k]=x.useState(0),{t:j,ready:S}=rD.useSyncExternalStore(y,C,C);x.useEffect(()=>{if(r&&!S&&!c){const z=()=>k($=>$+1);e.lng?kk(r,e.lng,m,z):$b(r,m,z)}},[r,e.lng,m,S,c,N]);const T=r||{},D=x.useRef(null),E=x.useRef(),I=z=>{const $=Object.getOwnPropertyDescriptors(z);$.__original&&delete $.__original;const W=Object.create(Object.getPrototypeOf(z),$);if(!Object.prototype.hasOwnProperty.call(W,"__original"))try{Object.defineProperty(W,"__original",{value:z,writable:!1,enumerable:!1,configurable:!1})}catch{}return W},O=x.useMemo(()=>{const z=T,$=z==null?void 0:z.language;let W=z;z&&(D.current&&D.current.__original===z?E.current!==$?(W=I(z),D.current=W,E.current=$):W=D.current:(W=I(z),D.current=W,E.current=$));const L=!S&&!c?(...H)=>(zb(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."),j(...H)):j,F=[L,W,S];return F.t=L,F.i18n=W,F.ready=S,F},[j,T,S,T.resolvedLanguage,T.language,T.languages]);if(r&&c&&!S)throw new Promise(z=>{const $=()=>z();e.lng?kk(r,e.lng,m,$):$b(r,m,$)});return O};function Hb(t){"@babel/helpers - typeof";return Hb=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},Hb(t)}function xj(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":Hb(XMLHttpRequest))==="object"}function cD(t){return!!t&&typeof t.then=="function"}function uD(t){return cD(t)?t:Promise.resolve(t)}var dD=/\{\{(.+?)\}\}/g;function Ak(t,e){return t.replace(dD,function(n,s){var a=e[s.trim()];return a??n})}const fD="modulepreload",pD=function(t){return"/"+t},jk={},vt=function(e,n,s){let a=Promise.resolve();if(n&&n.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(n.map(f=>{if(f=pD(f),f in jk)return;jk[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":fD,h||(b.as="script"),b.crossOrigin="",b.href=f,d&&b.setAttribute("nonce",d),document.head.appendChild(b),h)return new Promise((y,w)=>{b.addEventListener("load",y),b.addEventListener("error",()=>w(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(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,s)}return n}function Tk(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Nk(Object(n),!0).forEach(function(s){hD(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Nk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function hD(t,e,n){return(e=mD(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mD(t){var e=gD(t,"string");return To(e)=="symbol"?e:e+""}function gD(t,e){if(To(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var s=n.call(t,e);if(To(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function To(t){"@babel/helpers - typeof";return To=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},To(t)}var Di=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Di=global.fetch:typeof window<"u"&&window.fetch&&(Di=window.fetch);var zu;xj()&&(typeof global<"u"&&global.XMLHttpRequest?zu=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(zu=window.XMLHttpRequest));var mp;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?mp=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(mp=window.ActiveXObject));typeof Di!="function"&&(Di=void 0);if(!Di&&!zu&&!mp)try{vt(()=>import("./browser-ponyfill-DZOWXZ4K.js").then(t=>t.b),__vite__mapDeps([0,1])).then(function(t){Di=t.default}).catch(function(){})}catch{}var Wb=function(e,n){if(n&&To(n)==="object"){var s="";for(var a in n)s+="&"+encodeURIComponent(a)+"="+encodeURIComponent(n[a]);if(!s)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+s.slice(1)}return e},_k=function(e,n,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,n);if(i instanceof Promise){i.then(r).catch(s);return}}typeof fetch=="function"?fetch(e,n).then(r).catch(s):Di(e,n).then(r).catch(s)},Ek=!1,bD=function(e,n,s,a){e.queryStringParams&&(n=Wb(n,e.queryStringParams));var r=Tk({},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=Tk({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},Ek?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{_k(n,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]}),_k(n,c,a,d),Ek=!0}catch(h){a(h)}}},xD=function(e,n,s,a){s&&To(s)==="object"&&(s=Wb("",s).slice(1)),e.queryStringParams&&(n=Wb(n,e.queryStringParams));try{var r=zu?new zu:new mp("MSXML2.XMLHTTP.3.0");r.open(s?"POST":"GET",n,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)}},yD=function(e,n,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Di&&n.indexOf("file:")!==0)return bD(e,n,s,a);if(xj()||typeof ActiveXObject=="function")return xD(e,n,s,a);a(new Error("No fetch and no xhr implementation found!"))};function Vl(t){"@babel/helpers - typeof";return Vl=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},Vl(t)}function Mk(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,s)}return n}function Tg(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Mk(Object(n),!0).forEach(function(s){yj(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Mk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function vD(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function wD(t,e){for(var n=0;n<e.length;n++){var s=e[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,vj(s.key),s)}}function kD(t,e,n){return e&&wD(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function yj(t,e,n){return(e=vj(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vj(t){var e=SD(t,"string");return Vl(e)=="symbol"?e:e+""}function SD(t,e){if(Vl(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var s=n.call(t,e);if(Vl(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var CD=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(n){return JSON.parse(n)},stringify:JSON.stringify,parsePayload:function(n,s,a){return yj({},s,a||"")},parseLoadPayload:function(n,s){},request:yD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},wj=(function(){function t(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};vD(this,t),this.services=e,this.options=n,this.allOptions=s,this.type="backend",this.init(e,n,s)}return kD(t,[{key:"init",value:function(n){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=n,this.options=Tg(Tg(Tg({},CD()),this.options||{}),a),this.allOptions=r,this.services&&this.options.reloadInterval){var i=setInterval(function(){return s.reload()},this.options.reloadInterval);Vl(i)==="object"&&typeof i.unref=="function"&&i.unref()}}},{key:"readMulti",value:function(n,s,a){this._readAny(n,n,s,s,a)}},{key:"read",value:function(n,s,a){this._readAny([n],n,[s],s,a)}},{key:"_readAny",value:function(n,s,a,r,i){var c=this,d=this.options.loadPath;typeof this.options.loadPath=="function"&&(d=this.options.loadPath(n,a)),d=uD(d),d.then(function(f){if(!f)return i(null,{});var h=Ak(f,{lng:n.join("+"),ns:a.join("+")});c.loadUrl(h,i,s,r)})}},{key:"loadUrl",value:function(n,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,n,f,function(h,m){if(m&&(m.status>=500&&m.status<600||!m.status))return s("failed loading "+n+"; status code: "+m.status,!0);if(m&&m.status>=400&&m.status<500)return s("failed loading "+n+"; 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 "+n+": "+h.message,!0)}if(h)return s(h,!1);var w,C;try{typeof m.data=="string"?w=i.options.parse(m.data,a,r):w=m.data}catch{C="failed parsing "+n+" to json"}if(C)return s(C,!1);s(null,w)})}},{key:"create",value:function(n,s,a,r,i){var c=this;if(this.options.addPath){typeof n=="string"&&(n=[n]);var d=this.options.parsePayload(s,a,r),f=0,h=[],m=[];n.forEach(function(b){var y=c.options.addPath;typeof c.options.addPath=="function"&&(y=c.options.addPath(b,s));var w=Ak(y,{lng:b,ns:s});c.options.request(c.options,w,d,function(C,N){f+=1,h.push(C),m.push(N),f===n.length&&typeof i=="function"&&i(h,m)})})}}},{key:"reload",value:function(){var n=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){n.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)})})})}}}])})();wj.type="backend";const{slice:AD,forEach:jD}=[];function ND(t){return jD.call(AD.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function TD(t){return typeof t!="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(n=>n.test(t))}const Dk=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,_D=function(t,e){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let r=`${t}=${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(!Dk.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!Dk.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},Rk={create(t,e,n,s){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+n*60*1e3)),s&&(a.domain=s),document.cookie=_D(t,e,a)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let s=0;s<n.length;s++){let a=n[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(t,e){this.create(t,"",-1,e)}};var ED={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return Rk.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;n&&typeof document<"u"&&Rk.create(n,t,s,a,r)}},MD={name:"querystring",lookup(t){var s;let{lookupQuerystring:e}=t,n;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&&(n=i[c].substring(d+1))}}return n}},DD={name:"hash",lookup(t){var a;let{lookupHash:e,lookupFromHashIndex:n}=t,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&&n>-1){const c=r.match(/\/([a-zA-Z-]*)/g);return Array.isArray(c)?(a=c[typeof n=="number"?n:0])==null?void 0:a.replace("/",""):void 0}}}return s}};let Nl=null;const Ok=()=>{if(Nl!==null)return Nl;try{if(Nl=typeof window<"u"&&window.localStorage!==null,!Nl)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Nl=!1}return Nl};var RD={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&Ok())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&Ok()&&window.localStorage.setItem(n,t)}};let Tl=null;const Lk=()=>{if(Tl!==null)return Tl;try{if(Tl=typeof window<"u"&&window.sessionStorage!==null,!Tl)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Tl=!1}return Tl};var OD={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&Lk())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&Lk()&&window.sessionStorage.setItem(n,t)}},LD={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:s,language:a}=navigator;if(n)for(let r=0;r<n.length;r++)e.push(n[r]);s&&e.push(s),a&&e.push(a)}return e.length>0?e:void 0}},ID={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const s=e||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(n=s.getAttribute("lang")),n}},PD={name:"path",lookup(t){var a;let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?(a=n[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},BD={name:"subdomain",lookup(t){var a,r;let{lookupFromSubdomainIndex:e}=t;const n=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[n]}};let kj=!1;try{document.cookie,kj=!0}catch{}const Sj=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];kj||Sj.splice(1,1);const FD=()=>({order:Sj,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class Cj{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=ND(n,this.options||{},FD()),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(ED),this.addDetector(MD),this.addDetector(RD),this.addDetector(OD),this.addDetector(LD),this.addDetector(ID),this.addDetector(PD),this.addDetector(BD),this.addDetector(DD)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(s=>{if(this.detectors[s]){let a=this.detectors[s].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(n=n.concat(a))}}),n=n.filter(s=>s!=null&&!TD(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(e,this.options)}))}}Cj.type="languageDetector";const gp={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},qb={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},zD={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},Sq=["#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"],Af={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function Tx(t){const n=Math.floor((Date.now()-t)/1e3)/60;return n<1?Af.recent:n<5?Af.short:n<30?Af.medium:Af.long}function _x(t){return gp[t]??gp.default}let Zf=null;function Aj(){if(!Zf)try{Zf=globalThis.__i18n}catch{}return Zf}function $D(t){Zf=t}function UD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function HD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function WD(t){var a;const e=Aj(),n=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),s=Math.floor((Date.now()-t)/1e3);return s<60?n?n("common:time.seconds",{count:s}):`${s}s`:s<3600?n?n("common:time.minutes",{count:Math.floor(s/60)}):`${Math.floor(s/60)}m`:s<86400?n?n("common:time.hours",{count:Math.floor(s/3600)}):`${Math.floor(s/3600)}h`:n?n("common:time.days",{count:Math.floor(s/86400)}):`${Math.floor(s/86400)}d`}function Ex(t){var f;const e=Aj(),n=(f=e==null?void 0:e.t)==null?void 0:f.bind(e),s=Math.floor((Date.now()-t)/1e3);if(s<5)return n?n("common:time.justNow"):"just now";if(s<60)return n?n("common:time.secondsAgo",{count:s}):`${s}s ago`;const a=Math.floor(s/60);if(a<60){const h=s%60;return h>0?n?n("common:time.minutesSecondsAgo",{minutes:a,seconds:h}):`${a}m ${h}s ago`:n?n("common:time.minutesAgo",{count:a}):`${a}m ago`}const r=Math.floor(a/60),i=a%60;if(r<24)return i>0?n?n("common:time.hoursMinutesAgo",{hours:r,minutes:i}):`${r}h ${i}m ago`:n?n("common:time.hoursAgo",{count:r}):`${r}h ago`;const c=Math.floor(r/24),d=r%24;return d>0?n?n("common:time.daysHoursAgo",{days:c,hours:d}):`${c}d ${d}h ago`:n?n("common:time.daysAgo",{count:c}):`${c}d ago`}function Tu(t,e){return t?e?t.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():t:""}On.use(wj).use(Cj).use(eD).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:"/locales/{{lng}}/{{ns}}.json"},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{$D(On)});const pt={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",GLOBAL_SUPERVISOR_COLLAPSED:"tide-global-supervisor-collapsed",TOOLS_COLLAPSED:"tide-tool-history-collapsed",FILES_COLLAPSED:"tide-file-history-collapsed",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",MOBILE_OVERVIEW_HEIGHT:"tide-mobile-overview-height",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"},Vb="tide-backend-url-change";function Na(t,e){try{const n=localStorage.getItem(t);return n===null?e:JSON.parse(n)}catch{return e}}function Fa(t,e=""){try{return localStorage.getItem(t)??e}catch{return e}}function Ni(t,e=!1){try{const n=localStorage.getItem(t);return n===null?e:n==="true"}catch{return e}}function Mx(t,e){try{const n=localStorage.getItem(t);if(n===null)return e;const s=Number(n);return isNaN(s)?e:s}catch{return e}}function La(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Wr(t,e){try{localStorage.setItem(t,e)}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Ti(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Dx(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Ik(t){try{localStorage.removeItem(t)}catch(e){console.error(`Failed to remove from localStorage: ${t}`,e)}}function Ea(){const t=Rx();return t?t.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ii(){return Fa(pt.AUTH_TOKEN,"")}function Rx(){return Fa(pt.BACKEND_URL,"")}function qD(t){const e=t.trim();Wr(pt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vb,{detail:e}))}function VD(t){if(typeof window>"u")return()=>{};const e=s=>{t(s.detail)},n=s=>{s.key===pt.BACKEND_URL&&t(s.newValue??"")};return window.addEventListener(Vb,e),window.addEventListener("storage",n),()=>{window.removeEventListener(Vb,e),window.removeEventListener("storage",n)}}function Rt(t){return`${Ea()}${t}`}async function Bt(t,e){const n=Ii(),s=new Headers(e==null?void 0:e.headers);return n&&s.set("X-Auth-Token",n),fetch(t,{...e,headers:s,cache:"no-store"})}function Yb(t){const e=Ii();if(!e)return t;try{const n=!t.startsWith("http://")&&!t.startsWith("https://"),s=n?"http://dummy":void 0,a=new URL(t,s);return a.searchParams.set("token",e),n?a.pathname+a.search:a.toString()}catch{const n=t.includes("?")?"&":"?";return`${t}${n}token=${encodeURIComponent(e)}`}}function cs(t=!1,e){const[n,s]=x.useState(t),[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:n,data:a,open:i,close:c,toggle:d,setData:r}}function YD(){const[t,e]=x.useState(null),n=x.useCallback(a=>{e(a)},[]),s=x.useCallback(()=>{e(null)},[]);return{isOpen:t!==null,id:t,open:n,close:s}}function GD(){const[t,e]=x.useState(!1),[n,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:t,screenPosition:n,worldPosition:a,target:i,open:d,close:f}}const ca=[],KD=new Set;function bp(){KD.forEach(t=>t())}function QD(t,e){const n=ca.findIndex(s=>s.id===t);return n!==-1&&ca.splice(n,1),ca.push({id:t,close:e}),bp(),()=>{const s=ca.findIndex(a=>a.id===t);s!==-1&&(ca.splice(s,1),bp())}}function ep(){return ca.length===0?!1:(ca.pop().close(),bp(),!0)}function XD(t){const e=ca.findIndex(n=>n.id===t);return e===-1?!1:e<ca.length-1}function JD(...t){const e=new Set(t);for(;ca.length>0;){const n=ca[ca.length-1];if(e.has(n.id))break;ca.pop().close()}bp()}function Xt(t,e,n){const s=x.useRef(n);s.current=n,x.useEffect(()=>e?QD(t,()=>s.current()):void 0,[t,e])}const $u=5,_g={0:0,1:4,2:8,3:14,4:25,5:50};let _u=null,Pk=!1;async function ZD(){if(Pk)return _u;Pk=!0;try{const t=await vt(()=>import("./index-Bma1pZ6y.js"),__vite__mapDeps([2,3,1,4]));_u={Haptics:t.Haptics,ImpactStyle:t.ImpactStyle}}catch{}return _u}ZD();function xp(t){const e=Math.round(t),n=e<=0?0:e>=$u?$u:e;if(n!==0){if(_u){const{Haptics:s,ImpactStyle:a}=_u;if(n<=2&&typeof s.selectionChanged=="function"){s.selectionChanged().catch(()=>{navigator.vibrate&&navigator.vibrate(_g[n])});return}const i={3:"Light",4:"Medium",5:"Heavy"}[n];if(i&&a[i]){s.impact({style:a[i]}).catch(()=>{navigator.vibrate&&navigator.vibrate(_g[n])});return}}navigator.vibrate&&navigator.vibrate(_g[n])}}function Bk(t,e){const{threshold:n=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(C=>{if(C.touches.length!==1)return;const N=C.touches[0];h.current={startX:N.clientX,startY:N.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),b=x.useCallback(C=>{if(!h.current.isTracking||C.touches.length!==1)return;const N=C.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 T=window.innerWidth*.4,D=Math.max(-1,Math.min(1,k/T));Math.abs(k)>=12&&(h.current.hasMovedEnough=!0,c==null||c(D))},[s,c,d]),y=x.useCallback(C=>{const N=h.current.isTracking,k=h.current.hasMovedEnough;if(!N)return;const j=C.changedTouches[0],S=j.clientX-h.current.startX,T=Math.abs(j.clientY-h.current.startY),D=Date.now()-h.current.startTime;h.current.isTracking=!1,h.current.hasMovedEnough=!1,Math.abs(S)>=n&&T<=s&&D<500?(xp(f),S>0?i==null||i():r==null||r()):k&&(d==null||d())},[n,s,f,r,i,d]),w=x.useCallback(()=>{const C=h.current.hasMovedEnough;h.current.isTracking=!1,h.current.hasMovedEnough=!1,C&&(d==null||d())},[d]);x.useEffect(()=>{const C=t.current;if(!(!C||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return C.addEventListener("touchstart",m,{passive:!0}),C.addEventListener("touchmove",b,{passive:!0}),C.addEventListener("touchend",y,{passive:!0}),C.addEventListener("touchcancel",w,{passive:!0}),()=>{C.removeEventListener("touchstart",m),C.removeEventListener("touchmove",b),C.removeEventListener("touchend",y),C.removeEventListener("touchcancel",w)}},[t,a,m,b,y,w])}const Fk=8,eR=.93,zk=.4;function tR(t){const{gestureRef:e,agentListRef:n,enabled:s,onSelect:a}=t,[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=n.current;if(N){const k=Math.round(N.clientHeight/2);N.style.paddingTop=`${k}px`,N.style.paddingBottom=`${k}px`}},[n]),y=x.useCallback(()=>{f.current=!1,h.current=null,i(!1),d(null);const N=n.current;N&&(N.style.paddingTop="",N.style.paddingBottom="")},[n]),w=x.useCallback(N=>{const k=n.current;if(!k)return;k.scrollTop+=N;const j=k.getBoundingClientRect(),S=j.top+j.height/2,T=j.left+j.width/2,D=document.elementFromPoint(T,S);let E=null;if(D){const I=D.closest("[data-agent-id]");I&&k.contains(I)&&(E=I.dataset.agentId)}if(E!==h.current&&(h.current=E,d(E),E)){const I=U.getState().settings.vibrationIntensity??1;xp(I)}},[n]),C=x.useCallback(()=>{const N=h.current;if(N){const k=U.getState().settings.vibrationIntensity??1,j=k<=0?0:Math.min(k+1,$u);xp(j),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 j=!1,S=!1,T=0,D=0,E=0,I=0,O=0,_=0,M=0,R=0;const z=()=>{M&&(cancelAnimationFrame(M),M=0)},$=()=>{if(Math.abs(_)<zk){_=0;return}N.scrollTop+=_,_*=eR,M=requestAnimationFrame($)},W=V=>{if(z(),V.touches.length>=2){V.preventDefault(),j=!1,S=!1,R=(V.touches[0].clientY+V.touches[1].clientY)/2,b(),w(0);return}j=!0,S=!1,T=V.touches[0].clientX,D=V.touches[0].clientY,E=N.scrollTop,I=D,O=performance.now(),_=0},L=V=>{if(V.touches.length>=2){if(V.preventDefault(),(S||j)&&(S=!1,j=!1),!f.current){R=(V.touches[0].clientY+V.touches[1].clientY)/2,b(),w(0);return}const K=(V.touches[0].clientY+V.touches[1].clientY)/2,ne=R-K;R=K,w(ne);return}if(f.current&&V.touches.length===1){V.preventDefault();const K=V.touches[0].clientY,ne=R-K;R=K,w(ne);return}if(!j&&!S)return;const G=V.touches[0].clientX,B=V.touches[0].clientY;if(j&&!S){const K=Math.abs(G-T),ne=Math.abs(B-D);if(K<Fk&&ne<Fk)return;if(ne>=K)S=!0,j=!1,V.preventDefault();else{j=!1;return}}if(S){V.preventDefault();const K=performance.now(),ne=K-O;N.scrollTop=E+(D-B),ne>0&&(_=(I-B)/ne*16),I=B,O=K}},F=V=>{if(f.current&&V.touches.length===0){C();return}f.current||(S||j)&&V.touches.length===0&&(S&&Math.abs(_)>zk&&(M=requestAnimationFrame($)),S=!1,j=!1)},H=()=>{S=!1,j=!1,z(),f.current&&y()};return N.addEventListener("touchstart",W,{passive:!1}),N.addEventListener("touchmove",L,{passive:!1}),N.addEventListener("touchend",F,{passive:!0}),N.addEventListener("touchcancel",H,{passive:!0}),()=>{N.removeEventListener("touchstart",W),N.removeEventListener("touchmove",L),N.removeEventListener("touchend",F),N.removeEventListener("touchcancel",H),N.style.touchAction=k,z();const V=n.current;V&&(V.style.paddingTop="",V.style.paddingBottom="")}},[e,n,s,b,y,w,C]),{isActive:r,hoveredAgentId:c}}const nR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function sR(){return"documentPictureInPicture"in window}function aR(t,e){for(const r of t.styleSheets)try{if(r.cssRules){const i=e.createElement("style");for(const c of r.cssRules)i.appendChild(e.createTextNode(c.cssText));e.head.appendChild(i)}}catch{if(r.href){const i=e.createElement("link");i.rel="stylesheet",i.href=r.href,e.head.appendChild(i)}}const n=t.documentElement.style.cssText;n&&(e.documentElement.style.cssText=n);const s=getComputedStyle(t.documentElement),a=[];for(let r=0;r<s.length;r++){const i=s[r];i.startsWith("--")&&a.push(`${i}: ${s.getPropertyValue(i)}`)}if(a.length>0){const r=e.createElement("style");r.textContent=`:root { ${a.join("; ")} }`,e.head.appendChild(r)}}function rR(){const[t,e]=x.useState(!1),[n,s]=x.useState(null),[a,r]=x.useState(null),i=x.useRef(null),c=sR(),d=x.useCallback(()=>{if(i.current){const m=i.current.__cleanupFns;m&&m.forEach(b=>b()),i.current.close(),i.current=null}s(null),r(null),e(!1)},[]),f=x.useCallback(async m=>{if(!c)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;i.current&&d();const b={...nR,...m};try{const w=await window.documentPictureInPicture.requestWindow({width:b.width,height:b.height,disallowReturnToOpener:!0});i.current=w,b.copyStyleSheets&&aR(document,w.document);const C=w.document.createElement("div");C.id="pip-root",C.style.width="100%",C.style.height="100%",w.document.body.appendChild(C),w.document.body.style.margin="0",w.document.body.style.padding="0",w.document.body.style.overflow="hidden",w.addEventListener("pagehide",()=>{i.current=null,s(null),r(null),e(!1)});const N=[];if(b.keepOnTop&&b.keepOnTop!=="none"){const k=b.keepOnTop==="raise",j=()=>{i.current&&!i.current.closed&&setTimeout(()=>{i.current&&!i.current.closed&&(i.current.focus(),k&&setTimeout(()=>window.focus(),10))},50)},S=()=>{document.visibilityState==="visible"&&i.current&&!i.current.closed&&setTimeout(()=>{i.current&&!i.current.closed&&(i.current.focus(),k&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",j),document.addEventListener("visibilitychange",S),N.push(()=>window.removeEventListener("focus",j),()=>document.removeEventListener("visibilitychange",S))}return w.__cleanupFns=N,s(w),r(C),e(!0),!0}catch(y){return console.error("Failed to open Picture-in-Picture window:",y),!1}},[c,d]),h=x.useCallback(async m=>{t?d():await f(m)},[t,f,d]);return x.useEffect(()=>()=>{i.current&&i.current.close()},[]),x.useMemo(()=>({isOpen:t,pipWindow:n,pipContainer:a,isSupported:c,open:f,close:d,toggle:h}),[t,n,a,c,f,d,h])}function tu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class iR{constructor(){Xe(this,"messages",new Map);Xe(this,"logs",[]);Xe(this,"maxMessagesPerAgent",200);Xe(this,"maxLogs",500);Xe(this,"enabled",!0);Xe(this,"listeners",new Set);Xe(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,n){try{const s=JSON.parse(n);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${n.length}B`),this.addMessage(e,{id:tu(),agentId:e,direction:"sent",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:n.length,raw:n})}catch(s){console.error("[AgentDebugger] Failed to parse SENT message:",String(s).slice(0,80)),this.addMessage(e,{id:tu(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:n.length,raw:n})}}captureReceived(e,n){try{const s=JSON.parse(n);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${n.length}B`),this.addMessage(e,{id:tu(),agentId:e,direction:"received",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:n.length,raw:n})}catch(s){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(s).slice(0,80)),this.addMessage(e,{id:tu(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:n.length,raw:n})}}addMessage(e,n){let s=this.messages.get(e);s||(s=[],this.messages.set(e,s)),s.push(n),console.log(`[AgentDebugger] Added message for ${e}, total: ${s.length}, type: ${n.type}, direction: ${n.direction}`),s.length>this.maxMessagesPerAgent&&s.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const n=this.getMessages(e),s=n.filter(i=>i.direction==="sent").length,a=n.filter(i=>i.direction==="received").length,r=[...new Set(n.map(i=>i.type))];return{total:n.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(n=>n(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,n,s,a){const r={id:tu(),level:e,message:n,data:s,timestamp:Date.now(),source:a};this.logs.push(r),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,n,s){this.log("debug",e,n,s)}info(e,n,s){this.log("info",e,n,s)}warn(e,n,s){this.log("warn",e,n,s)}error(e,n,s){this.log("error",e,n,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 vs=new iR,Uu={debug:(t,e,n)=>vs.debug(t,e,n),info:(t,e,n)=>vs.info(t,e,n),warn:(t,e,n)=>vs.warn(t,e,n),error:(t,e,n)=>vs.error(t,e,n)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var Yl;(function(t){t.Unimplemented="UNIMPLEMENTED",t.Unavailable="UNAVAILABLE"})(Yl||(Yl={}));class Eg extends Error{constructor(e,n,s){super(e),this.message=e,this.code=n,this.data=s}}const oR=t=>{var e,n;return t!=null&&t.androidBridge?"android":!((n=(e=t==null?void 0:t.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||n===void 0)&&n.bridge?"ios":"web"},lR=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},s=n.Plugins=n.Plugins||{},a=()=>e!==null?e.name:oR(t),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=n.PluginHeaders)===null||b===void 0?void 0:b.find(y=>y.name===m)},d=m=>t.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 w=a(),C=c(m);let N;const k=async()=>(!N&&w in b?N=typeof b[w]=="function"?N=await b[w]():N=b[w]:e!==null&&!N&&"web"in b&&(N=typeof b.web=="function"?N=await b.web():N=b.web),N),j=(O,_)=>{var M,R;if(C){const z=C==null?void 0:C.methods.find($=>_===$.name);if(z)return z.rtype==="promise"?$=>n.nativePromise(m,_.toString(),$):($,W)=>n.nativeCallback(m,_.toString(),$,W);if(O)return(M=O[_])===null||M===void 0?void 0:M.bind(O)}else{if(O)return(R=O[_])===null||R===void 0?void 0:R.bind(O);throw new Eg(`"${m}" plugin is not implemented on ${w}`,Yl.Unimplemented)}},S=O=>{let _;const M=(...R)=>{const z=k().then($=>{const W=j($,O);if(W){const L=W(...R);return _=L==null?void 0:L.remove,L}else throw new Eg(`"${m}.${O}()" is not implemented on ${w}`,Yl.Unimplemented)});return O==="addListener"&&(z.remove=async()=>_()),z};return M.toString=()=>`${O.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:O,writable:!1,configurable:!1}),M},T=S("addListener"),D=S("removeListener"),E=(O,_)=>{const M=T({eventName:O},_),R=async()=>{const $=await M;D({eventName:O,callbackId:$},_)},z=new Promise($=>M.then(()=>$({remove:R})));return z.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},z},I=new Proxy({},{get(O,_){switch(_){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return C?E:T;case"removeListener":return D;default:return S(_)}}});return s[m]=I,f.set(m,{name:m,proxy:I,platforms:new Set([...Object.keys(b),...C?[w]:[]])}),I};return n.convertFileSrc||(n.convertFileSrc=m=>m),n.getPlatform=a,n.handleError=d,n.isNativePlatform=r,n.isPluginAvailable=i,n.registerPlugin=h,n.Exception=Eg,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},cR=t=>t.Capacitor=lR(t),yp=cR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Ju=yp.registerPlugin;class Ox{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,n){let s=!1;this.listeners[e]||(this.listeners[e]=[],s=!0),this.listeners[e].push(n);const r=this.windowListeners[e];r&&!r.registered&&this.addWindowListener(r),s&&this.sendRetainedArgumentsForEvent(e);const i=async()=>this.removeListener(e,n);return Promise.resolve({remove:i})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,n,s){const a=this.listeners[e];if(!a){if(s){let r=this.retainedEventArguments[e];r||(r=[]),r.push(n),this.retainedEventArguments[e]=r}return}a.forEach(r=>r(n))}hasListeners(e){var n;return!!(!((n=this.listeners[e])===null||n===void 0)&&n.length)}registerWindowListener(e,n){this.windowListeners[n]={registered:!1,windowEventName:e,pluginEventName:n,handler:s=>{this.notifyListeners(n,s)}}}unimplemented(e="not implemented"){return new yp.Exception(e,Yl.Unimplemented)}unavailable(e="not available"){return new yp.Exception(e,Yl.Unavailable)}async removeListener(e,n){const s=this.listeners[e];if(!s)return;const a=s.indexOf(n);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 n=this.retainedEventArguments[e];n&&(delete this.retainedEventArguments[e],n.forEach(s=>{this.notifyListeners(e,s)}))}}const $k=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Uk=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class uR extends Ox{async getCookies(){const e=document.cookie,n={};return e.split(";").forEach(s=>{if(s.length<=0)return;let[a,r]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=Uk(a).trim(),r=Uk(r).trim(),n[a]=r}),n}async setCookie(e){try{const n=$k(e.key),s=$k(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=`${n}=${s||""}${a}; path=${r}; ${i};`}catch(n){return Promise.reject(n)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(n){return Promise.reject(n)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const n of e)document.cookie=n.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)}}}Ju("CapacitorCookies",{web:()=>new uR});const dR=async t=>new Promise((e,n)=>{const s=new FileReader;s.onload=()=>{const a=s.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},s.onerror=a=>n(a),s.readAsDataURL(t)}),fR=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=t[e[i]],a),{})},pR=(t,e=!0)=>t?Object.entries(t).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,hR=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),a=fR(t.headers)["content-type"]||"";if(typeof t.data=="string")n.body=t.data;else if(a.includes("application/x-www-form-urlencoded")){const r=new URLSearchParams;for(const[i,c]of Object.entries(t.data||{}))r.set(i,c);n.body=r.toString()}else if(a.includes("multipart/form-data")||t.data instanceof FormData){const r=new FormData;if(t.data instanceof FormData)t.data.forEach((c,d)=>{r.append(d,c)});else for(const c of Object.keys(t.data))r.append(c,t.data[c]);n.body=r;const i=new Headers(n.headers);i.delete("content-type"),n.headers=i}else(a.includes("application/json")||typeof t.data=="object")&&(n.body=JSON.stringify(t.data));return n};class mR extends Ox{async request(e){const n=hR(e,e.webFetchExtra),s=pR(e.params,e.shouldEncodeUrlParams),a=s?`${e.url}?${s}`:e.url,r=await fetch(a,n),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 dR(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 Cq=Ju("CapacitorHttp",{web:()=>new mR});var Hk;(function(t){t.Dark="DARK",t.Light="LIGHT",t.Default="DEFAULT"})(Hk||(Hk={}));var Wk;(function(t){t.StatusBar="StatusBar",t.NavigationBar="NavigationBar"})(Wk||(Wk={}));class gR extends Ox{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")}}Ju("SystemBars",{web:()=>new gR});var qk;(function(t){t[t.Sunday=1]="Sunday",t[t.Monday=2]="Monday",t[t.Tuesday=3]="Tuesday",t[t.Wednesday=4]="Wednesday",t[t.Thursday=5]="Thursday",t[t.Friday=6]="Friday",t[t.Saturday=7]="Saturday"})(qk||(qk={}));const Lx=Ju("LocalNotifications",{web:()=>vt(()=>import("./web-DOowQZI5.js"),__vite__mapDeps([5,3,1,4])).then(t=>new t.LocalNotificationsWeb)}),bR=Ju("ServerConfig");let xR=100;const yR="agent_alerts",Gb="tide-notification-tap";function vR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function jj(t){if(vR()){U.openTerminalOnMobile(t);return}if(document.querySelector(".commander-overlay")){U.requestCommanderExpand(t);return}U.selectAgent(t),U.setTerminalOpen(!0)}function Zu(){try{return yp.isNativePlatform()}catch{return!1}}async function wR(){if(Zu())try{const t=await Lx.requestPermissions();return console.log("[Notifications] Permission result:",t.display),t.display==="granted"}catch(t){return console.error("[Notifications] Failed to request permissions:",t),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function kR(t){const{title:e,body:n,icon:s,data:a}=t;if(Zu())try{const r=xR++;console.log("[Notifications] Scheduling native notification id="+r,e),await Lx.schedule({notifications:[{id:r,title:e,body:n,extra:a,channelId:yR,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:n,icon:s,data:a});r.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(Gb,{detail:a}))}}}let Mg=!1;async function SR(t){const e=[];if(Mg)return()=>{};if(Mg=!0,t){const n=s=>{const a=s;a.detail&&t(a.detail)};window.addEventListener(Gb,n),e.push(()=>window.removeEventListener(Gb,n))}if(Zu())try{const n=await Lx.addListener("localNotificationActionPerformed",s=>{t&&s.notification.extra&&t(s.notification.extra)});e.push(()=>n.remove())}catch(n){console.error("[Notifications] Failed to add tap listener:",n)}return()=>{e.forEach(n=>n()),Mg=!1}}function CR(t,e){Zu()&&bR.syncConfig({url:t,token:e}).catch(n=>{console.warn("[Notifications] Failed to sync config to native service:",n)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const Yp=()=>window.__tideWsState.ws,Vk=t=>{window.__tideWsState.ws=t},AR=()=>window.__tideWsState.isConnecting,nu=t=>{window.__tideWsState.isConnecting=t},Kb=()=>window.__tideWsState.reconnectAttempts,Qb=t=>{window.__tideWsState.reconnectAttempts=t},Nj=()=>window.__tideWsState.reconnectTimeout,Tj=t=>{window.__tideWsState.reconnectTimeout=t},Yk=10,Ix="tide_ws_has_connected";function Gk(){return sessionStorage.getItem(Ix)==="true"}function jR(t){sessionStorage.setItem(Ix,"true")}function NR(){sessionStorage.removeItem(Ix)}let _j=null;const TR=t=>{_j=t},Kk=()=>_j,De={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 Ej(t){t.onToast&&(De.onToast=t.onToast),t.onAgentCreated&&(De.onAgentCreated=t.onAgentCreated),t.onAgentUpdated&&(De.onAgentUpdated=t.onAgentUpdated),t.onAgentDeleted&&(De.onAgentDeleted=t.onAgentDeleted),t.onAgentsSync&&(De.onAgentsSync=t.onAgentsSync),t.onAreasSync&&(De.onAreasSync=t.onAreasSync),t.onSpawnError&&(De.onSpawnError=t.onSpawnError),t.onSpawnSuccess&&(De.onSpawnSuccess=t.onSpawnSuccess),t.onToolUse&&(De.onToolUse=t.onToolUse),t.onDirectoryNotFound&&(De.onDirectoryNotFound=t.onDirectoryNotFound),t.onDelegation&&(De.onDelegation=t.onDelegation),t.onCustomClassesSync&&(De.onCustomClassesSync=t.onCustomClassesSync),t.onReconnect&&(De.onReconnect=t.onReconnect),t.onAgentNotification&&(De.onAgentNotification=t.onAgentNotification),t.onBuildingUpdated&&(De.onBuildingUpdated=t.onBuildingUpdated),t.onSubagentStarted&&(De.onSubagentStarted=t.onSubagentStarted),t.onSubagentCompleted&&(De.onSubagentCompleted=t.onSubagentCompleted)}function _R(){De.onToast=null,De.onAgentCreated=null,De.onAgentUpdated=null,De.onAgentDeleted=null,De.onAgentsSync=null,De.onAreasSync=null,De.onSpawnError=null,De.onSpawnSuccess=null,De.onToolUse=null,De.onDirectoryNotFound=null,De.onDelegation=null,De.onCustomClassesSync=null,De.onReconnect=null,De.onAgentNotification=null,De.onSubagentStarted=null,De.onSubagentCompleted=null}function ER(){De.onAgentCreated=null,De.onAgentUpdated=null,De.onAgentDeleted=null,De.onAgentsSync=null,De.onAreasSync=null,De.onToolUse=null,De.onDelegation=null,De.onCustomClassesSync=null,De.onBuildingUpdated=null,De.onSubagentStarted=null,De.onSubagentCompleted=null}const jf=new Map,MR=new Map,Xb={start(t){},end(t){},async measure(t,e){this.start(t);try{return await e()}finally{this.end(t)}},measureSync(t,e){this.start(t);try{return e()}finally{this.end(t)}},getMetrics(t){const e={},n=t?jf.has(t)?[[t,jf.get(t)]]:[]:Array.from(jf.entries());for(const[s,a]of n){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(){jf.clear(),MR.clear()},report(){}};class DR{constructor(){Xe(this,"frames",[]);Xe(this,"lastFrameTime",0);Xe(this,"frameCount",0);Xe(this,"fps",0);Xe(this,"minFps",1/0);Xe(this,"maxFps",0);Xe(this,"fpsHistory",[]);Xe(this,"maxHistorySize",60)}tick(e=200){const n=performance.now();if(this.lastFrameTime>0){const s=n-this.lastFrameTime;s<e&&(this.frames.push(s),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=n,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((n,s)=>n+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((n,s)=>n+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 Nf=new DR;class RR{constructor(){Xe(this,"snapshots",[]);Xe(this,"maxSnapshots",120);Xe(this,"intervalId",null);Xe(this,"leakThresholdMB",50);Xe(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 n=this.getUsage();n&&(this.baselineUsedMB=n.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 n={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(n),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],n=this.snapshots[this.snapshots.length-1],s=(n.timestamp-e.timestamp)/1e3/60;return s<.1?null:(n.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 n=this.getGrowthRate();if(n!==null&&(console.log(`Growth Rate: ${n.toFixed(2)}MB/min`),n>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 n;return(n=e==null?void 0:e.info)!=null&&n.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 su=new RR;function yu(t,e,n,s,a,r){}function Mj(t,e){x.useRef(0),x.useEffect(()=>{},[t,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}const Jb=pt.PENDING_MESSAGES,OR=300*1e3;function Dj(){try{const t=localStorage.getItem(Jb);if(!t)return[];const e=JSON.parse(t),n=Date.now();return e.filter(s=>n-s.queuedAt<OR)}catch{return[]}}function Rj(t){try{t.length===0?localStorage.removeItem(Jb):localStorage.setItem(Jb,JSON.stringify(t))}catch{}}function Tf(t){const e=Dj();e.push({message:t,queuedAt:Date.now()}),Rj(e)}function LR(){var s;const t=Dj();if(t.length===0)return 0;let e=0;const n=[];for(const a of t)IR(a.message)?e++:n.push(a);if(Rj(n),e>0){const a=e===1?"queued message":"queued messages";(s=De.onToast)==null||s.call(De,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function Px(t){if(t.payload&&typeof t.payload=="object"){const e=t.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 IR(t){const e=Yp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const n=JSON.stringify(t),s=Px(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",s,"payload:",t.payload),s&&vs.captureSent(s,n),e.send(n),!0}catch{return!1}}function Bx(t){var n,s,a,r,i,c,d,f,h,m;const e=Yp();if(!e)return(n=Kk())==null||n(),t.type==="send_command"?(Tf(t),(s=De.onToast)==null||s.call(De,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=De.onToast)==null||a.call(De,"error","Not Connected","Connecting to server... Please try again in a moment."),!1;if(e.readyState!==WebSocket.OPEN)return e.readyState===WebSocket.CONNECTING?t.type==="send_command"?(Tf(t),(r=De.onToast)==null||r.call(De,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=De.onToast)==null||i.call(De,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Kk())==null||c(),t.type==="send_command"?(Tf(t),(d=De.onToast)==null||d.call(De,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=De.onToast)==null||f.call(De,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const b=JSON.stringify(t),y=Px(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",y,"payload:",t.payload),y&&vs.captureSent(y,b),e.send(b),!0}catch(b){return t.type==="send_command"?(Tf(t),(h=De.onToast)==null||h.call(De,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=De.onToast)==null||m.call(De,"error","Send Failed",`Failed to send message: ${b}`),!1}}const vu=new Set,PR=5e3;function Qk(t){if(!t.isDetached||!t.sessionId){vu.delete(t.id);return}vu.has(t.id)||(vu.add(t.id),Bx({type:"reattach_agent",payload:{agentId:t.id}}),setTimeout(()=>{vu.delete(t.id)},PR))}function BR(t){var e,n,s,a,r,i,c,d,f,h,m,b,y,w,C,N,k,j,S,T,D,E,I,O;switch(Xb.start(`ws:${t.type}`),t.type){case"agents_update":{const _=t.payload,M=_.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}))),U.setAgents(_),(e=De.onAgentsSync)==null||e.call(De,_),U.loadToolHistory();for(const R of _)Qk(R);break}case"agent_created":{const _=t.payload;console.log("[WebSocket] Agent created:",_),U.addAgent(_);const M=(n=window.__spawnModalAreaContext)==null?void 0:n.areaId;M&&(U.assignAgentToArea(_.id,M),window.__spawnModalAreaContext=null),U.selectAgent(_.id),(s=De.onAgentCreated)==null||s.call(De,_),(a=De.onSpawnSuccess)==null||a.call(De),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=De.onToast)==null||r.call(De,"success","Agent Deployed",`${_.name} is ready for commands`);break}case"agent_updated":{const _=t.payload,R=U.getState().agents.get(_.id),z=(R==null?void 0:R.status)!==_.status;console.log(`[Tide] Agent updated: ${_.name} (${_.id}) status=${_.status} (was ${R==null?void 0:R.status})${z?" ⚡ STATUS CHANGED":""}`),z&&console.log(`[Tide] 🔔 Status change for ${_.name}: ${R==null?void 0:R.status} → ${_.status}`),z&&(R==null?void 0:R.status)==="working"&&_.status==="idle"&&U.triggerHistoryRefresh(_.id);const $=R?R.position.x!==_.position.x||R.position.z!==_.position.z:!1;U.updateAgent(_),Qk(_),(i=De.onAgentUpdated)==null||i.call(De,_,$);break}case"agent_deleted":{const{id:_}=t.payload;vu.delete(_),U.removeAgent(_),(c=De.onAgentDeleted)==null||c.call(De,_);break}case"activity":{const _=t.payload;U.addActivity(_);break}case"event":{const _=t.payload;if(Uu.debug(`Event: ${_.type}`,{agentId:_.agentId,toolName:_.toolName},"ws:event"),_.type==="tool_start"&&_.toolName&&((d=De.onToolUse)==null||d.call(De,_.agentId,_.toolName,_.toolInput),U.addToolExecution(_.agentId,_.toolName,_.toolInput),_.toolInput)){const M=_.toolInput.file_path||_.toolInput.path;M&&(_.toolName==="Write"?U.addFileChange(_.agentId,"created",M):_.toolName==="Edit"?U.addFileChange(_.agentId,"modified",M):_.toolName==="Read"&&U.addFileChange(_.agentId,"read",M))}break}case"output":{const _=t.payload;Uu.debug(`Output: "${_.text.slice(0,80)}..."`,{agentId:_.agentId,isStreaming:_.isStreaming,length:_.text.length,hasSkillUpdate:!!_.skillUpdate,uuid:_.uuid,toolName:_.toolName},"ws:output"),U.addOutput(_.agentId,{text:_.text,isStreaming:_.isStreaming,timestamp:_.timestamp,isDelegation:_.isDelegation,skillUpdate:_.skillUpdate,subagentName:_.subagentName,uuid:_.uuid,toolName:_.toolName,toolInput:_.toolInput,toolOutput:_.toolOutput});break}case"context_stats":{const{agentId:_,stats:M}=t.payload;console.log(`[Tide] Received context stats for agent ${_}: ${M.usedPercent}% used`),U.updateAgentContextStats(_,M);break}case"context_update":{const{agentId:_,contextUsed:M,contextLimit:R}=t.payload;U.updateAgentContext(_,M,R);break}case"error":{const _=t.payload;console.error("[WebSocket] Error from server:",_.message),(f=De.onToast)==null||f.call(De,"error","Error",_.message),(h=De.onSpawnError)==null||h.call(De),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:_}=t.payload;console.log("[WebSocket] Directory not found:",_),(m=De.onDirectoryNotFound)==null||m.call(De,_),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(_));break}case"command_started":{const{agentId:_,command:M}=t.payload,R=M.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;U.addUserPromptToOutput(_,M);break}case"session_updated":{const{agentId:_}=t.payload;U.loadToolHistory(),U.triggerHistoryRefresh(_);const M=U.getState().agents.get(_);M&&U.updateAgent({...M});break}case"supervisor_report":{const _=t.payload;U.setSupervisorReport(_);break}case"narrative_update":{const{agentId:_,narrative:M}=t.payload;U.addNarrative(_,M);break}case"supervisor_status":{const _=t.payload;U.setSupervisorStatus(_);break}case"agent_supervisor_history":{const _=t.payload;U.setAgentSupervisorHistory(_);break}case"agent_analysis":{const{agentId:_,analysis:M}=t.payload;U.addAgentAnalysis(_,M);break}case"areas_update":{const _=t.payload;U.setAreasFromServer(_),(b=De.onAreasSync)==null||b.call(De);break}case"buildings_update":{const _=t.payload;U.setBuildingsFromServer(_);break}case"building_created":{const _=t.payload;U.addBuilding(_);break}case"building_updated":{const _=t.payload;U.updateBuildingFromServer(_),(y=De.onBuildingUpdated)==null||y.call(De,_);break}case"building_deleted":{const{id:_}=t.payload;U.removeBuildingFromServer(_);break}case"building_logs":{const{buildingId:_,logs:M}=t.payload;U.addBuildingLogs(_,M);break}case"pm2_logs_chunk":{const{buildingId:_,chunk:M}=t.payload;U.appendStreamingLogChunk(_,M);break}case"pm2_logs_streaming":{const{buildingId:_,streaming:M}=t.payload;U.setStreamingStatus(_,M);break}case"docker_logs_chunk":{const{buildingId:_,chunk:M}=t.payload;U.appendStreamingLogChunk(_,M);break}case"docker_logs_streaming":{const{buildingId:_,streaming:M}=t.payload;U.setStreamingStatus(_,M);break}case"docker_containers_list":{const{containers:_,composeProjects:M}=t.payload;console.log(`[WebSocket] Received ${_.length} containers, ${M.length} compose projects`),U.setDockerContainersList(_,M);break}case"boss_building_logs_chunk":{const{bossBuildingId:_,subordinateBuildingId:M,subordinateBuildingName:R,chunk:z,isError:$}=t.payload;U.appendBossStreamingLogChunk(_,M,R,z,$);break}case"boss_building_subordinates_updated":{const{bossBuildingId:_,subordinateBuildingIds:M}=t.payload;U.updateBuilding(_,{subordinateBuildingIds:M});break}case"permission_request":{const _=t.payload;U.addPermissionRequest(_);break}case"permission_resolved":{const{requestId:_,approved:M}=t.payload;U.resolvePermissionRequest(_,M);break}case"delegation_decision":{const _=t.payload;U.handleDelegationDecision(_),_.status==="sent"&&((w=De.onToast)==null||w.call(De,"info","Task Delegated",`Delegated to ${_.selectedAgentName}: ${_.reasoning.slice(0,80)}...`),_.bossId&&_.selectedAgentId&&((C=De.onDelegation)==null||C.call(De,_.bossId,_.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:_,subordinateIds:M}=t.payload;U.updateBossSubordinates(_,M);break}case"delegation_history":{const{bossId:_,decisions:M}=t.payload;U.setDelegationHistory(_,M);break}case"boss_spawned_agent":{const{agent:_,bossPosition:M}=t.payload;console.log("[WebSocket] Boss spawned agent:",_.name,"- walking to boss at",M),U.addAgent(_),(N=De.onAgentCreated)==null||N.call(De,_),Bx({type:"move_agent",payload:{agentId:_.id,position:M}}),(k=De.onToast)==null||k.call(De,"success","Agent Deployed",`${_.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:_,subordinateId:M,subordinateName:R,taskDescription:z}=t.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${_}: ${z.slice(0,50)}...`),U.handleAgentTaskStarted(_,M,R,z);break}case"agent_task_output":{const{bossId:_,subordinateId:M,output:R,isStreaming:z,timestamp:$,subagentName:W,toolName:L,toolInput:F,toolOutput:H}=t.payload;U.handleAgentTaskOutput(_,M,{text:R,isStreaming:z||!1,timestamp:$||Date.now(),subagentName:W,toolName:L,toolInput:F,toolOutput:H});break}case"agent_task_completed":{const{bossId:_,subordinateId:M,success:R}=t.payload;console.log(`[WebSocket] Agent task completed for boss ${_}, subordinate ${M}, success: ${R}`),U.handleAgentTaskCompleted(_,M,R);break}case"skills_update":{const _=t.payload;U.setSkillsFromServer(_);break}case"skill_created":{const _=t.payload;U.addSkillFromServer(_),console.log(`[WebSocket] Skill created: ${_.name}`);break}case"skill_updated":{const _=t.payload;U.updateSkillFromServer(_),console.log(`[WebSocket] Skill updated: ${_.name}`);break}case"skill_deleted":{const{id:_}=t.payload;U.removeSkillFromServer(_),console.log(`[WebSocket] Skill deleted: ${_}`);break}case"agent_skills":{const{agentId:_,skills:M}=t.payload;console.log(`[WebSocket] Agent ${_} has ${M.length} skills`);break}case"custom_agent_classes_update":{const _=t.payload;U.setCustomAgentClassesFromServer(_),console.log(`[WebSocket] Received ${_.length} custom agent classes`);const M=new Map;for(const R of _)M.set(R.id,R);(j=De.onCustomClassesSync)==null||j.call(De,M);break}case"custom_agent_class_created":{const _=t.payload;U.addCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class created: ${_.name}`),(S=De.onCustomClassesSync)==null||S.call(De,U.getState().customAgentClasses);break}case"custom_agent_class_updated":{const _=t.payload;U.updateCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class updated: ${_.name}`),(T=De.onCustomClassesSync)==null||T.call(De,U.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:_}=t.payload;U.removeCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class deleted: ${_}`),(D=De.onCustomClassesSync)==null||D.call(De,U.getState().customAgentClasses);break}case"global_usage":{const _=t.payload;console.log("[WebSocket] Global usage update:",_),U.setGlobalUsage(_);break}case"agent_notification":{const _=t.payload;console.log(`[WebSocket] Agent notification from ${_.agentName}: ${_.title}`),(E=De.onAgentNotification)==null||E.call(De,_);break}case"focus_agent":{const{agentId:_,openTerminal:M}=t.payload;if(!U.getState().agents.get(_)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${_}`);break}U.selectAgent(_),M&&U.setTerminalOpen(!0);const z=[0,80,220,500,1e3];for(const $ of z)window.setTimeout(()=>{window.focus()},$);break}case"exec_task_started":{const{taskId:_,agentId:M,agentName:R,command:z,cwd:$}=t.payload;console.log(`[WebSocket] Exec task started: ${_} for agent ${R}: ${z.slice(0,50)}...`),U.handleExecTaskStarted(_,M,R,z,$);break}case"exec_task_output":{const{taskId:_,agentId:M,output:R,isError:z}=t.payload;U.handleExecTaskOutput(_,M,R,z);break}case"exec_task_completed":{const{taskId:_,agentId:M,exitCode:R,success:z}=t.payload;console.log(`[WebSocket] Exec task completed: ${_} for agent ${M}, success: ${z}`),U.handleExecTaskCompleted(_,M,R,z);break}case"subagent_started":{const _=t.payload;console.log(`[WebSocket] Subagent started: ${_.name} (${_.id}) for agent ${_.parentAgentId}`),U.addSubagent(_),(I=De.onSubagentStarted)==null||I.call(De,_);break}case"subagent_output":{const{subagentId:_,parentAgentId:M,text:R,timestamp:z}=t.payload,$=R.indexOf(":");if($>0){const W=R.slice(0,$).trim(),L=R.slice($+1).trim();U.addSubagentActivity(_,M,{toolName:W,description:L,timestamp:z})}else R.startsWith("Using ")&&U.addSubagentActivity(_,M,{toolName:R.slice(6).trim(),description:"",timestamp:z});break}case"subagent_completed":{const{subagentId:_,parentAgentId:M,success:R,resultPreview:z,subagentName:$,durationMs:W,tokensUsed:L,toolUseCount:F}=t.payload;console.log(`[WebSocket] Subagent completed: ${_} for agent ${M}, success: ${R}`),(W||L||F)&&U.updateSubagentStats(_,M,{durationMs:W||0,tokensUsed:L||0,toolUseCount:F||0}),U.completeSubagent(_,M,R),(O=De.onSubagentCompleted)==null||O.call(De,_);const H=U.getSubagent(_)||U.getSubagentByToolUseId(_),V=$||(H==null?void 0:H.name)||_,G=R?"✅":"❌",B=W?` (${(W/1e3).toFixed(0)}s · ${((L||0)/1e3).toFixed(1)}K tokens · ${F||0} tools)`:"";U.addOutput(M,{text:`${G} Subagent ${V} ${R?"completed":"failed"}${B}`,isStreaming:!1,timestamp:Date.now(),subagentName:V,toolOutput:z});break}case"subagent_stream":{const{toolUseId:_,parentAgentId:M,entries:R}=t.payload;U.addSubagentStreamEntries(_,M,R);break}case"secrets_update":{const _=t.payload;U.setSecretsFromServer(_),console.log(`[WebSocket] Received ${_.length} secrets`);break}case"secret_created":{const _=t.payload;U.addSecretFromServer(_),console.log(`[WebSocket] Secret created: ${_.name}`);break}case"secret_updated":{const _=t.payload;U.updateSecretFromServer(_),console.log(`[WebSocket] Secret updated: ${_.name}`);break}case"secret_deleted":{const{id:_}=t.payload;U.removeSecretFromServer(_),console.log(`[WebSocket] Secret deleted: ${_}`);break}case"database_connection_result":{const{buildingId:_,connectionId:M,success:R,error:z,serverVersion:$}=t.payload;U.setConnectionStatus(_,M,{connected:R,error:z,serverVersion:$}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${M}`);break}case"databases_list":{const{buildingId:_,connectionId:M,databases:R}=t.payload;U.setDatabases(_,M,R),console.log(`[WebSocket] Received ${R.length} databases for ${M}`);break}case"tables_list":{const{buildingId:_,connectionId:M,database:R,tables:z}=t.payload;U.setTables(_,M,R,z),console.log(`[WebSocket] Received ${z.length} tables for ${R}`);break}case"table_schema":{const{buildingId:_,connectionId:M,database:R,table:z,columns:$,indexes:W,foreignKeys:L}=t.payload;U.setTableSchema(_,M,R,z,{columns:$,indexes:W||[],foreignKeys:L||[]}),console.log(`[WebSocket] Received schema for ${z}`);break}case"query_result":{const{buildingId:_,result:M}=t.payload;U.setQueryResult(_,M),console.log(`[WebSocket] Query ${M.status}: ${M.rowCount??M.affectedRows??0} rows in ${M.duration}ms`);break}case"silent_query_result":{const{buildingId:_,query:M,requestId:R,success:z,affectedRows:$,error:W}=t.payload;U.setSilentQueryResult(_,{query:M,requestId:R,success:z,affectedRows:$,error:W}),console.log(`[WebSocket] Silent query ${z?"succeeded":"failed"}: ${$??0} affected rows`);break}case"query_history_update":{const{buildingId:_,history:M}=t.payload;U.setQueryHistory(_,M),console.log(`[WebSocket] Received ${M.length} query history entries for ${_}`);break}}Xb.end(`ws:${t.type}`)}TR(()=>Hu());let Xk=!1;function Oj(){const t=Yp();t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Page unloading");const e=Nj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),NR()}function FR(){Xk||(window.addEventListener("beforeunload",Oj),Xk=!0)}function Lj(){Oj(),U.setConnected(!1),U.stopStatusPolling()}function zR(){Lj(),Qb(0),setTimeout(()=>Hu(),100)}function Hu(){FR();const t=Nj();t&&(clearTimeout(t),Tj(null));const e=Yp();if(AR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Gk()&&De.onReconnect&&De.onReconnect();return}Qb(Kb()+1),nu(!0);const n=Rx(),s=Ii(),a=6200;let r;if(n){const c=n.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{nu(!1),Jk();return}Vk(i),i.onopen=()=>{var d,f,h;const c=Gk();nu(!1),Qb(0),jR(),U.setConnected(!0),U.startStatusPolling(),U.clearAllPermissions(),c?((d=De.onToast)==null||d.call(De,"success","Reconnected","Connection restored - refreshing data..."),(f=De.onReconnect)==null||f.call(De)):(h=De.onToast)==null||h.call(De,"success","Connected","Connected to Tide Commander server"),CR(n,s),LR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=Px(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&vs.captureReceived(f,c.data),BR(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;nu(!1),Vk(null),U.setConnected(!1),U.stopStatusPolling();const c=Kb();c<Yk?((d=De.onToast)==null||d.call(De,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${Yk})`),Jk()):(f=De.onToast)==null||f.call(De,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{nu(!1)},U.setSendMessage(Bx)}function Jk(){const t=Kb(),e=Math.min(1e3*Math.pow(2,t-1),3e4);Tj(setTimeout(Hu,e))}function $R(t,e){const n={position:t,target:e};La(pt.CAMERA_STATE,n)}function UR(){return Na(pt.CAMERA_STATE,null)}function Aq(t,e,n){const s={posX:t,posZ:e,zoom:n};La(pt.CAMERA_STATE_2D,s)}function jq(){return Na(pt.CAMERA_STATE_2D,null)}function sc(){return{Authorization:`Bearer ${Ii()}`,"Content-Type":"application/json"}}async function HR(){const t=await fetch(`${Ea()}/api/workspaces`,{headers:sc()});if(!t.ok)throw new Error(`Failed to fetch workspaces: ${t.statusText}`);return t.json()}async function WR(t,e){const n=await fetch(`${Ea()}/api/workspaces`,{method:"POST",headers:sc(),body:JSON.stringify({name:t,areaIds:e})});if(!n.ok)throw new Error(`Failed to create workspace: ${n.statusText}`);return n.json()}async function Zk(t,e){const n=await fetch(`${Ea()}/api/workspaces/${t}`,{method:"PUT",headers:sc(),body:JSON.stringify(e)});if(!n.ok)throw new Error(`Failed to update workspace: ${n.statusText}`);return n.json()}async function qR(t){const e=await fetch(`${Ea()}/api/workspaces/${t}`,{method:"DELETE",headers:sc()});if(!e.ok)throw new Error(`Failed to delete workspace: ${e.statusText}`)}async function VR(){const t=await fetch(`${Ea()}/api/workspaces/active`,{headers:sc()});if(!t.ok)throw new Error(`Failed to get active workspace: ${t.statusText}`);return(await t.json()).activeWorkspaceId??null}async function eS(t){const e=await fetch(`${Ea()}/api/workspaces/active`,{method:"PUT",headers:sc(),body:JSON.stringify({workspaceId:t})});if(!e.ok)throw new Error(`Failed to set active workspace: ${e.statusText}`)}const Wu=new Set;let sr=null,xo=[],Ij=!1;const Zb=new Set;function Dg(t){Ij=t,Zb.forEach(e=>e(t))}const Pj="tide-commander-active-workspace";function tS(){return typeof window>"u"?null:localStorage.getItem(Pj)||null}function Rg(t){typeof window>"u"||localStorage.setItem(Pj,t||"")}function au(){Wu.forEach(t=>t())}function YR(){return sr}function Fx(t){return sr?t?sr.areaIds.includes(t):!1:!0}function Nq(t){return sr?sr.areaIds.includes(t):!0}function Bj(){const[,t]=x.useState(0);return x.useEffect(()=>{const e=()=>t(n=>n+1);return Wu.add(e),()=>{Wu.delete(e)}},[]),[sr,xo]}function GR(t){return Wu.add(t),()=>{Wu.delete(t)}}function KR(){const[t,e]=x.useState(Ij);return x.useEffect(()=>{const n=s=>e(s);return Zb.add(n),()=>{Zb.delete(n)}},[]),t}const Og=new Map,QR=Ce.memo(function(){const{t:e}=dt("common"),n=ur(),[s,a]=x.useState([]),[r,i]=x.useState(()=>tS()),[c,d]=x.useState(!1),[f,h]=x.useState(!1),[m,b]=x.useState(!0),[y,w]=x.useState(null),[C,N]=x.useState(""),[k,j]=x.useState([]),[S,T]=x.useState(!1),D=x.useRef(null);x.useEffect(()=>{let L=!1;return(async()=>{try{const F=tS(),[H,V]=await Promise.all([HR(),VR()]);if(L)return;const G=F&&H.some(B=>B.id===F)?F:V&&H.some(B=>B.id===V)?V:null;a(H),xo=H,i(G),Rg(G),sr=H.find(B=>B.id===G)??null,au()}catch(F){console.error("workspace error:",F)}finally{L||b(!1)}})(),()=>{L=!0}},[]),x.useEffect(()=>{if(!c&&!f)return;const L=F=>{D.current&&!D.current.contains(F.target)&&(d(!1),h(!1))};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[c,f]);const E=x.useMemo(()=>s.find(L=>L.id===r)??null,[s,r]),I=x.useCallback(async L=>{Dg(!0);const F=Date.now();if(r){const B=UR();B&&(Og.set(r,B),Zk(r,{cameraState:B}).then(K=>{a(ne=>{const q=ne.map(xe=>xe.id===r?K:xe);return xo=q,q})}).catch(K=>console.error("workspace error:",K)))}i(L),Rg(L),d(!1);const H=L?s.find(B=>B.id===L)??null:null;if(sr=H,xo=s,au(),L){const K=(H==null?void 0:H.cameraState)??Og.get(L);K&&($R(K.position,K.target),Og.set(L,K))}eS(L).catch(B=>console.error("workspace error:",B));const V=Date.now()-F,G=400;V<G?setTimeout(()=>Dg(!1),G-V):Dg(!1)},[r,s]),O=x.useMemo(()=>Array.from(n.values()).filter(L=>!L.archived),[n]),_=x.useCallback(async()=>{if(C.trim())try{const L=await WR(C.trim(),k),F=[...s,L];a(F),xo=F,au(),N(""),j([]),T(!1)}catch(L){console.error("workspace error:",L)}},[C,k,s]),M=x.useCallback(async()=>{if(!(!y||!C.trim()))try{const L=await Zk(y,{name:C.trim(),areaIds:k}),F=s.map(H=>H.id===y?L:H);a(F),xo=F,y===r&&(sr=L),au(),w(null),N(""),j([])}catch(L){console.error("workspace error:",L)}},[y,C,k,s,r]),R=x.useCallback(async L=>{try{await qR(L);const F=s.filter(H=>H.id!==L);a(F),xo=F,r===L&&(i(null),Rg(null),sr=null,await eS(null).catch(H=>console.error("workspace error:",H))),au()}catch(F){console.error("workspace error:",F)}},[s,r]),z=x.useCallback(L=>{w(L.id),N(L.name),j([...L.areaIds]),T(!1)},[]),$=x.useCallback(()=>{w(null),N(""),j([]),T(!0)},[]),W=x.useCallback(L=>{j(F=>F.includes(L)?F.filter(H=>H!==L):[...F,L])},[]);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:E?E.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:()=>I(null),children:e("agentBar.allWorkspaces",{defaultValue:"All"})}),s.map(L=>o.jsxs("button",{className:`workspace-switcher-option ${L.id===r?"active":""}`,onClick:()=>I(L.id),children:[L.name,o.jsx("span",{className:"workspace-switcher-option-count",children:L.areaIds.length})]},L.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(L=>o.jsx("div",{className:"workspace-switcher-manager-item",children:y===L.id?o.jsxs("div",{className:"workspace-switcher-editor",children:[o.jsx("input",{type:"text",value:C,onChange:F=>N(F.target.value),className:"workspace-switcher-input",placeholder:"Workspace name",autoFocus:!0,onKeyDown:F=>{F.key==="Enter"&&M(),F.key==="Escape"&&w(null)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[O.map(F=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(F.id),onChange:()=>W(F.id)}),o.jsx("span",{style:{color:F.color},children:F.name})]},F.id)),O.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:()=>w(null),children:"Cancel"})]})]}):o.jsxs("div",{className:"workspace-switcher-manager-row",children:[o.jsx("span",{className:"workspace-switcher-manager-name",children:L.name}),o.jsxs("span",{className:"workspace-switcher-manager-count",children:[L.areaIds.length," areas"]}),o.jsx("button",{className:"workspace-switcher-btn-edit",onClick:()=>z(L),title:"Edit",children:"✏"}),o.jsx("button",{className:"workspace-switcher-btn-delete",onClick:()=>R(L.id),title:"Delete",children:"🗑"})]})},L.id))}),S?o.jsxs("div",{className:"workspace-switcher-editor workspace-switcher-create-form",children:[o.jsx("input",{type:"text",value:C,onChange:L=>N(L.target.value),className:"workspace-switcher-input",placeholder:"New workspace name",autoFocus:!0,onKeyDown:L=>{L.key==="Enter"&&_(),L.key==="Escape"&&T(!1)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[O.map(L=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(L.id),onChange:()=>W(L.id)}),o.jsx("span",{style:{color:L.color},children:L.name})]},L.id)),O.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:_,children:"Create"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>T(!1),children:"Cancel"})]})]}):o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-add",onClick:$,children:["+ ",e("agentBar.newWorkspace",{defaultValue:"New Workspace"})]})]})]})}),vp="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 Gp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function Fj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function XR(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function qu(t){typeof window<"u"&&(window.__tidePersistedScene=t)}function Eu(t){typeof window<"u"&&(window.__tidePersistedCanvas=t)}function zj(t){typeof window<"u"&&(window.__tideWsConnected=t)}function JR(t){typeof window<"u"&&(window.__tideIsPageUnloading=t)}function ZR(){sessionStorage.setItem(vp,"true")}function _f(t){JR(!0),sessionStorage.removeItem(vp),Lj(),_R(),window.__tideScene&&(window.__tideScene=null);const e=Gp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),qu(null)):console.log("[App] No persistedScene to dispose"),Eu(null),zj(!1);const n=document.getElementById("battlefield");n&&n.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function eO(){var a,r;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(vp)==="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=Gp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}qu(null)}const n=document.getElementById("battlefield"),s=Fj();n&&n!==s&&n.remove(),sessionStorage.removeItem(vp)}function tO(){typeof window>"u"||(eO(),window.addEventListener("pageshow",t=>{t.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),_f(),window.location.reload())}),window.onunload=()=>_f(),window.onbeforeunload=t=>{_f()},window.addEventListener("pagehide",t=>{_f(`pagehide (persisted=${t.persisted})`)}))}tO();const nS={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},sS={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},aS={idleAnimation:"sit",workingAnimation:"sprint"},nO=0;function $j(){const t={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:nS,modelStyle:sS,animations:aS,fpsLimit:nO},e=Na(pt.CONFIG,null);if(e){const n=e.indicatorScale;return{characterScale:e.characterScale??t.characterScale,scale2d:e.scale2d??n??t.scale2d,scale3d:e.scale3d??n??t.scale3d,show2DTaskLabels:e.show2DTaskLabels??t.show2DTaskLabels,gridVisible:e.gridVisible??t.gridVisible,timeMode:e.timeMode??t.timeMode,terrain:{...nS,...e.terrain},modelStyle:{...sS,...e.modelStyle},animations:{...aS,...e.animations},fpsLimit:e.fpsLimit??t.fpsLimit}}return t}function sO(t){La(pt.CONFIG,t)}function aO(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function Uj(){console.log("[Tide HMR] Manual scene refresh triggered");const t=Gp();if(t){try{t.dispose()}catch(n){console.warn("[Tide HMR] Error disposing scene:",n)}qu(null)}Eu(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const n=e.getContext("webgl2")||e.getContext("webgl");if(n){const s=n.getExtension("WEBGL_lose_context");s&&s.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=Uj);function rO({canvasRef:t,selectionBoxRef:e,viewMode:n,sceneMountKey:s=0,showToast:a,showAgentNotification:r,toolboxModal:i,contextMenu:c,setHoveredAgentPopup:d,setBuildingPopup:f,getBuildingPopup:h,openBuildingModal:m,openPM2LogsModal:b,openBossLogsModal:y,openDatabasePanel:w,onSceneLoadingChange:C}){const N=x.useRef(null),k=x.useRef(null),j=x.useRef(null),S=x.useRef(null),T=x.useRef(null);return x.useEffect(()=>{if(n!=="3d"){C==null||C(!1);return}if(!t.current||!e.current)return;let D=!1;C==null||C(!0);const E=Gp(),O=Fj()===t.current;function _(){var R,z,$,W,L,F,H,V;(R=N.current)==null||R.setOnToast(a),(z=N.current)==null||z.setOnBuildingClick((G,B)=>{U.selectBuilding(G);const K=U.getState().buildings.get(G);(K==null?void 0:K.type)==="folder"&&K.folderPath?U.openFileExplorer(K.folderPath):(K==null?void 0:K.type)==="server"||(K==null?void 0:K.type)==="boss"||(K==null?void 0:K.type)==="database"?(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{f({buildingId:G,screenPos:B,fromClick:!0}),k.current=null},150)):m(G)}),($=N.current)==null||$.setOnContextMenu((G,B,K)=>{c.open(G,B,K)}),(W=N.current)==null||W.setOnAgentHover(()=>{}),(L=N.current)==null||L.setOnBuildingHover((G,B)=>{const K=h();if(G&&B){const ne=U.getState().buildings.get(G);((ne==null?void 0:ne.type)==="server"||(ne==null?void 0:ne.type)==="boss"||(ne==null?void 0:ne.type)==="database")&&!(K!=null&&K.fromClick)&&f({buildingId:G,screenPos:B,fromClick:!1})}else K!=null&&K.fromClick||f(null)}),(F=N.current)==null||F.setOnGroundClick(()=>{f(null)}),(H=N.current)==null||H.setOnAreaDoubleClick(G=>{U.selectArea(G),i.open()}),(V=N.current)==null||V.setOnBuildingDoubleClick(G=>{var K;k.current&&(clearTimeout(k.current),k.current=null),f(null);const B=U.getState().buildings.get(G);(B==null?void 0:B.type)==="server"&&((K=B.pm2)!=null&&K.enabled)?b==null||b(G):(B==null?void 0:B.type)==="boss"?y==null||y(G):(B==null?void 0:B.type)==="database"?w==null||w(G):(B==null?void 0:B.type)==="folder"&&B.folderPath?U.openFileExplorer(B.folderPath):m(G)})}if(E)try{N.current=E,O?(console.log("[Tide] Reusing existing scene (StrictMode remount)"),E.ensureRenderLoopRunning()):(console.log("[Tide] Reattaching persisted scene to new canvas"),E.reattach(t.current,e.current),Eu(t.current));const R=U.getState();E.syncAreas(),E.syncBuildings(),R.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",R.agents.size),E.syncAgents(Array.from(R.agents.values()))),_()}catch(R){console.error("[Tide] Failed to reattach persisted 3D scene:",R),C==null||C(!1)}finally{S.current=requestAnimationFrame(()=>{T.current=requestAnimationFrame(()=>{C==null||C(!1),T.current=null}),S.current=null})}else{const R=t.current,z=e.current,$=async()=>{if(D){console.log("[Tide] Effect cleaned up before scene init, skipping"),C==null||C(!1);return}if(!R.isConnected||!z.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),C==null||C(!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),ZR();try{const{SceneManager:W}=await vt(async()=>{const{SceneManager:H}=await import("./SceneManager-BD0UwiqS.js");return{SceneManager:H}},__vite__mapDeps([6,4,3,1]));if(D){C==null||C(!1);return}const L=new W(R,z);N.current=L,qu(L),Eu(R);const F=$j();L.setCharacterScale(F.characterScale),L.setScale3D(F.scale3d),L.setGridVisible(F.gridVisible),L.setTimeMode(F.timeMode),L.setTerrainConfig(F.terrain),L.setFloorStyle(F.terrain.floorStyle,!0),L.setAgentModelStyle(F.modelStyle),L.setIdleAnimation(F.animations.idleAnimation),L.setWorkingAnimation(F.animations.workingAnimation),L.setFpsLimit(F.fpsLimit),L.syncAreas(),L.syncBuildings(),L.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const H=U.getState();H.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",H.customAgentClasses.size),L.setCustomAgentClasses(H.customAgentClasses)),H.agents.size>0&&(console.log("[Tide] Syncing agents from store:",H.agents.size),L.syncAgents(Array.from(H.agents.values()))),L.upgradeAgentModels()}).catch(H=>{console.warn("[Tide] Some models failed to load, using fallback:",H)}).finally(()=>{C==null||C(!1)}),_()}catch(W){console.error("[Tide] Failed to initialize 3D scene:",W),C==null||C(!1)}};j.current=requestAnimationFrame(()=>void $())}Ej({onAgentCreated:R=>{var z,$,W;(z=N.current)==null||z.addAgent(R),($=N.current)==null||$.refreshSelectionVisuals(),(W=window.__spawnModalSuccess)==null||W.call(window)},onAgentUpdated:(R,z)=>{var W;const $=U.getState().agents.get(R.id)||R;(W=N.current)==null||W.updateAgent($,z)},onAgentDeleted:R=>{var z;(z=N.current)==null||z.removeAgent(R)},onAgentsSync:R=>{var $;const z=Array.from(U.getState().agents.values());($=N.current)==null||$.syncAgents(z)},onAreasSync:()=>{var z,$;(z=N.current)==null||z.syncAreas();const R=Array.from(U.getState().agents.values());($=N.current)==null||$.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 z;(z=window.__spawnModalDirNotFound)==null||z.call(window,R)},onToolUse:(R,z,$)=>{var W;(W=N.current)==null||W.showToolBubble(R,z,$)},onDelegation:(R,z)=>{var $;($=N.current)==null||$.showDelegationEffect(R,z)},onCustomClassesSync:R=>{var z,$;(z=N.current)==null||z.setCustomAgentClasses(R),($=N.current)==null||$.upgradeAgentModels()},onBuildingUpdated:R=>{var z;(z=N.current)==null||z.updateBuilding(R)},onSubagentStarted:R=>{var z;(z=N.current)==null||z.addSubagentEffect(R.id,R.parentAgentId,R.name,R.subagentType)},onSubagentCompleted:R=>{var W;const z=U.getSubagent(R)||U.getSubagentByToolUseId(R),$=(z==null?void 0:z.id)||R;(W=N.current)==null||W.completeSubagentEffect($),setTimeout(()=>{var L;(L=N.current)==null||L.removeSubagentEffect($)},3e4)}});const M=GR(()=>{if(N.current){N.current.syncAreas(),N.current.syncBuildings();const R=Array.from(U.getState().agents.values());N.current.syncAgents(R)}});return()=>{M(),D=!0,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),U.getState().viewMode!=="3d"&&aO()&&N.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),ER(),N.current.dispose(),N.current=null,qu(null),Eu(null))}},[n,s]),N}function iO({showToast:t,showAgentNotification:e}){x.useEffect(()=>{Ej({onToast:t,onReconnect:()=>{U.triggerReconnect()},onAgentNotification:a=>{e(a)}}),XR()||(Hu(),zj(!0)),wR();let n;SR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&jj(a.agentId)}).then(a=>{n=a});const s=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>Hu(),100)};return window.addEventListener("tideAppResume",s),()=>{window.removeEventListener("tideAppResume",s),n==null||n()}},[t,e])}function oO(t){x.useEffect(()=>{let e="",n="",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,w)=>(y<<5)-y+w.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 U.subscribe(()=>{var b;const r=U.getState(),i=Array.from(r.selectedAgentIds).sort().join(","),c=Array.from(r.selectedBuildingIds).sort().join(","),d=i!==e,f=c!==n,{newVersion:h,changed:m}=a(r.agents);(d||f||m)&&(e=i,n=c,s=h,(b=t.current)==null||b.refreshSelectionVisuals())})},[t])}function lO(t){x.useEffect(()=>{var s;(s=t.current)==null||s.syncAreas();let e=0,n=0;return U.subscribe(()=>{var c,d;const r=U.getState().areas;if(r.size!==e){e=r.size,n=Date.now(),(c=t.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!==n&&(n=i,(d=t.current)==null||d.syncAreas())})},[t])}function cO(t){x.useEffect(()=>{var s;(s=t.current)==null||s.syncBuildings();let e=0,n=0;return U.subscribe(()=>{var c,d;const r=U.getState().buildings;if(r.size!==e){e=r.size,n=Date.now(),(c=t.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!==n&&(n=i,(d=t.current)==null||d.syncBuildings())})},[t])}function uO(t,e){x.useEffect(()=>{var n;(n=t.current)==null||n.highlightArea(e)},[t,e])}function dO(t,e){x.useEffect(()=>{var n;(n=t.current)==null||n.setPowerSaving(e)},[t,e])}function Pt(t,e,n,s,a={},r="global"){return{id:t,name:e,description:n,key:s,modifiers:a,enabled:!0,context:r}}const Lg=[Pt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Pt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Pt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Pt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Pt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Pt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Pt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Pt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Pt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Pt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Pt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Pt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Pt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Pt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Pt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Pt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Pt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Pt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Pt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Pt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Pt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Pt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Pt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Pt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Pt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Pt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Pt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Pt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Pt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Pt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Pt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Pt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Pt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Pt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Pt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Pt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Pt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Pt("clear-context","Clear Context","Clear context of the selected agent","c",{alt:!0,shift:!0}),Pt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Pt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Pt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Pt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Pt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Pt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Pt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Pt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Pt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Pt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function Tn(t,e){if(!e||!e.enabled)return!1;const{ctrl:n,alt:s,shift:a}=e.modifiers,r=n?t.ctrlKey||t.metaKey:!t.ctrlKey&&!t.metaKey,i=s?t.altKey:!t.altKey,c=a?t.shiftKey:!t.shiftKey;let d;if(n?d=(t.ctrlKey||t.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 t.code===m}if(f.length===1&&/^[0-9]$/.test(f)){const m=`Digit${f}`;return t.code===m}return f==="Space"||f===" "?t.code==="Space":t.key===f}function Tq(t){const e=[];if(t.modifiers.ctrl){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌘":"Ctrl")}if(t.modifiers.alt){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌥":"Alt")}t.modifiers.shift&&e.push("Shift"),t.modifiers.meta&&e.push("⌘");let n=t.key;return n===" "?n="Space":n.length===1&&(n=n.toUpperCase()),e.push(n),e.join("+")}function _q(t,e,n,s){return t.filter(a=>{if(a.id===n||!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 fO({sceneRef:t,spawnModal:e,commanderModal:n,explorerModal:s,spotlightModal:a,deleteConfirmModal:r,onRequestBuildingDelete:i,onOpenDatabasePanel:c,onCloseDatabasePanel:d,databasePanelOpen:f}){x.useEffect(()=>{const h=m=>{var R,z,$,W;const b=U.getShortcuts(),y=m.target,w=y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true"||!!y.closest(".cm-editor"),C=b.find(L=>L.id==="deselect-all");if(Tn(m,C)){if(y.closest(".guake-bottom-terminal-embed"))return;if(ep()){m.preventDefault();return}const L=U.getState();if(L.activeTool==="rectangle"||L.activeTool==="circle"){(R=t.current)==null||R.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():L.terminalOpen?(U.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(U.deselectAll(),(z=t.current)==null||z.refreshSelectionVisuals())}for(let L=1;L<=9;L++){const F=b.find(H=>H.id===`select-agent-${L}`);if(Tn(m,F)){m.preventDefault();const H=U.getState(),V=L-1,G=Array.from(H.agents.keys());V<G.length&&(U.selectAgent(G[V]),($=t.current)==null||$.refreshSelectionVisuals());return}}const N=b.find(L=>L.id==="spawn-agent");if(Tn(m,N)){m.preventDefault(),e.open();return}const k=b.find(L=>L.id==="toggle-commander-tab");if(Tn(m,k)&&!w){m.preventDefault(),n.toggle();return}const j=b.find(L=>L.id==="toggle-commander");if(Tn(m,j)){m.preventDefault(),n.toggle();return}const S=b.find(L=>L.id==="toggle-file-explorer");if(Tn(m,S)){m.preventDefault();const L=U.getState();if(s.isOpen||L.explorerFolderPath!==null||L.explorerAreaId!==null)s.close(),U.closeFileExplorer();else{const H=U.getLastExplorerState();if((H==null?void 0:H.type)==="folder")U.openFileExplorer(H.path);else if((H==null?void 0:H.type)==="area")if(L.areas.has(H.areaId))s.open(H.areaId);else{const V=Array.from(L.areas.values()).filter(G=>G.directories&&G.directories.length>0);V.length>0&&s.open(V[0].id)}else{const V=Array.from(L.areas.values()).filter(G=>G.directories&&G.directories.length>0);V.length>0&&s.open(V[0].id)}}return}if(m.altKey&&!m.ctrlKey&&!m.shiftKey&&!m.metaKey&&m.code==="KeyD"){if(m.preventDefault(),m.stopPropagation(),f){d();return}const L=localStorage.getItem("tide-commander-last-database-building"),F=U.getState();if(L){const H=F.buildings.get(L);if((H==null?void 0:H.type)==="database"){c(L);return}}for(const[H,V]of F.buildings)if(V.type==="database"){c(H);return}return}const T=b.find(L=>L.id==="toggle-spotlight");if(Tn(m,T)||m.altKey&&!m.ctrlKey&&!m.metaKey&&m.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:T,altKey:m.altKey,code:m.code}),m.preventDefault(),a.toggle();return}const D=b.find(L=>L.id==="toggle-2d-view");if(Tn(m,D)){m.preventDefault();const L=U.getState().viewMode,F=L==="3d"?"2d":L==="2d"?"dashboard":"3d";U.setViewMode(F);return}const E=b.find(L=>L.id==="clear-context");if(Tn(m,E)){m.preventDefault();const L=U.getState(),F=L.selectedAgentIds.size===1?Array.from(L.selectedAgentIds)[0]:null;F&&U.clearContext(F);return}const I=b.find(L=>L.id==="next-working-agent"),O=b.find(L=>L.id==="prev-working-agent");if((Tn(m,I)||Tn(m,O))&&!w){const L=U.getState();if(L.terminalOpen)return;const F=Array.from(L.agents.values());let H=F.filter(K=>L.agentsWithUnseenOutput.has(K.id));if(H.length===0&&(H=F.filter(K=>K.status==="working")),H.length===0)return;m.preventDefault();const V=L.selectedAgentIds.size===1?Array.from(L.selectedAgentIds)[0]:null,G=V?H.findIndex(K=>K.id===V):-1;let B;Tn(m,I)?B=G===-1?0:(G+1)%H.length:B=G===-1?H.length-1:(G-1+H.length)%H.length,U.selectAgent(H[B].id),(W=t.current)==null||W.refreshSelectionVisuals();return}const _=b.find(L=>L.id==="delete-selected"),M=b.find(L=>L.id==="delete-selected-backspace");if((Tn(m,_)||Tn(m,M))&&!w){const L=U.getState();if(L.selectedAgentIds.size>0){m.preventDefault(),r.open();return}if(L.selectedBuildingIds.size>0){m.preventDefault(),i();return}return}};return document.addEventListener("keydown",h,!0),()=>document.removeEventListener("keydown",h,!0)},[t,e,n,s,a,r,i,c,d,f])}function pO(){const[t,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()&&(ep()||(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()?ep()?a=Date.now():(c=window.__tideSetBackNavModal)==null||c.call(window,!0):(ep(),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:t,setShowBackNavModal:e,handleLeave:()=>{e(!1);const s=window.__tideHistoryDepth??2;window.history.go(-(s+1))}}}const Ig="agent-order-change";function hO(t){const e=x.useMemo(()=>new Set(t.map(d=>d.id)),[t]),[n,s]=x.useState(()=>Na(pt.AGENT_ORDER,[]));x.useEffect(()=>{const d=f=>{s(f.detail)};return window.addEventListener(Ig,d),()=>{window.removeEventListener(Ig,d)}},[]);const a=x.useMemo(()=>{const d=n.filter(b=>e.has(b)),f=t.filter(b=>!d.includes(b.id)).map(b=>b.id),h=[...d,...f],m=new Map(t.map(b=>[b.id,b]));return h.map(b=>m.get(b)).filter(b=>b!==void 0)},[t,n,e]),r=x.useCallback(d=>{s(d),La(pt.AGENT_ORDER,d),window.dispatchEvent(new CustomEvent(Ig,{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([]),La(pt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const d=n.filter(f=>e.has(f));d.length!==n.length&&r(d)},[e,n,r]),{orderedAgents:a,moveAgent:i,resetOrder:c}}function Ta(t){const e=x.useRef(null),n=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(),t()),e.current=null},[t]);return{handleMouseDown:n,handleClick:s}}const mO=3e4;function gO(){const t=x.useRef(null);x.useEffect(()=>{const e=async()=>{var i,c;const n=U.getState(),s=new Map,a=new Map;for(const[d,f]of n.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 Bt(Rt(`/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 w=U.getState().buildings.get(y);w&&w.gitChangesCount!==b&&U.updateBuildingLocal(y,{gitChangesCount:b})}}catch{}const r=new Map;for(const[d,f]of n.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 Bt(Rt(`/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 w=U.getState().areas.get(b);if(!w)continue;const C=w.directoryGitCounts?[...w.directoryGitCounts]:new Array(w.directories.length).fill(0);let N=!1;for(const{dirIndex:k,count:j}of y)C[k]!==j&&(C[k]=j,N=!0);N&&U.updateAreaLocal(b,{directoryGitCounts:C})}}catch{}};return e(),t.current=setInterval(e,mO),()=>{t.current&&(clearInterval(t.current),t.current=null)}},[])}const Pg={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:"",vibrationIntensity:1,tabTitle:""},rS=90,Bg=["simple","chat","advanced"],iS=55,oS=20,lS=95,bO=200,xO=12e4,yO=5,la=new Map;function vO(t){const e=la.get(t);e&&(la.delete(t),la.set(t,e))}function wO(){for(;la.size>yO;){const t=la.keys().next().value;if(t!==void 0)la.delete(t);else break}}function Hj(t){la.delete(t)}function kO(t){return t.trim().replace(/\r\n/g,`
42
+ */var Sk;function sD(){if(Sk)return Ng;Sk=1;var t=jx();function e(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var n=typeof Object.is=="function"?Object.is:e,s=t.useState,a=t.useEffect,r=t.useLayoutEffect,i=t.useDebugValue;function c(m,b){var y=b(),w=s({inst:{value:y,getSnapshot:b}}),C=w[0].inst,N=w[1];return r(function(){C.value=y,C.getSnapshot=b,d(C)&&N({inst:C})},[m,y,b]),a(function(){return d(C)&&N({inst:C}),m(function(){d(C)&&N({inst:C})})},[m]),i(y),y}function d(m){var b=m.getSnapshot;m=m.value;try{var y=b();return!n(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 Ng.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h,Ng}var Ck;function aD(){return Ck||(Ck=1,jg.exports=sD()),jg.exports}var rD=aD();const iD=(t,e)=>{if(No(e))return e;if(qM(e)&&No(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const n=t[t.length-1];return typeof n=="function"?"":n}return t},oD={t:iD,ready:!1},lD=()=>()=>{},dt=(t,e={})=>{var _,M,R;const{i18n:n}=e,{i18n:s,defaultNS:a}=x.useContext(tD)||{},r=n||s||ZM();r&&!r.reportNamespaces&&(r.reportNamespaces=new nD),r||zb(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=x.useMemo(()=>{var z;return{...XM(),...(z=r==null?void 0:r.options)==null?void 0:z.react,...e}},[r,e]),{useSuspense:c,keyPrefix:d}=i,f=t||a||((_=r==null?void 0:r.options)==null?void 0:_.defaultNS),h=No(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(z=>{if(!r)return lD;const{bindI18n:$,bindI18nStore:W}=i,L=()=>{b.current+=1,z()};return $&&r.on($,L),W&&r.store.on(W,L),()=>{$&&$.split(" ").forEach(F=>r.off(F,L)),W&&W.split(" ").forEach(F=>r.store.off(F,L))}},[r,i]),w=x.useRef(),C=x.useCallback(()=>{if(!r)return oD;const z=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(V=>WM(V,r,i)),$=e.lng||r.language,W=b.current,L=w.current;if(L&&L.ready===z&&L.lng===$&&L.keyPrefix===d&&L.revision===W)return L;const H={t:r.getFixedT($,i.nsMode==="fallback"?m:m[0],d),ready:z,lng:$,keyPrefix:d,revision:W};return w.current=H,H},[r,m,d,i,e.lng]),[N,k]=x.useState(0),{t:j,ready:S}=rD.useSyncExternalStore(y,C,C);x.useEffect(()=>{if(r&&!S&&!c){const z=()=>k($=>$+1);e.lng?kk(r,e.lng,m,z):$b(r,m,z)}},[r,e.lng,m,S,c,N]);const T=r||{},D=x.useRef(null),E=x.useRef(),I=z=>{const $=Object.getOwnPropertyDescriptors(z);$.__original&&delete $.__original;const W=Object.create(Object.getPrototypeOf(z),$);if(!Object.prototype.hasOwnProperty.call(W,"__original"))try{Object.defineProperty(W,"__original",{value:z,writable:!1,enumerable:!1,configurable:!1})}catch{}return W},O=x.useMemo(()=>{const z=T,$=z==null?void 0:z.language;let W=z;z&&(D.current&&D.current.__original===z?E.current!==$?(W=I(z),D.current=W,E.current=$):W=D.current:(W=I(z),D.current=W,E.current=$));const L=!S&&!c?(...H)=>(zb(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."),j(...H)):j,F=[L,W,S];return F.t=L,F.i18n=W,F.ready=S,F},[j,T,S,T.resolvedLanguage,T.language,T.languages]);if(r&&c&&!S)throw new Promise(z=>{const $=()=>z();e.lng?kk(r,e.lng,m,$):$b(r,m,$)});return O};function Hb(t){"@babel/helpers - typeof";return Hb=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},Hb(t)}function xj(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":Hb(XMLHttpRequest))==="object"}function cD(t){return!!t&&typeof t.then=="function"}function uD(t){return cD(t)?t:Promise.resolve(t)}var dD=/\{\{(.+?)\}\}/g;function Ak(t,e){return t.replace(dD,function(n,s){var a=e[s.trim()];return a??n})}const fD="modulepreload",pD=function(t){return"/"+t},jk={},vt=function(e,n,s){let a=Promise.resolve();if(n&&n.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(n.map(f=>{if(f=pD(f),f in jk)return;jk[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":fD,h||(b.as="script"),b.crossOrigin="",b.href=f,d&&b.setAttribute("nonce",d),document.head.appendChild(b),h)return new Promise((y,w)=>{b.addEventListener("load",y),b.addEventListener("error",()=>w(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(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,s)}return n}function Tk(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Nk(Object(n),!0).forEach(function(s){hD(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Nk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function hD(t,e,n){return(e=mD(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mD(t){var e=gD(t,"string");return To(e)=="symbol"?e:e+""}function gD(t,e){if(To(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var s=n.call(t,e);if(To(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function To(t){"@babel/helpers - typeof";return To=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},To(t)}var Di=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Di=global.fetch:typeof window<"u"&&window.fetch&&(Di=window.fetch);var zu;xj()&&(typeof global<"u"&&global.XMLHttpRequest?zu=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(zu=window.XMLHttpRequest));var mp;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?mp=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(mp=window.ActiveXObject));typeof Di!="function"&&(Di=void 0);if(!Di&&!zu&&!mp)try{vt(()=>import("./browser-ponyfill-DZOWXZ4K.js").then(t=>t.b),__vite__mapDeps([0,1])).then(function(t){Di=t.default}).catch(function(){})}catch{}var Wb=function(e,n){if(n&&To(n)==="object"){var s="";for(var a in n)s+="&"+encodeURIComponent(a)+"="+encodeURIComponent(n[a]);if(!s)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+s.slice(1)}return e},_k=function(e,n,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,n);if(i instanceof Promise){i.then(r).catch(s);return}}typeof fetch=="function"?fetch(e,n).then(r).catch(s):Di(e,n).then(r).catch(s)},Ek=!1,bD=function(e,n,s,a){e.queryStringParams&&(n=Wb(n,e.queryStringParams));var r=Tk({},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=Tk({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},Ek?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{_k(n,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]}),_k(n,c,a,d),Ek=!0}catch(h){a(h)}}},xD=function(e,n,s,a){s&&To(s)==="object"&&(s=Wb("",s).slice(1)),e.queryStringParams&&(n=Wb(n,e.queryStringParams));try{var r=zu?new zu:new mp("MSXML2.XMLHTTP.3.0");r.open(s?"POST":"GET",n,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)}},yD=function(e,n,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Di&&n.indexOf("file:")!==0)return bD(e,n,s,a);if(xj()||typeof ActiveXObject=="function")return xD(e,n,s,a);a(new Error("No fetch and no xhr implementation found!"))};function Vl(t){"@babel/helpers - typeof";return Vl=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},Vl(t)}function Mk(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,s)}return n}function Tg(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Mk(Object(n),!0).forEach(function(s){yj(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Mk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function vD(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function wD(t,e){for(var n=0;n<e.length;n++){var s=e[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,vj(s.key),s)}}function kD(t,e,n){return e&&wD(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function yj(t,e,n){return(e=vj(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vj(t){var e=SD(t,"string");return Vl(e)=="symbol"?e:e+""}function SD(t,e){if(Vl(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var s=n.call(t,e);if(Vl(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var CD=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(n){return JSON.parse(n)},stringify:JSON.stringify,parsePayload:function(n,s,a){return yj({},s,a||"")},parseLoadPayload:function(n,s){},request:yD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},wj=(function(){function t(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};vD(this,t),this.services=e,this.options=n,this.allOptions=s,this.type="backend",this.init(e,n,s)}return kD(t,[{key:"init",value:function(n){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=n,this.options=Tg(Tg(Tg({},CD()),this.options||{}),a),this.allOptions=r,this.services&&this.options.reloadInterval){var i=setInterval(function(){return s.reload()},this.options.reloadInterval);Vl(i)==="object"&&typeof i.unref=="function"&&i.unref()}}},{key:"readMulti",value:function(n,s,a){this._readAny(n,n,s,s,a)}},{key:"read",value:function(n,s,a){this._readAny([n],n,[s],s,a)}},{key:"_readAny",value:function(n,s,a,r,i){var c=this,d=this.options.loadPath;typeof this.options.loadPath=="function"&&(d=this.options.loadPath(n,a)),d=uD(d),d.then(function(f){if(!f)return i(null,{});var h=Ak(f,{lng:n.join("+"),ns:a.join("+")});c.loadUrl(h,i,s,r)})}},{key:"loadUrl",value:function(n,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,n,f,function(h,m){if(m&&(m.status>=500&&m.status<600||!m.status))return s("failed loading "+n+"; status code: "+m.status,!0);if(m&&m.status>=400&&m.status<500)return s("failed loading "+n+"; 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 "+n+": "+h.message,!0)}if(h)return s(h,!1);var w,C;try{typeof m.data=="string"?w=i.options.parse(m.data,a,r):w=m.data}catch{C="failed parsing "+n+" to json"}if(C)return s(C,!1);s(null,w)})}},{key:"create",value:function(n,s,a,r,i){var c=this;if(this.options.addPath){typeof n=="string"&&(n=[n]);var d=this.options.parsePayload(s,a,r),f=0,h=[],m=[];n.forEach(function(b){var y=c.options.addPath;typeof c.options.addPath=="function"&&(y=c.options.addPath(b,s));var w=Ak(y,{lng:b,ns:s});c.options.request(c.options,w,d,function(C,N){f+=1,h.push(C),m.push(N),f===n.length&&typeof i=="function"&&i(h,m)})})}}},{key:"reload",value:function(){var n=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){n.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)})})})}}}])})();wj.type="backend";const{slice:AD,forEach:jD}=[];function ND(t){return jD.call(AD.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function TD(t){return typeof t!="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(n=>n.test(t))}const Dk=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,_D=function(t,e){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let r=`${t}=${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(!Dk.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!Dk.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},Rk={create(t,e,n,s){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+n*60*1e3)),s&&(a.domain=s),document.cookie=_D(t,e,a)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let s=0;s<n.length;s++){let a=n[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(t,e){this.create(t,"",-1,e)}};var ED={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return Rk.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;n&&typeof document<"u"&&Rk.create(n,t,s,a,r)}},MD={name:"querystring",lookup(t){var s;let{lookupQuerystring:e}=t,n;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&&(n=i[c].substring(d+1))}}return n}},DD={name:"hash",lookup(t){var a;let{lookupHash:e,lookupFromHashIndex:n}=t,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&&n>-1){const c=r.match(/\/([a-zA-Z-]*)/g);return Array.isArray(c)?(a=c[typeof n=="number"?n:0])==null?void 0:a.replace("/",""):void 0}}}return s}};let Nl=null;const Ok=()=>{if(Nl!==null)return Nl;try{if(Nl=typeof window<"u"&&window.localStorage!==null,!Nl)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Nl=!1}return Nl};var RD={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&Ok())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&Ok()&&window.localStorage.setItem(n,t)}};let Tl=null;const Lk=()=>{if(Tl!==null)return Tl;try{if(Tl=typeof window<"u"&&window.sessionStorage!==null,!Tl)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Tl=!1}return Tl};var OD={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&Lk())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&Lk()&&window.sessionStorage.setItem(n,t)}},LD={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:s,language:a}=navigator;if(n)for(let r=0;r<n.length;r++)e.push(n[r]);s&&e.push(s),a&&e.push(a)}return e.length>0?e:void 0}},ID={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const s=e||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(n=s.getAttribute("lang")),n}},PD={name:"path",lookup(t){var a;let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?(a=n[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},BD={name:"subdomain",lookup(t){var a,r;let{lookupFromSubdomainIndex:e}=t;const n=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[n]}};let kj=!1;try{document.cookie,kj=!0}catch{}const Sj=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];kj||Sj.splice(1,1);const FD=()=>({order:Sj,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class Cj{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=ND(n,this.options||{},FD()),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(ED),this.addDetector(MD),this.addDetector(RD),this.addDetector(OD),this.addDetector(LD),this.addDetector(ID),this.addDetector(PD),this.addDetector(BD),this.addDetector(DD)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(s=>{if(this.detectors[s]){let a=this.detectors[s].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(n=n.concat(a))}}),n=n.filter(s=>s!=null&&!TD(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(e,this.options)}))}}Cj.type="languageDetector";const gp={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},qb={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},zD={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},Sq=["#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"],Af={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function Tx(t){const n=Math.floor((Date.now()-t)/1e3)/60;return n<1?Af.recent:n<5?Af.short:n<30?Af.medium:Af.long}function _x(t){return gp[t]??gp.default}let Zf=null;function Aj(){if(!Zf)try{Zf=globalThis.__i18n}catch{}return Zf}function $D(t){Zf=t}function UD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function HD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function WD(t){var a;const e=Aj(),n=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),s=Math.floor((Date.now()-t)/1e3);return s<60?n?n("common:time.seconds",{count:s}):`${s}s`:s<3600?n?n("common:time.minutes",{count:Math.floor(s/60)}):`${Math.floor(s/60)}m`:s<86400?n?n("common:time.hours",{count:Math.floor(s/3600)}):`${Math.floor(s/3600)}h`:n?n("common:time.days",{count:Math.floor(s/86400)}):`${Math.floor(s/86400)}d`}function Ex(t){var f;const e=Aj(),n=(f=e==null?void 0:e.t)==null?void 0:f.bind(e),s=Math.floor((Date.now()-t)/1e3);if(s<5)return n?n("common:time.justNow"):"just now";if(s<60)return n?n("common:time.secondsAgo",{count:s}):`${s}s ago`;const a=Math.floor(s/60);if(a<60){const h=s%60;return h>0?n?n("common:time.minutesSecondsAgo",{minutes:a,seconds:h}):`${a}m ${h}s ago`:n?n("common:time.minutesAgo",{count:a}):`${a}m ago`}const r=Math.floor(a/60),i=a%60;if(r<24)return i>0?n?n("common:time.hoursMinutesAgo",{hours:r,minutes:i}):`${r}h ${i}m ago`:n?n("common:time.hoursAgo",{count:r}):`${r}h ago`;const c=Math.floor(r/24),d=r%24;return d>0?n?n("common:time.daysHoursAgo",{days:c,hours:d}):`${c}d ${d}h ago`:n?n("common:time.daysAgo",{count:c}):`${c}d ago`}function Tu(t,e){return t?e?t.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():t:""}On.use(wj).use(Cj).use(eD).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:"/locales/{{lng}}/{{ns}}.json"},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{$D(On)});const pt={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",GLOBAL_SUPERVISOR_COLLAPSED:"tide-global-supervisor-collapsed",TOOLS_COLLAPSED:"tide-tool-history-collapsed",FILES_COLLAPSED:"tide-file-history-collapsed",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",MOBILE_OVERVIEW_HEIGHT:"tide-mobile-overview-height",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"},Vb="tide-backend-url-change";function Na(t,e){try{const n=localStorage.getItem(t);return n===null?e:JSON.parse(n)}catch{return e}}function Fa(t,e=""){try{return localStorage.getItem(t)??e}catch{return e}}function Ni(t,e=!1){try{const n=localStorage.getItem(t);return n===null?e:n==="true"}catch{return e}}function Mx(t,e){try{const n=localStorage.getItem(t);if(n===null)return e;const s=Number(n);return isNaN(s)?e:s}catch{return e}}function La(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Wr(t,e){try{localStorage.setItem(t,e)}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Ti(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Dx(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Ik(t){try{localStorage.removeItem(t)}catch(e){console.error(`Failed to remove from localStorage: ${t}`,e)}}function Ea(){const t=Rx();return t?t.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ii(){return Fa(pt.AUTH_TOKEN,"")}function Rx(){return Fa(pt.BACKEND_URL,"")}function qD(t){const e=t.trim();Wr(pt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vb,{detail:e}))}function VD(t){if(typeof window>"u")return()=>{};const e=s=>{t(s.detail)},n=s=>{s.key===pt.BACKEND_URL&&t(s.newValue??"")};return window.addEventListener(Vb,e),window.addEventListener("storage",n),()=>{window.removeEventListener(Vb,e),window.removeEventListener("storage",n)}}function Rt(t){return`${Ea()}${t}`}async function Bt(t,e){const n=Ii(),s=new Headers(e==null?void 0:e.headers);return n&&s.set("X-Auth-Token",n),fetch(t,{...e,headers:s,cache:"no-store"})}function Yb(t){const e=Ii();if(!e)return t;try{const n=!t.startsWith("http://")&&!t.startsWith("https://"),s=n?"http://dummy":void 0,a=new URL(t,s);return a.searchParams.set("token",e),n?a.pathname+a.search:a.toString()}catch{const n=t.includes("?")?"&":"?";return`${t}${n}token=${encodeURIComponent(e)}`}}function cs(t=!1,e){const[n,s]=x.useState(t),[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:n,data:a,open:i,close:c,toggle:d,setData:r}}function YD(){const[t,e]=x.useState(null),n=x.useCallback(a=>{e(a)},[]),s=x.useCallback(()=>{e(null)},[]);return{isOpen:t!==null,id:t,open:n,close:s}}function GD(){const[t,e]=x.useState(!1),[n,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:t,screenPosition:n,worldPosition:a,target:i,open:d,close:f}}const ca=[],KD=new Set;function bp(){KD.forEach(t=>t())}function QD(t,e){const n=ca.findIndex(s=>s.id===t);return n!==-1&&ca.splice(n,1),ca.push({id:t,close:e}),bp(),()=>{const s=ca.findIndex(a=>a.id===t);s!==-1&&(ca.splice(s,1),bp())}}function ep(){return ca.length===0?!1:(ca.pop().close(),bp(),!0)}function XD(t){const e=ca.findIndex(n=>n.id===t);return e===-1?!1:e<ca.length-1}function JD(...t){const e=new Set(t);for(;ca.length>0;){const n=ca[ca.length-1];if(e.has(n.id))break;ca.pop().close()}bp()}function Xt(t,e,n){const s=x.useRef(n);s.current=n,x.useEffect(()=>e?QD(t,()=>s.current()):void 0,[t,e])}const $u=5,_g={0:0,1:4,2:8,3:14,4:25,5:50};let _u=null,Pk=!1;async function ZD(){if(Pk)return _u;Pk=!0;try{const t=await vt(()=>import("./index-DENcwRRk.js"),__vite__mapDeps([2,3,1,4]));_u={Haptics:t.Haptics,ImpactStyle:t.ImpactStyle}}catch{}return _u}ZD();function xp(t){const e=Math.round(t),n=e<=0?0:e>=$u?$u:e;if(n!==0){if(_u){const{Haptics:s,ImpactStyle:a}=_u;if(n<=2&&typeof s.selectionChanged=="function"){s.selectionChanged().catch(()=>{navigator.vibrate&&navigator.vibrate(_g[n])});return}const i={3:"Light",4:"Medium",5:"Heavy"}[n];if(i&&a[i]){s.impact({style:a[i]}).catch(()=>{navigator.vibrate&&navigator.vibrate(_g[n])});return}}navigator.vibrate&&navigator.vibrate(_g[n])}}function Bk(t,e){const{threshold:n=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(C=>{if(C.touches.length!==1)return;const N=C.touches[0];h.current={startX:N.clientX,startY:N.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),b=x.useCallback(C=>{if(!h.current.isTracking||C.touches.length!==1)return;const N=C.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 T=window.innerWidth*.4,D=Math.max(-1,Math.min(1,k/T));Math.abs(k)>=12&&(h.current.hasMovedEnough=!0,c==null||c(D))},[s,c,d]),y=x.useCallback(C=>{const N=h.current.isTracking,k=h.current.hasMovedEnough;if(!N)return;const j=C.changedTouches[0],S=j.clientX-h.current.startX,T=Math.abs(j.clientY-h.current.startY),D=Date.now()-h.current.startTime;h.current.isTracking=!1,h.current.hasMovedEnough=!1,Math.abs(S)>=n&&T<=s&&D<500?(xp(f),S>0?i==null||i():r==null||r()):k&&(d==null||d())},[n,s,f,r,i,d]),w=x.useCallback(()=>{const C=h.current.hasMovedEnough;h.current.isTracking=!1,h.current.hasMovedEnough=!1,C&&(d==null||d())},[d]);x.useEffect(()=>{const C=t.current;if(!(!C||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return C.addEventListener("touchstart",m,{passive:!0}),C.addEventListener("touchmove",b,{passive:!0}),C.addEventListener("touchend",y,{passive:!0}),C.addEventListener("touchcancel",w,{passive:!0}),()=>{C.removeEventListener("touchstart",m),C.removeEventListener("touchmove",b),C.removeEventListener("touchend",y),C.removeEventListener("touchcancel",w)}},[t,a,m,b,y,w])}const Fk=8,eR=.93,zk=.4;function tR(t){const{gestureRef:e,agentListRef:n,enabled:s,onSelect:a}=t,[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=n.current;if(N){const k=Math.round(N.clientHeight/2);N.style.paddingTop=`${k}px`,N.style.paddingBottom=`${k}px`}},[n]),y=x.useCallback(()=>{f.current=!1,h.current=null,i(!1),d(null);const N=n.current;N&&(N.style.paddingTop="",N.style.paddingBottom="")},[n]),w=x.useCallback(N=>{const k=n.current;if(!k)return;k.scrollTop+=N;const j=k.getBoundingClientRect(),S=j.top+j.height/2,T=j.left+j.width/2,D=document.elementFromPoint(T,S);let E=null;if(D){const I=D.closest("[data-agent-id]");I&&k.contains(I)&&(E=I.dataset.agentId)}if(E!==h.current&&(h.current=E,d(E),E)){const I=U.getState().settings.vibrationIntensity??1;xp(I)}},[n]),C=x.useCallback(()=>{const N=h.current;if(N){const k=U.getState().settings.vibrationIntensity??1,j=k<=0?0:Math.min(k+1,$u);xp(j),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 j=!1,S=!1,T=0,D=0,E=0,I=0,O=0,_=0,M=0,R=0;const z=()=>{M&&(cancelAnimationFrame(M),M=0)},$=()=>{if(Math.abs(_)<zk){_=0;return}N.scrollTop+=_,_*=eR,M=requestAnimationFrame($)},W=V=>{if(z(),V.touches.length>=2){V.preventDefault(),j=!1,S=!1,R=(V.touches[0].clientY+V.touches[1].clientY)/2,b(),w(0);return}j=!0,S=!1,T=V.touches[0].clientX,D=V.touches[0].clientY,E=N.scrollTop,I=D,O=performance.now(),_=0},L=V=>{if(V.touches.length>=2){if(V.preventDefault(),(S||j)&&(S=!1,j=!1),!f.current){R=(V.touches[0].clientY+V.touches[1].clientY)/2,b(),w(0);return}const K=(V.touches[0].clientY+V.touches[1].clientY)/2,ne=R-K;R=K,w(ne);return}if(f.current&&V.touches.length===1){V.preventDefault();const K=V.touches[0].clientY,ne=R-K;R=K,w(ne);return}if(!j&&!S)return;const G=V.touches[0].clientX,B=V.touches[0].clientY;if(j&&!S){const K=Math.abs(G-T),ne=Math.abs(B-D);if(K<Fk&&ne<Fk)return;if(ne>=K)S=!0,j=!1,V.preventDefault();else{j=!1;return}}if(S){V.preventDefault();const K=performance.now(),ne=K-O;N.scrollTop=E+(D-B),ne>0&&(_=(I-B)/ne*16),I=B,O=K}},F=V=>{if(f.current&&V.touches.length===0){C();return}f.current||(S||j)&&V.touches.length===0&&(S&&Math.abs(_)>zk&&(M=requestAnimationFrame($)),S=!1,j=!1)},H=()=>{S=!1,j=!1,z(),f.current&&y()};return N.addEventListener("touchstart",W,{passive:!1}),N.addEventListener("touchmove",L,{passive:!1}),N.addEventListener("touchend",F,{passive:!0}),N.addEventListener("touchcancel",H,{passive:!0}),()=>{N.removeEventListener("touchstart",W),N.removeEventListener("touchmove",L),N.removeEventListener("touchend",F),N.removeEventListener("touchcancel",H),N.style.touchAction=k,z();const V=n.current;V&&(V.style.paddingTop="",V.style.paddingBottom="")}},[e,n,s,b,y,w,C]),{isActive:r,hoveredAgentId:c}}const nR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function sR(){return"documentPictureInPicture"in window}function aR(t,e){for(const r of t.styleSheets)try{if(r.cssRules){const i=e.createElement("style");for(const c of r.cssRules)i.appendChild(e.createTextNode(c.cssText));e.head.appendChild(i)}}catch{if(r.href){const i=e.createElement("link");i.rel="stylesheet",i.href=r.href,e.head.appendChild(i)}}const n=t.documentElement.style.cssText;n&&(e.documentElement.style.cssText=n);const s=getComputedStyle(t.documentElement),a=[];for(let r=0;r<s.length;r++){const i=s[r];i.startsWith("--")&&a.push(`${i}: ${s.getPropertyValue(i)}`)}if(a.length>0){const r=e.createElement("style");r.textContent=`:root { ${a.join("; ")} }`,e.head.appendChild(r)}}function rR(){const[t,e]=x.useState(!1),[n,s]=x.useState(null),[a,r]=x.useState(null),i=x.useRef(null),c=sR(),d=x.useCallback(()=>{if(i.current){const m=i.current.__cleanupFns;m&&m.forEach(b=>b()),i.current.close(),i.current=null}s(null),r(null),e(!1)},[]),f=x.useCallback(async m=>{if(!c)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;i.current&&d();const b={...nR,...m};try{const w=await window.documentPictureInPicture.requestWindow({width:b.width,height:b.height,disallowReturnToOpener:!0});i.current=w,b.copyStyleSheets&&aR(document,w.document);const C=w.document.createElement("div");C.id="pip-root",C.style.width="100%",C.style.height="100%",w.document.body.appendChild(C),w.document.body.style.margin="0",w.document.body.style.padding="0",w.document.body.style.overflow="hidden",w.addEventListener("pagehide",()=>{i.current=null,s(null),r(null),e(!1)});const N=[];if(b.keepOnTop&&b.keepOnTop!=="none"){const k=b.keepOnTop==="raise",j=()=>{i.current&&!i.current.closed&&setTimeout(()=>{i.current&&!i.current.closed&&(i.current.focus(),k&&setTimeout(()=>window.focus(),10))},50)},S=()=>{document.visibilityState==="visible"&&i.current&&!i.current.closed&&setTimeout(()=>{i.current&&!i.current.closed&&(i.current.focus(),k&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",j),document.addEventListener("visibilitychange",S),N.push(()=>window.removeEventListener("focus",j),()=>document.removeEventListener("visibilitychange",S))}return w.__cleanupFns=N,s(w),r(C),e(!0),!0}catch(y){return console.error("Failed to open Picture-in-Picture window:",y),!1}},[c,d]),h=x.useCallback(async m=>{t?d():await f(m)},[t,f,d]);return x.useEffect(()=>()=>{i.current&&i.current.close()},[]),x.useMemo(()=>({isOpen:t,pipWindow:n,pipContainer:a,isSupported:c,open:f,close:d,toggle:h}),[t,n,a,c,f,d,h])}function tu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class iR{constructor(){Xe(this,"messages",new Map);Xe(this,"logs",[]);Xe(this,"maxMessagesPerAgent",200);Xe(this,"maxLogs",500);Xe(this,"enabled",!0);Xe(this,"listeners",new Set);Xe(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,n){try{const s=JSON.parse(n);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${n.length}B`),this.addMessage(e,{id:tu(),agentId:e,direction:"sent",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:n.length,raw:n})}catch(s){console.error("[AgentDebugger] Failed to parse SENT message:",String(s).slice(0,80)),this.addMessage(e,{id:tu(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:n.length,raw:n})}}captureReceived(e,n){try{const s=JSON.parse(n);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${s.type}, size: ${n.length}B`),this.addMessage(e,{id:tu(),agentId:e,direction:"received",type:s.type||"unknown",payload:s.payload||s,timestamp:Date.now(),size:n.length,raw:n})}catch(s){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(s).slice(0,80)),this.addMessage(e,{id:tu(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(s)},timestamp:Date.now(),size:n.length,raw:n})}}addMessage(e,n){let s=this.messages.get(e);s||(s=[],this.messages.set(e,s)),s.push(n),console.log(`[AgentDebugger] Added message for ${e}, total: ${s.length}, type: ${n.type}, direction: ${n.direction}`),s.length>this.maxMessagesPerAgent&&s.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const n=this.getMessages(e),s=n.filter(i=>i.direction==="sent").length,a=n.filter(i=>i.direction==="received").length,r=[...new Set(n.map(i=>i.type))];return{total:n.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(n=>n(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,n,s,a){const r={id:tu(),level:e,message:n,data:s,timestamp:Date.now(),source:a};this.logs.push(r),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,n,s){this.log("debug",e,n,s)}info(e,n,s){this.log("info",e,n,s)}warn(e,n,s){this.log("warn",e,n,s)}error(e,n,s){this.log("error",e,n,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 vs=new iR,Uu={debug:(t,e,n)=>vs.debug(t,e,n),info:(t,e,n)=>vs.info(t,e,n),warn:(t,e,n)=>vs.warn(t,e,n),error:(t,e,n)=>vs.error(t,e,n)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var Yl;(function(t){t.Unimplemented="UNIMPLEMENTED",t.Unavailable="UNAVAILABLE"})(Yl||(Yl={}));class Eg extends Error{constructor(e,n,s){super(e),this.message=e,this.code=n,this.data=s}}const oR=t=>{var e,n;return t!=null&&t.androidBridge?"android":!((n=(e=t==null?void 0:t.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||n===void 0)&&n.bridge?"ios":"web"},lR=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},s=n.Plugins=n.Plugins||{},a=()=>e!==null?e.name:oR(t),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=n.PluginHeaders)===null||b===void 0?void 0:b.find(y=>y.name===m)},d=m=>t.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 w=a(),C=c(m);let N;const k=async()=>(!N&&w in b?N=typeof b[w]=="function"?N=await b[w]():N=b[w]:e!==null&&!N&&"web"in b&&(N=typeof b.web=="function"?N=await b.web():N=b.web),N),j=(O,_)=>{var M,R;if(C){const z=C==null?void 0:C.methods.find($=>_===$.name);if(z)return z.rtype==="promise"?$=>n.nativePromise(m,_.toString(),$):($,W)=>n.nativeCallback(m,_.toString(),$,W);if(O)return(M=O[_])===null||M===void 0?void 0:M.bind(O)}else{if(O)return(R=O[_])===null||R===void 0?void 0:R.bind(O);throw new Eg(`"${m}" plugin is not implemented on ${w}`,Yl.Unimplemented)}},S=O=>{let _;const M=(...R)=>{const z=k().then($=>{const W=j($,O);if(W){const L=W(...R);return _=L==null?void 0:L.remove,L}else throw new Eg(`"${m}.${O}()" is not implemented on ${w}`,Yl.Unimplemented)});return O==="addListener"&&(z.remove=async()=>_()),z};return M.toString=()=>`${O.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:O,writable:!1,configurable:!1}),M},T=S("addListener"),D=S("removeListener"),E=(O,_)=>{const M=T({eventName:O},_),R=async()=>{const $=await M;D({eventName:O,callbackId:$},_)},z=new Promise($=>M.then(()=>$({remove:R})));return z.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},z},I=new Proxy({},{get(O,_){switch(_){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return C?E:T;case"removeListener":return D;default:return S(_)}}});return s[m]=I,f.set(m,{name:m,proxy:I,platforms:new Set([...Object.keys(b),...C?[w]:[]])}),I};return n.convertFileSrc||(n.convertFileSrc=m=>m),n.getPlatform=a,n.handleError=d,n.isNativePlatform=r,n.isPluginAvailable=i,n.registerPlugin=h,n.Exception=Eg,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},cR=t=>t.Capacitor=lR(t),yp=cR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Ju=yp.registerPlugin;class Ox{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,n){let s=!1;this.listeners[e]||(this.listeners[e]=[],s=!0),this.listeners[e].push(n);const r=this.windowListeners[e];r&&!r.registered&&this.addWindowListener(r),s&&this.sendRetainedArgumentsForEvent(e);const i=async()=>this.removeListener(e,n);return Promise.resolve({remove:i})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,n,s){const a=this.listeners[e];if(!a){if(s){let r=this.retainedEventArguments[e];r||(r=[]),r.push(n),this.retainedEventArguments[e]=r}return}a.forEach(r=>r(n))}hasListeners(e){var n;return!!(!((n=this.listeners[e])===null||n===void 0)&&n.length)}registerWindowListener(e,n){this.windowListeners[n]={registered:!1,windowEventName:e,pluginEventName:n,handler:s=>{this.notifyListeners(n,s)}}}unimplemented(e="not implemented"){return new yp.Exception(e,Yl.Unimplemented)}unavailable(e="not available"){return new yp.Exception(e,Yl.Unavailable)}async removeListener(e,n){const s=this.listeners[e];if(!s)return;const a=s.indexOf(n);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 n=this.retainedEventArguments[e];n&&(delete this.retainedEventArguments[e],n.forEach(s=>{this.notifyListeners(e,s)}))}}const $k=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Uk=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class uR extends Ox{async getCookies(){const e=document.cookie,n={};return e.split(";").forEach(s=>{if(s.length<=0)return;let[a,r]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=Uk(a).trim(),r=Uk(r).trim(),n[a]=r}),n}async setCookie(e){try{const n=$k(e.key),s=$k(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=`${n}=${s||""}${a}; path=${r}; ${i};`}catch(n){return Promise.reject(n)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(n){return Promise.reject(n)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const n of e)document.cookie=n.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)}}}Ju("CapacitorCookies",{web:()=>new uR});const dR=async t=>new Promise((e,n)=>{const s=new FileReader;s.onload=()=>{const a=s.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},s.onerror=a=>n(a),s.readAsDataURL(t)}),fR=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=t[e[i]],a),{})},pR=(t,e=!0)=>t?Object.entries(t).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,hR=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),a=fR(t.headers)["content-type"]||"";if(typeof t.data=="string")n.body=t.data;else if(a.includes("application/x-www-form-urlencoded")){const r=new URLSearchParams;for(const[i,c]of Object.entries(t.data||{}))r.set(i,c);n.body=r.toString()}else if(a.includes("multipart/form-data")||t.data instanceof FormData){const r=new FormData;if(t.data instanceof FormData)t.data.forEach((c,d)=>{r.append(d,c)});else for(const c of Object.keys(t.data))r.append(c,t.data[c]);n.body=r;const i=new Headers(n.headers);i.delete("content-type"),n.headers=i}else(a.includes("application/json")||typeof t.data=="object")&&(n.body=JSON.stringify(t.data));return n};class mR extends Ox{async request(e){const n=hR(e,e.webFetchExtra),s=pR(e.params,e.shouldEncodeUrlParams),a=s?`${e.url}?${s}`:e.url,r=await fetch(a,n),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 dR(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 Cq=Ju("CapacitorHttp",{web:()=>new mR});var Hk;(function(t){t.Dark="DARK",t.Light="LIGHT",t.Default="DEFAULT"})(Hk||(Hk={}));var Wk;(function(t){t.StatusBar="StatusBar",t.NavigationBar="NavigationBar"})(Wk||(Wk={}));class gR extends Ox{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")}}Ju("SystemBars",{web:()=>new gR});var qk;(function(t){t[t.Sunday=1]="Sunday",t[t.Monday=2]="Monday",t[t.Tuesday=3]="Tuesday",t[t.Wednesday=4]="Wednesday",t[t.Thursday=5]="Thursday",t[t.Friday=6]="Friday",t[t.Saturday=7]="Saturday"})(qk||(qk={}));const Lx=Ju("LocalNotifications",{web:()=>vt(()=>import("./web-CmQWPACi.js"),__vite__mapDeps([5,3,1,4])).then(t=>new t.LocalNotificationsWeb)}),bR=Ju("ServerConfig");let xR=100;const yR="agent_alerts",Gb="tide-notification-tap";function vR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function jj(t){if(vR()){U.openTerminalOnMobile(t);return}if(document.querySelector(".commander-overlay")){U.requestCommanderExpand(t);return}U.selectAgent(t),U.setTerminalOpen(!0)}function Zu(){try{return yp.isNativePlatform()}catch{return!1}}async function wR(){if(Zu())try{const t=await Lx.requestPermissions();return console.log("[Notifications] Permission result:",t.display),t.display==="granted"}catch(t){return console.error("[Notifications] Failed to request permissions:",t),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function kR(t){const{title:e,body:n,icon:s,data:a}=t;if(Zu())try{const r=xR++;console.log("[Notifications] Scheduling native notification id="+r,e),await Lx.schedule({notifications:[{id:r,title:e,body:n,extra:a,channelId:yR,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:n,icon:s,data:a});r.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(Gb,{detail:a}))}}}let Mg=!1;async function SR(t){const e=[];if(Mg)return()=>{};if(Mg=!0,t){const n=s=>{const a=s;a.detail&&t(a.detail)};window.addEventListener(Gb,n),e.push(()=>window.removeEventListener(Gb,n))}if(Zu())try{const n=await Lx.addListener("localNotificationActionPerformed",s=>{t&&s.notification.extra&&t(s.notification.extra)});e.push(()=>n.remove())}catch(n){console.error("[Notifications] Failed to add tap listener:",n)}return()=>{e.forEach(n=>n()),Mg=!1}}function CR(t,e){Zu()&&bR.syncConfig({url:t,token:e}).catch(n=>{console.warn("[Notifications] Failed to sync config to native service:",n)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const Yp=()=>window.__tideWsState.ws,Vk=t=>{window.__tideWsState.ws=t},AR=()=>window.__tideWsState.isConnecting,nu=t=>{window.__tideWsState.isConnecting=t},Kb=()=>window.__tideWsState.reconnectAttempts,Qb=t=>{window.__tideWsState.reconnectAttempts=t},Nj=()=>window.__tideWsState.reconnectTimeout,Tj=t=>{window.__tideWsState.reconnectTimeout=t},Yk=10,Ix="tide_ws_has_connected";function Gk(){return sessionStorage.getItem(Ix)==="true"}function jR(t){sessionStorage.setItem(Ix,"true")}function NR(){sessionStorage.removeItem(Ix)}let _j=null;const TR=t=>{_j=t},Kk=()=>_j,De={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 Ej(t){t.onToast&&(De.onToast=t.onToast),t.onAgentCreated&&(De.onAgentCreated=t.onAgentCreated),t.onAgentUpdated&&(De.onAgentUpdated=t.onAgentUpdated),t.onAgentDeleted&&(De.onAgentDeleted=t.onAgentDeleted),t.onAgentsSync&&(De.onAgentsSync=t.onAgentsSync),t.onAreasSync&&(De.onAreasSync=t.onAreasSync),t.onSpawnError&&(De.onSpawnError=t.onSpawnError),t.onSpawnSuccess&&(De.onSpawnSuccess=t.onSpawnSuccess),t.onToolUse&&(De.onToolUse=t.onToolUse),t.onDirectoryNotFound&&(De.onDirectoryNotFound=t.onDirectoryNotFound),t.onDelegation&&(De.onDelegation=t.onDelegation),t.onCustomClassesSync&&(De.onCustomClassesSync=t.onCustomClassesSync),t.onReconnect&&(De.onReconnect=t.onReconnect),t.onAgentNotification&&(De.onAgentNotification=t.onAgentNotification),t.onBuildingUpdated&&(De.onBuildingUpdated=t.onBuildingUpdated),t.onSubagentStarted&&(De.onSubagentStarted=t.onSubagentStarted),t.onSubagentCompleted&&(De.onSubagentCompleted=t.onSubagentCompleted)}function _R(){De.onToast=null,De.onAgentCreated=null,De.onAgentUpdated=null,De.onAgentDeleted=null,De.onAgentsSync=null,De.onAreasSync=null,De.onSpawnError=null,De.onSpawnSuccess=null,De.onToolUse=null,De.onDirectoryNotFound=null,De.onDelegation=null,De.onCustomClassesSync=null,De.onReconnect=null,De.onAgentNotification=null,De.onSubagentStarted=null,De.onSubagentCompleted=null}function ER(){De.onAgentCreated=null,De.onAgentUpdated=null,De.onAgentDeleted=null,De.onAgentsSync=null,De.onAreasSync=null,De.onToolUse=null,De.onDelegation=null,De.onCustomClassesSync=null,De.onBuildingUpdated=null,De.onSubagentStarted=null,De.onSubagentCompleted=null}const jf=new Map,MR=new Map,Xb={start(t){},end(t){},async measure(t,e){this.start(t);try{return await e()}finally{this.end(t)}},measureSync(t,e){this.start(t);try{return e()}finally{this.end(t)}},getMetrics(t){const e={},n=t?jf.has(t)?[[t,jf.get(t)]]:[]:Array.from(jf.entries());for(const[s,a]of n){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(){jf.clear(),MR.clear()},report(){}};class DR{constructor(){Xe(this,"frames",[]);Xe(this,"lastFrameTime",0);Xe(this,"frameCount",0);Xe(this,"fps",0);Xe(this,"minFps",1/0);Xe(this,"maxFps",0);Xe(this,"fpsHistory",[]);Xe(this,"maxHistorySize",60)}tick(e=200){const n=performance.now();if(this.lastFrameTime>0){const s=n-this.lastFrameTime;s<e&&(this.frames.push(s),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=n,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((n,s)=>n+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((n,s)=>n+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 Nf=new DR;class RR{constructor(){Xe(this,"snapshots",[]);Xe(this,"maxSnapshots",120);Xe(this,"intervalId",null);Xe(this,"leakThresholdMB",50);Xe(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 n=this.getUsage();n&&(this.baselineUsedMB=n.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 n={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(n),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],n=this.snapshots[this.snapshots.length-1],s=(n.timestamp-e.timestamp)/1e3/60;return s<.1?null:(n.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 n=this.getGrowthRate();if(n!==null&&(console.log(`Growth Rate: ${n.toFixed(2)}MB/min`),n>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 n;return(n=e==null?void 0:e.info)!=null&&n.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 su=new RR;function yu(t,e,n,s,a,r){}function Mj(t,e){x.useRef(0),x.useEffect(()=>{},[t,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}const Jb=pt.PENDING_MESSAGES,OR=300*1e3;function Dj(){try{const t=localStorage.getItem(Jb);if(!t)return[];const e=JSON.parse(t),n=Date.now();return e.filter(s=>n-s.queuedAt<OR)}catch{return[]}}function Rj(t){try{t.length===0?localStorage.removeItem(Jb):localStorage.setItem(Jb,JSON.stringify(t))}catch{}}function Tf(t){const e=Dj();e.push({message:t,queuedAt:Date.now()}),Rj(e)}function LR(){var s;const t=Dj();if(t.length===0)return 0;let e=0;const n=[];for(const a of t)IR(a.message)?e++:n.push(a);if(Rj(n),e>0){const a=e===1?"queued message":"queued messages";(s=De.onToast)==null||s.call(De,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function Px(t){if(t.payload&&typeof t.payload=="object"){const e=t.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 IR(t){const e=Yp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const n=JSON.stringify(t),s=Px(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",s,"payload:",t.payload),s&&vs.captureSent(s,n),e.send(n),!0}catch{return!1}}function Bx(t){var n,s,a,r,i,c,d,f,h,m;const e=Yp();if(!e)return(n=Kk())==null||n(),t.type==="send_command"?(Tf(t),(s=De.onToast)==null||s.call(De,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=De.onToast)==null||a.call(De,"error","Not Connected","Connecting to server... Please try again in a moment."),!1;if(e.readyState!==WebSocket.OPEN)return e.readyState===WebSocket.CONNECTING?t.type==="send_command"?(Tf(t),(r=De.onToast)==null||r.call(De,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=De.onToast)==null||i.call(De,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Kk())==null||c(),t.type==="send_command"?(Tf(t),(d=De.onToast)==null||d.call(De,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=De.onToast)==null||f.call(De,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const b=JSON.stringify(t),y=Px(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",y,"payload:",t.payload),y&&vs.captureSent(y,b),e.send(b),!0}catch(b){return t.type==="send_command"?(Tf(t),(h=De.onToast)==null||h.call(De,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=De.onToast)==null||m.call(De,"error","Send Failed",`Failed to send message: ${b}`),!1}}const vu=new Set,PR=5e3;function Qk(t){if(!t.isDetached||!t.sessionId){vu.delete(t.id);return}vu.has(t.id)||(vu.add(t.id),Bx({type:"reattach_agent",payload:{agentId:t.id}}),setTimeout(()=>{vu.delete(t.id)},PR))}function BR(t){var e,n,s,a,r,i,c,d,f,h,m,b,y,w,C,N,k,j,S,T,D,E,I,O;switch(Xb.start(`ws:${t.type}`),t.type){case"agents_update":{const _=t.payload,M=_.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}))),U.setAgents(_),(e=De.onAgentsSync)==null||e.call(De,_),U.loadToolHistory();for(const R of _)Qk(R);break}case"agent_created":{const _=t.payload;console.log("[WebSocket] Agent created:",_),U.addAgent(_);const M=(n=window.__spawnModalAreaContext)==null?void 0:n.areaId;M&&(U.assignAgentToArea(_.id,M),window.__spawnModalAreaContext=null),U.selectAgent(_.id),(s=De.onAgentCreated)==null||s.call(De,_),(a=De.onSpawnSuccess)==null||a.call(De),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=De.onToast)==null||r.call(De,"success","Agent Deployed",`${_.name} is ready for commands`);break}case"agent_updated":{const _=t.payload,R=U.getState().agents.get(_.id),z=(R==null?void 0:R.status)!==_.status;console.log(`[Tide] Agent updated: ${_.name} (${_.id}) status=${_.status} (was ${R==null?void 0:R.status})${z?" ⚡ STATUS CHANGED":""}`),z&&console.log(`[Tide] 🔔 Status change for ${_.name}: ${R==null?void 0:R.status} → ${_.status}`),z&&(R==null?void 0:R.status)==="working"&&_.status==="idle"&&U.triggerHistoryRefresh(_.id);const $=R?R.position.x!==_.position.x||R.position.z!==_.position.z:!1;U.updateAgent(_),Qk(_),(i=De.onAgentUpdated)==null||i.call(De,_,$);break}case"agent_deleted":{const{id:_}=t.payload;vu.delete(_),U.removeAgent(_),(c=De.onAgentDeleted)==null||c.call(De,_);break}case"activity":{const _=t.payload;U.addActivity(_);break}case"event":{const _=t.payload;if(Uu.debug(`Event: ${_.type}`,{agentId:_.agentId,toolName:_.toolName},"ws:event"),_.type==="tool_start"&&_.toolName&&((d=De.onToolUse)==null||d.call(De,_.agentId,_.toolName,_.toolInput),U.addToolExecution(_.agentId,_.toolName,_.toolInput),_.toolInput)){const M=_.toolInput.file_path||_.toolInput.path;M&&(_.toolName==="Write"?U.addFileChange(_.agentId,"created",M):_.toolName==="Edit"?U.addFileChange(_.agentId,"modified",M):_.toolName==="Read"&&U.addFileChange(_.agentId,"read",M))}break}case"output":{const _=t.payload;Uu.debug(`Output: "${_.text.slice(0,80)}..."`,{agentId:_.agentId,isStreaming:_.isStreaming,length:_.text.length,hasSkillUpdate:!!_.skillUpdate,uuid:_.uuid,toolName:_.toolName},"ws:output"),U.addOutput(_.agentId,{text:_.text,isStreaming:_.isStreaming,timestamp:_.timestamp,isDelegation:_.isDelegation,skillUpdate:_.skillUpdate,subagentName:_.subagentName,uuid:_.uuid,toolName:_.toolName,toolInput:_.toolInput,toolOutput:_.toolOutput});break}case"context_stats":{const{agentId:_,stats:M}=t.payload;console.log(`[Tide] Received context stats for agent ${_}: ${M.usedPercent}% used`),U.updateAgentContextStats(_,M);break}case"context_update":{const{agentId:_,contextUsed:M,contextLimit:R}=t.payload;U.updateAgentContext(_,M,R);break}case"error":{const _=t.payload;console.error("[WebSocket] Error from server:",_.message),(f=De.onToast)==null||f.call(De,"error","Error",_.message),(h=De.onSpawnError)==null||h.call(De),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:_}=t.payload;console.log("[WebSocket] Directory not found:",_),(m=De.onDirectoryNotFound)==null||m.call(De,_),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(_));break}case"command_started":{const{agentId:_,command:M}=t.payload,R=M.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;U.addUserPromptToOutput(_,M);break}case"session_updated":{const{agentId:_}=t.payload;U.loadToolHistory(),U.triggerHistoryRefresh(_);const M=U.getState().agents.get(_);M&&U.updateAgent({...M});break}case"supervisor_report":{const _=t.payload;U.setSupervisorReport(_);break}case"narrative_update":{const{agentId:_,narrative:M}=t.payload;U.addNarrative(_,M);break}case"supervisor_status":{const _=t.payload;U.setSupervisorStatus(_);break}case"agent_supervisor_history":{const _=t.payload;U.setAgentSupervisorHistory(_);break}case"agent_analysis":{const{agentId:_,analysis:M}=t.payload;U.addAgentAnalysis(_,M);break}case"areas_update":{const _=t.payload;U.setAreasFromServer(_),(b=De.onAreasSync)==null||b.call(De);break}case"buildings_update":{const _=t.payload;U.setBuildingsFromServer(_);break}case"building_created":{const _=t.payload;U.addBuilding(_);break}case"building_updated":{const _=t.payload;U.updateBuildingFromServer(_),(y=De.onBuildingUpdated)==null||y.call(De,_);break}case"building_deleted":{const{id:_}=t.payload;U.removeBuildingFromServer(_);break}case"building_logs":{const{buildingId:_,logs:M}=t.payload;U.addBuildingLogs(_,M);break}case"pm2_logs_chunk":{const{buildingId:_,chunk:M}=t.payload;U.appendStreamingLogChunk(_,M);break}case"pm2_logs_streaming":{const{buildingId:_,streaming:M}=t.payload;U.setStreamingStatus(_,M);break}case"docker_logs_chunk":{const{buildingId:_,chunk:M}=t.payload;U.appendStreamingLogChunk(_,M);break}case"docker_logs_streaming":{const{buildingId:_,streaming:M}=t.payload;U.setStreamingStatus(_,M);break}case"docker_containers_list":{const{containers:_,composeProjects:M}=t.payload;console.log(`[WebSocket] Received ${_.length} containers, ${M.length} compose projects`),U.setDockerContainersList(_,M);break}case"boss_building_logs_chunk":{const{bossBuildingId:_,subordinateBuildingId:M,subordinateBuildingName:R,chunk:z,isError:$}=t.payload;U.appendBossStreamingLogChunk(_,M,R,z,$);break}case"boss_building_subordinates_updated":{const{bossBuildingId:_,subordinateBuildingIds:M}=t.payload;U.updateBuilding(_,{subordinateBuildingIds:M});break}case"permission_request":{const _=t.payload;U.addPermissionRequest(_);break}case"permission_resolved":{const{requestId:_,approved:M}=t.payload;U.resolvePermissionRequest(_,M);break}case"delegation_decision":{const _=t.payload;U.handleDelegationDecision(_),_.status==="sent"&&((w=De.onToast)==null||w.call(De,"info","Task Delegated",`Delegated to ${_.selectedAgentName}: ${_.reasoning.slice(0,80)}...`),_.bossId&&_.selectedAgentId&&((C=De.onDelegation)==null||C.call(De,_.bossId,_.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:_,subordinateIds:M}=t.payload;U.updateBossSubordinates(_,M);break}case"delegation_history":{const{bossId:_,decisions:M}=t.payload;U.setDelegationHistory(_,M);break}case"boss_spawned_agent":{const{agent:_,bossPosition:M}=t.payload;console.log("[WebSocket] Boss spawned agent:",_.name,"- walking to boss at",M),U.addAgent(_),(N=De.onAgentCreated)==null||N.call(De,_),Bx({type:"move_agent",payload:{agentId:_.id,position:M}}),(k=De.onToast)==null||k.call(De,"success","Agent Deployed",`${_.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:_,subordinateId:M,subordinateName:R,taskDescription:z}=t.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${_}: ${z.slice(0,50)}...`),U.handleAgentTaskStarted(_,M,R,z);break}case"agent_task_output":{const{bossId:_,subordinateId:M,output:R,isStreaming:z,timestamp:$,subagentName:W,toolName:L,toolInput:F,toolOutput:H}=t.payload;U.handleAgentTaskOutput(_,M,{text:R,isStreaming:z||!1,timestamp:$||Date.now(),subagentName:W,toolName:L,toolInput:F,toolOutput:H});break}case"agent_task_completed":{const{bossId:_,subordinateId:M,success:R}=t.payload;console.log(`[WebSocket] Agent task completed for boss ${_}, subordinate ${M}, success: ${R}`),U.handleAgentTaskCompleted(_,M,R);break}case"skills_update":{const _=t.payload;U.setSkillsFromServer(_);break}case"skill_created":{const _=t.payload;U.addSkillFromServer(_),console.log(`[WebSocket] Skill created: ${_.name}`);break}case"skill_updated":{const _=t.payload;U.updateSkillFromServer(_),console.log(`[WebSocket] Skill updated: ${_.name}`);break}case"skill_deleted":{const{id:_}=t.payload;U.removeSkillFromServer(_),console.log(`[WebSocket] Skill deleted: ${_}`);break}case"agent_skills":{const{agentId:_,skills:M}=t.payload;console.log(`[WebSocket] Agent ${_} has ${M.length} skills`);break}case"custom_agent_classes_update":{const _=t.payload;U.setCustomAgentClassesFromServer(_),console.log(`[WebSocket] Received ${_.length} custom agent classes`);const M=new Map;for(const R of _)M.set(R.id,R);(j=De.onCustomClassesSync)==null||j.call(De,M);break}case"custom_agent_class_created":{const _=t.payload;U.addCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class created: ${_.name}`),(S=De.onCustomClassesSync)==null||S.call(De,U.getState().customAgentClasses);break}case"custom_agent_class_updated":{const _=t.payload;U.updateCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class updated: ${_.name}`),(T=De.onCustomClassesSync)==null||T.call(De,U.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:_}=t.payload;U.removeCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class deleted: ${_}`),(D=De.onCustomClassesSync)==null||D.call(De,U.getState().customAgentClasses);break}case"global_usage":{const _=t.payload;console.log("[WebSocket] Global usage update:",_),U.setGlobalUsage(_);break}case"agent_notification":{const _=t.payload;console.log(`[WebSocket] Agent notification from ${_.agentName}: ${_.title}`),(E=De.onAgentNotification)==null||E.call(De,_);break}case"focus_agent":{const{agentId:_,openTerminal:M}=t.payload;if(!U.getState().agents.get(_)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${_}`);break}U.selectAgent(_),M&&U.setTerminalOpen(!0);const z=[0,80,220,500,1e3];for(const $ of z)window.setTimeout(()=>{window.focus()},$);break}case"exec_task_started":{const{taskId:_,agentId:M,agentName:R,command:z,cwd:$}=t.payload;console.log(`[WebSocket] Exec task started: ${_} for agent ${R}: ${z.slice(0,50)}...`),U.handleExecTaskStarted(_,M,R,z,$);break}case"exec_task_output":{const{taskId:_,agentId:M,output:R,isError:z}=t.payload;U.handleExecTaskOutput(_,M,R,z);break}case"exec_task_completed":{const{taskId:_,agentId:M,exitCode:R,success:z}=t.payload;console.log(`[WebSocket] Exec task completed: ${_} for agent ${M}, success: ${z}`),U.handleExecTaskCompleted(_,M,R,z);break}case"subagent_started":{const _=t.payload;console.log(`[WebSocket] Subagent started: ${_.name} (${_.id}) for agent ${_.parentAgentId}`),U.addSubagent(_),(I=De.onSubagentStarted)==null||I.call(De,_);break}case"subagent_output":{const{subagentId:_,parentAgentId:M,text:R,timestamp:z}=t.payload,$=R.indexOf(":");if($>0){const W=R.slice(0,$).trim(),L=R.slice($+1).trim();U.addSubagentActivity(_,M,{toolName:W,description:L,timestamp:z})}else R.startsWith("Using ")&&U.addSubagentActivity(_,M,{toolName:R.slice(6).trim(),description:"",timestamp:z});break}case"subagent_completed":{const{subagentId:_,parentAgentId:M,success:R,resultPreview:z,subagentName:$,durationMs:W,tokensUsed:L,toolUseCount:F}=t.payload;console.log(`[WebSocket] Subagent completed: ${_} for agent ${M}, success: ${R}`),(W||L||F)&&U.updateSubagentStats(_,M,{durationMs:W||0,tokensUsed:L||0,toolUseCount:F||0}),U.completeSubagent(_,M,R),(O=De.onSubagentCompleted)==null||O.call(De,_);const H=U.getSubagent(_)||U.getSubagentByToolUseId(_),V=$||(H==null?void 0:H.name)||_,G=R?"✅":"❌",B=W?` (${(W/1e3).toFixed(0)}s · ${((L||0)/1e3).toFixed(1)}K tokens · ${F||0} tools)`:"";U.addOutput(M,{text:`${G} Subagent ${V} ${R?"completed":"failed"}${B}`,isStreaming:!1,timestamp:Date.now(),subagentName:V,toolOutput:z});break}case"subagent_stream":{const{toolUseId:_,parentAgentId:M,entries:R}=t.payload;U.addSubagentStreamEntries(_,M,R);break}case"secrets_update":{const _=t.payload;U.setSecretsFromServer(_),console.log(`[WebSocket] Received ${_.length} secrets`);break}case"secret_created":{const _=t.payload;U.addSecretFromServer(_),console.log(`[WebSocket] Secret created: ${_.name}`);break}case"secret_updated":{const _=t.payload;U.updateSecretFromServer(_),console.log(`[WebSocket] Secret updated: ${_.name}`);break}case"secret_deleted":{const{id:_}=t.payload;U.removeSecretFromServer(_),console.log(`[WebSocket] Secret deleted: ${_}`);break}case"database_connection_result":{const{buildingId:_,connectionId:M,success:R,error:z,serverVersion:$}=t.payload;U.setConnectionStatus(_,M,{connected:R,error:z,serverVersion:$}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${M}`);break}case"databases_list":{const{buildingId:_,connectionId:M,databases:R}=t.payload;U.setDatabases(_,M,R),console.log(`[WebSocket] Received ${R.length} databases for ${M}`);break}case"tables_list":{const{buildingId:_,connectionId:M,database:R,tables:z}=t.payload;U.setTables(_,M,R,z),console.log(`[WebSocket] Received ${z.length} tables for ${R}`);break}case"table_schema":{const{buildingId:_,connectionId:M,database:R,table:z,columns:$,indexes:W,foreignKeys:L}=t.payload;U.setTableSchema(_,M,R,z,{columns:$,indexes:W||[],foreignKeys:L||[]}),console.log(`[WebSocket] Received schema for ${z}`);break}case"query_result":{const{buildingId:_,result:M}=t.payload;U.setQueryResult(_,M),console.log(`[WebSocket] Query ${M.status}: ${M.rowCount??M.affectedRows??0} rows in ${M.duration}ms`);break}case"silent_query_result":{const{buildingId:_,query:M,requestId:R,success:z,affectedRows:$,error:W}=t.payload;U.setSilentQueryResult(_,{query:M,requestId:R,success:z,affectedRows:$,error:W}),console.log(`[WebSocket] Silent query ${z?"succeeded":"failed"}: ${$??0} affected rows`);break}case"query_history_update":{const{buildingId:_,history:M}=t.payload;U.setQueryHistory(_,M),console.log(`[WebSocket] Received ${M.length} query history entries for ${_}`);break}}Xb.end(`ws:${t.type}`)}TR(()=>Hu());let Xk=!1;function Oj(){const t=Yp();t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Page unloading");const e=Nj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),NR()}function FR(){Xk||(window.addEventListener("beforeunload",Oj),Xk=!0)}function Lj(){Oj(),U.setConnected(!1),U.stopStatusPolling()}function zR(){Lj(),Qb(0),setTimeout(()=>Hu(),100)}function Hu(){FR();const t=Nj();t&&(clearTimeout(t),Tj(null));const e=Yp();if(AR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Gk()&&De.onReconnect&&De.onReconnect();return}Qb(Kb()+1),nu(!0);const n=Rx(),s=Ii(),a=6200;let r;if(n){const c=n.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{nu(!1),Jk();return}Vk(i),i.onopen=()=>{var d,f,h;const c=Gk();nu(!1),Qb(0),jR(),U.setConnected(!0),U.startStatusPolling(),U.clearAllPermissions(),c?((d=De.onToast)==null||d.call(De,"success","Reconnected","Connection restored - refreshing data..."),(f=De.onReconnect)==null||f.call(De)):(h=De.onToast)==null||h.call(De,"success","Connected","Connected to Tide Commander server"),CR(n,s),LR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=Px(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&vs.captureReceived(f,c.data),BR(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;nu(!1),Vk(null),U.setConnected(!1),U.stopStatusPolling();const c=Kb();c<Yk?((d=De.onToast)==null||d.call(De,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${Yk})`),Jk()):(f=De.onToast)==null||f.call(De,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{nu(!1)},U.setSendMessage(Bx)}function Jk(){const t=Kb(),e=Math.min(1e3*Math.pow(2,t-1),3e4);Tj(setTimeout(Hu,e))}function $R(t,e){const n={position:t,target:e};La(pt.CAMERA_STATE,n)}function UR(){return Na(pt.CAMERA_STATE,null)}function Aq(t,e,n){const s={posX:t,posZ:e,zoom:n};La(pt.CAMERA_STATE_2D,s)}function jq(){return Na(pt.CAMERA_STATE_2D,null)}function sc(){return{Authorization:`Bearer ${Ii()}`,"Content-Type":"application/json"}}async function HR(){const t=await fetch(`${Ea()}/api/workspaces`,{headers:sc()});if(!t.ok)throw new Error(`Failed to fetch workspaces: ${t.statusText}`);return t.json()}async function WR(t,e){const n=await fetch(`${Ea()}/api/workspaces`,{method:"POST",headers:sc(),body:JSON.stringify({name:t,areaIds:e})});if(!n.ok)throw new Error(`Failed to create workspace: ${n.statusText}`);return n.json()}async function Zk(t,e){const n=await fetch(`${Ea()}/api/workspaces/${t}`,{method:"PUT",headers:sc(),body:JSON.stringify(e)});if(!n.ok)throw new Error(`Failed to update workspace: ${n.statusText}`);return n.json()}async function qR(t){const e=await fetch(`${Ea()}/api/workspaces/${t}`,{method:"DELETE",headers:sc()});if(!e.ok)throw new Error(`Failed to delete workspace: ${e.statusText}`)}async function VR(){const t=await fetch(`${Ea()}/api/workspaces/active`,{headers:sc()});if(!t.ok)throw new Error(`Failed to get active workspace: ${t.statusText}`);return(await t.json()).activeWorkspaceId??null}async function eS(t){const e=await fetch(`${Ea()}/api/workspaces/active`,{method:"PUT",headers:sc(),body:JSON.stringify({workspaceId:t})});if(!e.ok)throw new Error(`Failed to set active workspace: ${e.statusText}`)}const Wu=new Set;let sr=null,xo=[],Ij=!1;const Zb=new Set;function Dg(t){Ij=t,Zb.forEach(e=>e(t))}const Pj="tide-commander-active-workspace";function tS(){return typeof window>"u"?null:localStorage.getItem(Pj)||null}function Rg(t){typeof window>"u"||localStorage.setItem(Pj,t||"")}function au(){Wu.forEach(t=>t())}function YR(){return sr}function Fx(t){return sr?t?sr.areaIds.includes(t):!1:!0}function Nq(t){return sr?sr.areaIds.includes(t):!0}function Bj(){const[,t]=x.useState(0);return x.useEffect(()=>{const e=()=>t(n=>n+1);return Wu.add(e),()=>{Wu.delete(e)}},[]),[sr,xo]}function GR(t){return Wu.add(t),()=>{Wu.delete(t)}}function KR(){const[t,e]=x.useState(Ij);return x.useEffect(()=>{const n=s=>e(s);return Zb.add(n),()=>{Zb.delete(n)}},[]),t}const Og=new Map,QR=Ce.memo(function(){const{t:e}=dt("common"),n=ur(),[s,a]=x.useState([]),[r,i]=x.useState(()=>tS()),[c,d]=x.useState(!1),[f,h]=x.useState(!1),[m,b]=x.useState(!0),[y,w]=x.useState(null),[C,N]=x.useState(""),[k,j]=x.useState([]),[S,T]=x.useState(!1),D=x.useRef(null);x.useEffect(()=>{let L=!1;return(async()=>{try{const F=tS(),[H,V]=await Promise.all([HR(),VR()]);if(L)return;const G=F&&H.some(B=>B.id===F)?F:V&&H.some(B=>B.id===V)?V:null;a(H),xo=H,i(G),Rg(G),sr=H.find(B=>B.id===G)??null,au()}catch(F){console.error("workspace error:",F)}finally{L||b(!1)}})(),()=>{L=!0}},[]),x.useEffect(()=>{if(!c&&!f)return;const L=F=>{D.current&&!D.current.contains(F.target)&&(d(!1),h(!1))};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[c,f]);const E=x.useMemo(()=>s.find(L=>L.id===r)??null,[s,r]),I=x.useCallback(async L=>{Dg(!0);const F=Date.now();if(r){const B=UR();B&&(Og.set(r,B),Zk(r,{cameraState:B}).then(K=>{a(ne=>{const q=ne.map(xe=>xe.id===r?K:xe);return xo=q,q})}).catch(K=>console.error("workspace error:",K)))}i(L),Rg(L),d(!1);const H=L?s.find(B=>B.id===L)??null:null;if(sr=H,xo=s,au(),L){const K=(H==null?void 0:H.cameraState)??Og.get(L);K&&($R(K.position,K.target),Og.set(L,K))}eS(L).catch(B=>console.error("workspace error:",B));const V=Date.now()-F,G=400;V<G?setTimeout(()=>Dg(!1),G-V):Dg(!1)},[r,s]),O=x.useMemo(()=>Array.from(n.values()).filter(L=>!L.archived),[n]),_=x.useCallback(async()=>{if(C.trim())try{const L=await WR(C.trim(),k),F=[...s,L];a(F),xo=F,au(),N(""),j([]),T(!1)}catch(L){console.error("workspace error:",L)}},[C,k,s]),M=x.useCallback(async()=>{if(!(!y||!C.trim()))try{const L=await Zk(y,{name:C.trim(),areaIds:k}),F=s.map(H=>H.id===y?L:H);a(F),xo=F,y===r&&(sr=L),au(),w(null),N(""),j([])}catch(L){console.error("workspace error:",L)}},[y,C,k,s,r]),R=x.useCallback(async L=>{try{await qR(L);const F=s.filter(H=>H.id!==L);a(F),xo=F,r===L&&(i(null),Rg(null),sr=null,await eS(null).catch(H=>console.error("workspace error:",H))),au()}catch(F){console.error("workspace error:",F)}},[s,r]),z=x.useCallback(L=>{w(L.id),N(L.name),j([...L.areaIds]),T(!1)},[]),$=x.useCallback(()=>{w(null),N(""),j([]),T(!0)},[]),W=x.useCallback(L=>{j(F=>F.includes(L)?F.filter(H=>H!==L):[...F,L])},[]);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:E?E.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:()=>I(null),children:e("agentBar.allWorkspaces",{defaultValue:"All"})}),s.map(L=>o.jsxs("button",{className:`workspace-switcher-option ${L.id===r?"active":""}`,onClick:()=>I(L.id),children:[L.name,o.jsx("span",{className:"workspace-switcher-option-count",children:L.areaIds.length})]},L.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(L=>o.jsx("div",{className:"workspace-switcher-manager-item",children:y===L.id?o.jsxs("div",{className:"workspace-switcher-editor",children:[o.jsx("input",{type:"text",value:C,onChange:F=>N(F.target.value),className:"workspace-switcher-input",placeholder:"Workspace name",autoFocus:!0,onKeyDown:F=>{F.key==="Enter"&&M(),F.key==="Escape"&&w(null)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[O.map(F=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(F.id),onChange:()=>W(F.id)}),o.jsx("span",{style:{color:F.color},children:F.name})]},F.id)),O.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:()=>w(null),children:"Cancel"})]})]}):o.jsxs("div",{className:"workspace-switcher-manager-row",children:[o.jsx("span",{className:"workspace-switcher-manager-name",children:L.name}),o.jsxs("span",{className:"workspace-switcher-manager-count",children:[L.areaIds.length," areas"]}),o.jsx("button",{className:"workspace-switcher-btn-edit",onClick:()=>z(L),title:"Edit",children:"✏"}),o.jsx("button",{className:"workspace-switcher-btn-delete",onClick:()=>R(L.id),title:"Delete",children:"🗑"})]})},L.id))}),S?o.jsxs("div",{className:"workspace-switcher-editor workspace-switcher-create-form",children:[o.jsx("input",{type:"text",value:C,onChange:L=>N(L.target.value),className:"workspace-switcher-input",placeholder:"New workspace name",autoFocus:!0,onKeyDown:L=>{L.key==="Enter"&&_(),L.key==="Escape"&&T(!1)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[O.map(L=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(L.id),onChange:()=>W(L.id)}),o.jsx("span",{style:{color:L.color},children:L.name})]},L.id)),O.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:_,children:"Create"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>T(!1),children:"Cancel"})]})]}):o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-add",onClick:$,children:["+ ",e("agentBar.newWorkspace",{defaultValue:"New Workspace"})]})]})]})}),vp="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 Gp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function Fj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function XR(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function qu(t){typeof window<"u"&&(window.__tidePersistedScene=t)}function Eu(t){typeof window<"u"&&(window.__tidePersistedCanvas=t)}function zj(t){typeof window<"u"&&(window.__tideWsConnected=t)}function JR(t){typeof window<"u"&&(window.__tideIsPageUnloading=t)}function ZR(){sessionStorage.setItem(vp,"true")}function _f(t){JR(!0),sessionStorage.removeItem(vp),Lj(),_R(),window.__tideScene&&(window.__tideScene=null);const e=Gp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),qu(null)):console.log("[App] No persistedScene to dispose"),Eu(null),zj(!1);const n=document.getElementById("battlefield");n&&n.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function eO(){var a,r;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(vp)==="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=Gp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}qu(null)}const n=document.getElementById("battlefield"),s=Fj();n&&n!==s&&n.remove(),sessionStorage.removeItem(vp)}function tO(){typeof window>"u"||(eO(),window.addEventListener("pageshow",t=>{t.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),_f(),window.location.reload())}),window.onunload=()=>_f(),window.onbeforeunload=t=>{_f()},window.addEventListener("pagehide",t=>{_f(`pagehide (persisted=${t.persisted})`)}))}tO();const nS={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},sS={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},aS={idleAnimation:"sit",workingAnimation:"sprint"},nO=0;function $j(){const t={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:nS,modelStyle:sS,animations:aS,fpsLimit:nO},e=Na(pt.CONFIG,null);if(e){const n=e.indicatorScale;return{characterScale:e.characterScale??t.characterScale,scale2d:e.scale2d??n??t.scale2d,scale3d:e.scale3d??n??t.scale3d,show2DTaskLabels:e.show2DTaskLabels??t.show2DTaskLabels,gridVisible:e.gridVisible??t.gridVisible,timeMode:e.timeMode??t.timeMode,terrain:{...nS,...e.terrain},modelStyle:{...sS,...e.modelStyle},animations:{...aS,...e.animations},fpsLimit:e.fpsLimit??t.fpsLimit}}return t}function sO(t){La(pt.CONFIG,t)}function aO(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function Uj(){console.log("[Tide HMR] Manual scene refresh triggered");const t=Gp();if(t){try{t.dispose()}catch(n){console.warn("[Tide HMR] Error disposing scene:",n)}qu(null)}Eu(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const n=e.getContext("webgl2")||e.getContext("webgl");if(n){const s=n.getExtension("WEBGL_lose_context");s&&s.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=Uj);function rO({canvasRef:t,selectionBoxRef:e,viewMode:n,sceneMountKey:s=0,showToast:a,showAgentNotification:r,toolboxModal:i,contextMenu:c,setHoveredAgentPopup:d,setBuildingPopup:f,getBuildingPopup:h,openBuildingModal:m,openPM2LogsModal:b,openBossLogsModal:y,openDatabasePanel:w,onSceneLoadingChange:C}){const N=x.useRef(null),k=x.useRef(null),j=x.useRef(null),S=x.useRef(null),T=x.useRef(null);return x.useEffect(()=>{if(n!=="3d"){C==null||C(!1);return}if(!t.current||!e.current)return;let D=!1;C==null||C(!0);const E=Gp(),O=Fj()===t.current;function _(){var R,z,$,W,L,F,H,V;(R=N.current)==null||R.setOnToast(a),(z=N.current)==null||z.setOnBuildingClick((G,B)=>{U.selectBuilding(G);const K=U.getState().buildings.get(G);(K==null?void 0:K.type)==="folder"&&K.folderPath?U.openFileExplorer(K.folderPath):(K==null?void 0:K.type)==="server"||(K==null?void 0:K.type)==="boss"||(K==null?void 0:K.type)==="database"?(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{f({buildingId:G,screenPos:B,fromClick:!0}),k.current=null},150)):m(G)}),($=N.current)==null||$.setOnContextMenu((G,B,K)=>{c.open(G,B,K)}),(W=N.current)==null||W.setOnAgentHover(()=>{}),(L=N.current)==null||L.setOnBuildingHover((G,B)=>{const K=h();if(G&&B){const ne=U.getState().buildings.get(G);((ne==null?void 0:ne.type)==="server"||(ne==null?void 0:ne.type)==="boss"||(ne==null?void 0:ne.type)==="database")&&!(K!=null&&K.fromClick)&&f({buildingId:G,screenPos:B,fromClick:!1})}else K!=null&&K.fromClick||f(null)}),(F=N.current)==null||F.setOnGroundClick(()=>{f(null)}),(H=N.current)==null||H.setOnAreaDoubleClick(G=>{U.selectArea(G),i.open()}),(V=N.current)==null||V.setOnBuildingDoubleClick(G=>{var K;k.current&&(clearTimeout(k.current),k.current=null),f(null);const B=U.getState().buildings.get(G);(B==null?void 0:B.type)==="server"&&((K=B.pm2)!=null&&K.enabled)?b==null||b(G):(B==null?void 0:B.type)==="boss"?y==null||y(G):(B==null?void 0:B.type)==="database"?w==null||w(G):(B==null?void 0:B.type)==="folder"&&B.folderPath?U.openFileExplorer(B.folderPath):m(G)})}if(E)try{N.current=E,O?(console.log("[Tide] Reusing existing scene (StrictMode remount)"),E.ensureRenderLoopRunning()):(console.log("[Tide] Reattaching persisted scene to new canvas"),E.reattach(t.current,e.current),Eu(t.current));const R=U.getState();E.syncAreas(),E.syncBuildings(),R.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",R.agents.size),E.syncAgents(Array.from(R.agents.values()))),_()}catch(R){console.error("[Tide] Failed to reattach persisted 3D scene:",R),C==null||C(!1)}finally{S.current=requestAnimationFrame(()=>{T.current=requestAnimationFrame(()=>{C==null||C(!1),T.current=null}),S.current=null})}else{const R=t.current,z=e.current,$=async()=>{if(D){console.log("[Tide] Effect cleaned up before scene init, skipping"),C==null||C(!1);return}if(!R.isConnected||!z.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),C==null||C(!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),ZR();try{const{SceneManager:W}=await vt(async()=>{const{SceneManager:H}=await import("./SceneManager-BgjRQCpO.js");return{SceneManager:H}},__vite__mapDeps([6,4,3,1]));if(D){C==null||C(!1);return}const L=new W(R,z);N.current=L,qu(L),Eu(R);const F=$j();L.setCharacterScale(F.characterScale),L.setScale3D(F.scale3d),L.setGridVisible(F.gridVisible),L.setTimeMode(F.timeMode),L.setTerrainConfig(F.terrain),L.setFloorStyle(F.terrain.floorStyle,!0),L.setAgentModelStyle(F.modelStyle),L.setIdleAnimation(F.animations.idleAnimation),L.setWorkingAnimation(F.animations.workingAnimation),L.setFpsLimit(F.fpsLimit),L.syncAreas(),L.syncBuildings(),L.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const H=U.getState();H.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",H.customAgentClasses.size),L.setCustomAgentClasses(H.customAgentClasses)),H.agents.size>0&&(console.log("[Tide] Syncing agents from store:",H.agents.size),L.syncAgents(Array.from(H.agents.values()))),L.upgradeAgentModels()}).catch(H=>{console.warn("[Tide] Some models failed to load, using fallback:",H)}).finally(()=>{C==null||C(!1)}),_()}catch(W){console.error("[Tide] Failed to initialize 3D scene:",W),C==null||C(!1)}};j.current=requestAnimationFrame(()=>void $())}Ej({onAgentCreated:R=>{var z,$,W;(z=N.current)==null||z.addAgent(R),($=N.current)==null||$.refreshSelectionVisuals(),(W=window.__spawnModalSuccess)==null||W.call(window)},onAgentUpdated:(R,z)=>{var W;const $=U.getState().agents.get(R.id)||R;(W=N.current)==null||W.updateAgent($,z)},onAgentDeleted:R=>{var z;(z=N.current)==null||z.removeAgent(R)},onAgentsSync:R=>{var $;const z=Array.from(U.getState().agents.values());($=N.current)==null||$.syncAgents(z)},onAreasSync:()=>{var z,$;(z=N.current)==null||z.syncAreas();const R=Array.from(U.getState().agents.values());($=N.current)==null||$.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 z;(z=window.__spawnModalDirNotFound)==null||z.call(window,R)},onToolUse:(R,z,$)=>{var W;(W=N.current)==null||W.showToolBubble(R,z,$)},onDelegation:(R,z)=>{var $;($=N.current)==null||$.showDelegationEffect(R,z)},onCustomClassesSync:R=>{var z,$;(z=N.current)==null||z.setCustomAgentClasses(R),($=N.current)==null||$.upgradeAgentModels()},onBuildingUpdated:R=>{var z;(z=N.current)==null||z.updateBuilding(R)},onSubagentStarted:R=>{var z;(z=N.current)==null||z.addSubagentEffect(R.id,R.parentAgentId,R.name,R.subagentType)},onSubagentCompleted:R=>{var W;const z=U.getSubagent(R)||U.getSubagentByToolUseId(R),$=(z==null?void 0:z.id)||R;(W=N.current)==null||W.completeSubagentEffect($),setTimeout(()=>{var L;(L=N.current)==null||L.removeSubagentEffect($)},3e4)}});const M=GR(()=>{if(N.current){N.current.syncAreas(),N.current.syncBuildings();const R=Array.from(U.getState().agents.values());N.current.syncAgents(R)}});return()=>{M(),D=!0,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),U.getState().viewMode!=="3d"&&aO()&&N.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),ER(),N.current.dispose(),N.current=null,qu(null),Eu(null))}},[n,s]),N}function iO({showToast:t,showAgentNotification:e}){x.useEffect(()=>{Ej({onToast:t,onReconnect:()=>{U.triggerReconnect()},onAgentNotification:a=>{e(a)}}),XR()||(Hu(),zj(!0)),wR();let n;SR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&jj(a.agentId)}).then(a=>{n=a});const s=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>Hu(),100)};return window.addEventListener("tideAppResume",s),()=>{window.removeEventListener("tideAppResume",s),n==null||n()}},[t,e])}function oO(t){x.useEffect(()=>{let e="",n="",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,w)=>(y<<5)-y+w.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 U.subscribe(()=>{var b;const r=U.getState(),i=Array.from(r.selectedAgentIds).sort().join(","),c=Array.from(r.selectedBuildingIds).sort().join(","),d=i!==e,f=c!==n,{newVersion:h,changed:m}=a(r.agents);(d||f||m)&&(e=i,n=c,s=h,(b=t.current)==null||b.refreshSelectionVisuals())})},[t])}function lO(t){x.useEffect(()=>{var s;(s=t.current)==null||s.syncAreas();let e=0,n=0;return U.subscribe(()=>{var c,d;const r=U.getState().areas;if(r.size!==e){e=r.size,n=Date.now(),(c=t.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!==n&&(n=i,(d=t.current)==null||d.syncAreas())})},[t])}function cO(t){x.useEffect(()=>{var s;(s=t.current)==null||s.syncBuildings();let e=0,n=0;return U.subscribe(()=>{var c,d;const r=U.getState().buildings;if(r.size!==e){e=r.size,n=Date.now(),(c=t.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!==n&&(n=i,(d=t.current)==null||d.syncBuildings())})},[t])}function uO(t,e){x.useEffect(()=>{var n;(n=t.current)==null||n.highlightArea(e)},[t,e])}function dO(t,e){x.useEffect(()=>{var n;(n=t.current)==null||n.setPowerSaving(e)},[t,e])}function Pt(t,e,n,s,a={},r="global"){return{id:t,name:e,description:n,key:s,modifiers:a,enabled:!0,context:r}}const Lg=[Pt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Pt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Pt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Pt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Pt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Pt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Pt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Pt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Pt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Pt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Pt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Pt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Pt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Pt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Pt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Pt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Pt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Pt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Pt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Pt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Pt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Pt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Pt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Pt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Pt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Pt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Pt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Pt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Pt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Pt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Pt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Pt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Pt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Pt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Pt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Pt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Pt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Pt("clear-context","Clear Context","Clear context of the selected agent","c",{alt:!0,shift:!0}),Pt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Pt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Pt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Pt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Pt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Pt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Pt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Pt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Pt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Pt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function Tn(t,e){if(!e||!e.enabled)return!1;const{ctrl:n,alt:s,shift:a}=e.modifiers,r=n?t.ctrlKey||t.metaKey:!t.ctrlKey&&!t.metaKey,i=s?t.altKey:!t.altKey,c=a?t.shiftKey:!t.shiftKey;let d;if(n?d=(t.ctrlKey||t.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 t.code===m}if(f.length===1&&/^[0-9]$/.test(f)){const m=`Digit${f}`;return t.code===m}return f==="Space"||f===" "?t.code==="Space":t.key===f}function Tq(t){const e=[];if(t.modifiers.ctrl){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌘":"Ctrl")}if(t.modifiers.alt){const s=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(s?"⌥":"Alt")}t.modifiers.shift&&e.push("Shift"),t.modifiers.meta&&e.push("⌘");let n=t.key;return n===" "?n="Space":n.length===1&&(n=n.toUpperCase()),e.push(n),e.join("+")}function _q(t,e,n,s){return t.filter(a=>{if(a.id===n||!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 fO({sceneRef:t,spawnModal:e,commanderModal:n,explorerModal:s,spotlightModal:a,deleteConfirmModal:r,onRequestBuildingDelete:i,onOpenDatabasePanel:c,onCloseDatabasePanel:d,databasePanelOpen:f}){x.useEffect(()=>{const h=m=>{var R,z,$,W;const b=U.getShortcuts(),y=m.target,w=y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true"||!!y.closest(".cm-editor"),C=b.find(L=>L.id==="deselect-all");if(Tn(m,C)){if(y.closest(".guake-bottom-terminal-embed"))return;if(ep()){m.preventDefault();return}const L=U.getState();if(L.activeTool==="rectangle"||L.activeTool==="circle"){(R=t.current)==null||R.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():L.terminalOpen?(U.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(U.deselectAll(),(z=t.current)==null||z.refreshSelectionVisuals())}for(let L=1;L<=9;L++){const F=b.find(H=>H.id===`select-agent-${L}`);if(Tn(m,F)){m.preventDefault();const H=U.getState(),V=L-1,G=Array.from(H.agents.keys());V<G.length&&(U.selectAgent(G[V]),($=t.current)==null||$.refreshSelectionVisuals());return}}const N=b.find(L=>L.id==="spawn-agent");if(Tn(m,N)){m.preventDefault(),e.open();return}const k=b.find(L=>L.id==="toggle-commander-tab");if(Tn(m,k)&&!w){m.preventDefault(),n.toggle();return}const j=b.find(L=>L.id==="toggle-commander");if(Tn(m,j)){m.preventDefault(),n.toggle();return}const S=b.find(L=>L.id==="toggle-file-explorer");if(Tn(m,S)){m.preventDefault();const L=U.getState();if(s.isOpen||L.explorerFolderPath!==null||L.explorerAreaId!==null)s.close(),U.closeFileExplorer();else{const H=U.getLastExplorerState();if((H==null?void 0:H.type)==="folder")U.openFileExplorer(H.path);else if((H==null?void 0:H.type)==="area")if(L.areas.has(H.areaId))s.open(H.areaId);else{const V=Array.from(L.areas.values()).filter(G=>G.directories&&G.directories.length>0);V.length>0&&s.open(V[0].id)}else{const V=Array.from(L.areas.values()).filter(G=>G.directories&&G.directories.length>0);V.length>0&&s.open(V[0].id)}}return}if(m.altKey&&!m.ctrlKey&&!m.shiftKey&&!m.metaKey&&m.code==="KeyD"){if(m.preventDefault(),m.stopPropagation(),f){d();return}const L=localStorage.getItem("tide-commander-last-database-building"),F=U.getState();if(L){const H=F.buildings.get(L);if((H==null?void 0:H.type)==="database"){c(L);return}}for(const[H,V]of F.buildings)if(V.type==="database"){c(H);return}return}const T=b.find(L=>L.id==="toggle-spotlight");if(Tn(m,T)||m.altKey&&!m.ctrlKey&&!m.metaKey&&m.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:T,altKey:m.altKey,code:m.code}),m.preventDefault(),a.toggle();return}const D=b.find(L=>L.id==="toggle-2d-view");if(Tn(m,D)){m.preventDefault();const L=U.getState().viewMode,F=L==="3d"?"2d":L==="2d"?"dashboard":"3d";U.setViewMode(F);return}const E=b.find(L=>L.id==="clear-context");if(Tn(m,E)){m.preventDefault();const L=U.getState(),F=L.selectedAgentIds.size===1?Array.from(L.selectedAgentIds)[0]:null;F&&U.clearContext(F);return}const I=b.find(L=>L.id==="next-working-agent"),O=b.find(L=>L.id==="prev-working-agent");if((Tn(m,I)||Tn(m,O))&&!w){const L=U.getState();if(L.terminalOpen)return;const F=Array.from(L.agents.values());let H=F.filter(K=>L.agentsWithUnseenOutput.has(K.id));if(H.length===0&&(H=F.filter(K=>K.status==="working")),H.length===0)return;m.preventDefault();const V=L.selectedAgentIds.size===1?Array.from(L.selectedAgentIds)[0]:null,G=V?H.findIndex(K=>K.id===V):-1;let B;Tn(m,I)?B=G===-1?0:(G+1)%H.length:B=G===-1?H.length-1:(G-1+H.length)%H.length,U.selectAgent(H[B].id),(W=t.current)==null||W.refreshSelectionVisuals();return}const _=b.find(L=>L.id==="delete-selected"),M=b.find(L=>L.id==="delete-selected-backspace");if((Tn(m,_)||Tn(m,M))&&!w){const L=U.getState();if(L.selectedAgentIds.size>0){m.preventDefault(),r.open();return}if(L.selectedBuildingIds.size>0){m.preventDefault(),i();return}return}};return document.addEventListener("keydown",h,!0),()=>document.removeEventListener("keydown",h,!0)},[t,e,n,s,a,r,i,c,d,f])}function pO(){const[t,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()&&(ep()||(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()?ep()?a=Date.now():(c=window.__tideSetBackNavModal)==null||c.call(window,!0):(ep(),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:t,setShowBackNavModal:e,handleLeave:()=>{e(!1);const s=window.__tideHistoryDepth??2;window.history.go(-(s+1))}}}const Ig="agent-order-change";function hO(t){const e=x.useMemo(()=>new Set(t.map(d=>d.id)),[t]),[n,s]=x.useState(()=>Na(pt.AGENT_ORDER,[]));x.useEffect(()=>{const d=f=>{s(f.detail)};return window.addEventListener(Ig,d),()=>{window.removeEventListener(Ig,d)}},[]);const a=x.useMemo(()=>{const d=n.filter(b=>e.has(b)),f=t.filter(b=>!d.includes(b.id)).map(b=>b.id),h=[...d,...f],m=new Map(t.map(b=>[b.id,b]));return h.map(b=>m.get(b)).filter(b=>b!==void 0)},[t,n,e]),r=x.useCallback(d=>{s(d),La(pt.AGENT_ORDER,d),window.dispatchEvent(new CustomEvent(Ig,{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([]),La(pt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const d=n.filter(f=>e.has(f));d.length!==n.length&&r(d)},[e,n,r]),{orderedAgents:a,moveAgent:i,resetOrder:c}}function Ta(t){const e=x.useRef(null),n=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(),t()),e.current=null},[t]);return{handleMouseDown:n,handleClick:s}}const mO=3e4;function gO(){const t=x.useRef(null);x.useEffect(()=>{const e=async()=>{var i,c;const n=U.getState(),s=new Map,a=new Map;for(const[d,f]of n.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 Bt(Rt(`/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 w=U.getState().buildings.get(y);w&&w.gitChangesCount!==b&&U.updateBuildingLocal(y,{gitChangesCount:b})}}catch{}const r=new Map;for(const[d,f]of n.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 Bt(Rt(`/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 w=U.getState().areas.get(b);if(!w)continue;const C=w.directoryGitCounts?[...w.directoryGitCounts]:new Array(w.directories.length).fill(0);let N=!1;for(const{dirIndex:k,count:j}of y)C[k]!==j&&(C[k]=j,N=!0);N&&U.updateAreaLocal(b,{directoryGitCounts:C})}}catch{}};return e(),t.current=setInterval(e,mO),()=>{t.current&&(clearInterval(t.current),t.current=null)}},[])}const Pg={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:"",vibrationIntensity:1,tabTitle:""},rS=90,Bg=["simple","chat","advanced"],iS=55,oS=20,lS=95,bO=200,xO=12e4,yO=5,la=new Map;function vO(t){const e=la.get(t);e&&(la.delete(t),la.set(t,e))}function wO(){for(;la.size>yO;){const t=la.keys().next().value;if(t!==void 0)la.delete(t);else break}}function Hj(t){la.delete(t)}function kO(t){return t.trim().replace(/\r\n/g,`
43
43
  `)}function ex(t,e){return`${t}:${kO(e)}`}function cS(t,e,n,s){if(t.uuid&&e.has(t.uuid))return!1;const a=t.isUserPrompt?"user":"assistant",r=ex(a,t.text),i=t.timestamp||0,c=n.get(r);return c!==void 0&&Math.abs(i-c)<=xO?!1:i>s}function Wj({selectedAgentId:t,hasSessionId:e,reconnectCount:n,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),[w,C]=x.useState(!1),[N,k]=x.useState(!1),[j,S]=x.useState(0),T=x.useRef(!0),D=x.useRef(0),E=x.useRef(0),I=x.useRef(!1),O=x.useRef(!1),_=x.useRef(null),M=x.useRef(!1),R=x.useRef(null),z=x.useRef(null);x.useEffect(()=>(T.current=!0,()=>{T.current=!1}),[]),x.useEffect(()=>{if(!t||!e){c([]),E.current=0,k(!1),O.current=!1,S(0),f(!1),m(!1),y(Z=>Z+1),M.current=!1,R.current=null;return}const V=`${t}:${n}:${s}`;if(R.current===V)return;const G=_.current!==null&&_.current!==t,B=n>0,K=G||B,ne=!G&&!M.current&&e;_.current=t,M.current=e,R.current=V;let q;if(B){const Z=U.getOutputs(t);Z.length>0&&(q=Z.map(ce=>({...ce})))}z.current&&(clearTimeout(z.current),z.current=null),B&&la.delete(t),D.current+=1;const xe=D.current;m(!0);const Ae=la.get(t);Ae?(vO(t),c(Ae.messages),E.current=Ae.messages.length,k(Ae.hasMore),O.current=Ae.hasMore,S(Ae.totalCount)):(c([]),E.current=0,k(!1),O.current=!1,S(0)),ne||(z.current=setTimeout(()=>{f(!0)},150)),Bt(Rt(`/api/agents/${t}/history?limit=${rS}&offset=0`)).then(Z=>{if(!Z.ok)throw new Error(`HTTP ${Z.status}: ${Z.statusText}`);return Z.json()}).then(Z=>{if(xe!==D.current)return;const ce=Array.isArray(Z.messages)?Z.messages:[],me=Array.isArray(Z.subagents)?Z.subagents:[];c(ce),E.current=ce.length;const ee=Z.hasMore||!1;if(k(ee),O.current=ee,S(Z.totalCount||0),me.length>0&&U.hydrateSubagentsFromHistory(t,me),la.set(t,{messages:ce,hasMore:ee,totalCount:Z.totalCount||0}),wO(),q&&q.length>0){const re=ce.length>0?Math.max(...ce.map(ge=>ge.timestamp?new Date(ge.timestamp).getTime():0)):0,We=new Set(ce.map(ge=>ge.uuid).filter(ge=>typeof ge=="string"&&ge.length>0)),ze=new Map;for(const ge of ce){if(ge.type!=="user"&&ge.type!=="assistant")continue;const Te=ex(ge.type,ge.content),qe=ge.timestamp?new Date(ge.timestamp).getTime():0,it=ze.get(Te)??0;qe>it&&ze.set(Te,qe)}const Pe=q.filter(ge=>cS(ge,We,ze,re));U.clearOutputs(t);for(const ge of Pe)U.addOutput(t,ge)}else if(ce.length>0){const re=Math.max(...ce.map(Te=>Te.timestamp?new Date(Te.timestamp).getTime():0)),We=new Set(ce.map(Te=>Te.uuid).filter(Te=>typeof Te=="string"&&Te.length>0)),ze=new Map;for(const Te of ce){if(Te.type!=="user"&&Te.type!=="assistant")continue;const qe=ex(Te.type,Te.content),it=Te.timestamp?new Date(Te.timestamp).getTime():0,he=ze.get(qe)??0;it>he&&ze.set(qe,it)}const Pe=U.getOutputs(t),ge=Pe.filter(Te=>{const qe=cS(Te,We,ze,re);return qe||console.warn(`[HISTORY-DEDUP] Removing live output: uuid=${Te.uuid||"none"} ts=${Te.timestamp} lastHistTs=${re} text="${Te.text.slice(0,80)}"`),qe});if(Pe.length!==ge.length){console.warn(`[HISTORY-DEDUP] Cleared ${Pe.length-ge.length}/${Pe.length} overlapping outputs for agent ${t}`),U.clearOutputs(t);for(const Te of ge)U.addOutput(t,Te)}}if(!a.get(t)){for(let re=ce.length-1;re>=0;re--)if(ce[re].type==="user"){U.setLastPrompt(t,ce[re].content);break}}}).catch(Z=>{if(console.error("Failed to load history:",Z),c([]),E.current=0,k(!1),O.current=!1,S(0),K&&q&&q.length>0){U.clearOutputs(t);for(const ce of q)U.addOutput(t,ce)}}).finally(()=>{T.current&&xe===D.current&&(z.current&&(clearTimeout(z.current),z.current=null),f(!1),m(!1),y(Z=>Z+1))})},[t,e,n,s]);const $=x.useCallback(async()=>{if(!t||I.current||!O.current)return;const V=r.current;if(!V){console.warn("loadMoreHistory: outputScrollRef not connected");return}const G=V.scrollHeight-V.scrollTop;I.current=!0,C(!0);const B=E.current;try{const ne=await(await Bt(Rt(`/api/agents/${t}/history?limit=${rS}&offset=${B}`))).json(),q=Array.isArray(ne.subagents)?ne.subagents:[];if(q.length>0&&U.hydrateSubagentsFromHistory(t,q),ne.messages&&ne.messages.length>0){if(!T.current)return;c(Ae=>{const Z=[...ne.messages,...Ae];return E.current=Z.length,Z});const xe=ne.hasMore||!1;O.current=xe,k(xe),requestAnimationFrame(()=>{requestAnimationFrame(()=>{T.current&&(r.current&&(r.current.scrollTop=r.current.scrollHeight-G),I.current=!1,C(!1))})})}else{if(!T.current)return;I.current=!1,C(!1)}}catch(K){if(console.error("Failed to load more history:",K),!T.current)return;I.current=!1,C(!1)}},[t,r]),W=x.useCallback(V=>{if(!r.current||V.current)return;const{scrollTop:G}=r.current;!I.current&&O.current&&G<bO&&$()},[$,r]),L=x.useCallback(()=>{c([]),E.current=0,t&&la.delete(t)},[t]),F=x.useRef(!1),H=x.useCallback(async()=>{var V,G;if(!(!t||!O.current)&&!(I.current||F.current)){F.current=!0,I.current=!0,C(!0);try{const K=await(await Bt(Rt(`/api/agents/${t}/history?limit=100000&offset=0`))).json();if(!T.current)return;const ne=Array.isArray(K.subagents)?K.subagents:[];ne.length>0&&U.hydrateSubagentsFromHistory(t,ne),K.messages&&K.messages.length>0&&(c(K.messages),E.current=K.messages.length),O.current=!1,k(!1),S(K.totalCount||((V=K.messages)==null?void 0:V.length)||0),la.set(t,{messages:K.messages||[],hasMore:!1,totalCount:K.totalCount||((G=K.messages)==null?void 0:G.length)||0})}catch(B){console.error("Failed to load all history:",B)}finally{T.current&&(I.current=!1,F.current=!1,C(!1))}}},[t]);return{history:i,loadingHistory:d,fetchingHistory:h,historyLoadVersion:b,loadingMore:w,hasMore:N,totalCount:j,isMountedRef:T,loadMoreHistory:$,loadAllHistory:H,allLoaded:!N,handleScroll:W,clearHistory:L,hasCachedHistory:x.useCallback(V=>la.has(V),[])}}function ru(...t){}function SO(t){return(t.tokensUsed??0)===0&&(t.contextUsed??0)===0&&!t.contextStats&&!t.sessionId&&!t.currentTask&&!t.lastAssignedTask}function uS(t,e){var r,i;if(!t||SO(e))return e;const n=((r=t.contextStats)==null?void 0:r.lastUpdated)??0,s=((i=e.contextStats)==null?void 0:i.lastUpdated)??0;return n>0&&n>s?{...e,contextUsed:t.contextUsed,contextLimit:t.contextLimit,contextStats:t.contextStats}:e}function CO(t,e,n,s,a){return{setAgents(r){const i=new Map,c=t().agents;for(const f of r){const h=c.get(f.id);i.set(f.id,uS(h,f)),(f.class==="boss"||f.isBoss)&&ru("[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)}),n()},addAgent(r){e(i=>{const c=new Map(i.agents);c.set(r.id,r),i.agents=c}),n()},updateAgent(r){var h;const c=t().agents.get(r.id),d=(c==null?void 0:c.status)!==r.status;d&&ru(`[Store] Agent ${r.name} status update: ${c==null?void 0:c.status} → ${r.status}`);let f=!1;e(m=>{const b=new Map(m.agents);b.set(r.id,uS(c,r)),m.agents=b,d&&(c==null?void 0:c.status)==="working"&&r.status==="idle"&&(m.terminalOpen&&m.selectedAgentIds.has(r.id)||(m.agentsWithUnseenOutput=new Set(m.agentsWithUnseenOutput),m.agentsWithUnseenOutput.add(r.id),ru(`[Store] Agent ${r.name} completed work - marked as unseen`),f=!0))}),f&&a&&a(),n(),d&&ru(`[Store] Agent ${r.name} status now in store: ${(h=t().agents.get(r.id))==null?void 0:h.status}`)},updateAgentContextStats(r,i){const d=t().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}),n())},updateAgentContext(r,i,c){const f=t().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),w=f.contextStats?{...f.contextStats,totalTokens:i,contextWindow:h,usedPercent:m,lastUpdated:Date.now()}:void 0;y.set(r,{...f,contextUsed:i,contextLimit:h,contextStats:w}),b.agents=y}),n()}},removeAgent(r){const i=t().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.supervisor.narratives.delete(r),c.supervisor.agentHistories.delete(r),c.supervisor.historyFetchedForAgents.delete(r),c.subagents.delete(r)}),Hj(r),i&&a&&a(),n()},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)),c.currentSnapshot=null}),i&&a&&a(),n()},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(),n()},selectMultiple(r){e(i=>{i.selectedAgentIds=new Set(r)}),n()},deselectAll(){e(r=>{r.selectedAgentIds=new Set}),n()},spawnAgent(r,i,c,d,f,h,m,b,y,w,C,N,k){ru("[Store] spawnAgent called with:",{name:r,agentClass:i,cwd:c,position:d,sessionId:f,useChrome:h,permissionMode:m,initialSkillIds:b,provider:y,codexConfig:w,codexModel:C,model:N,customInstructions:k?`${k.length} chars`:void 0});const j=d?{x:d.x,y:0,z:d.z}:void 0,S={type:"spawn_agent",payload:{name:r,class:i,cwd:c,position:j,sessionId:f,useChrome:h,permissionMode:m,initialSkillIds:b,provider:y,codexConfig:w,codexModel:C,model:N,customInstructions:k}},T=s();if(!T){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}T(S)},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()})}),n(),(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=t().agents.get(r);d&&(e(f=>{const h={...d,position:i},m=new Map(f.agents);m.set(r,h),f.agents=m}),n())},moveAgent(r,i){var f;const d=t().agents.get(r);d&&(e(h=>{const m={...d,position:i},b=new Map(h.agents);b.set(r,m),h.agents=b}),n()),(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,currentTool:void 0,lastAssignedTask:void 0,lastAssignedTaskTime:void 0,sessionId:void 0,tokensUsed:0,contextUsed:0,contextStats:void 0},w=new Map(c.agents);w.set(r,y),c.agents=w}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,w]of m)w.parentAgentId===r&&(m.delete(y),b=!0);b&&(c.subagents=m)}),n()},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=t().agents.get(r);d&&(e(h=>{const m={...d,name:i},b=new Map(h.agents);b.set(r,m),h.agents=b}),n()),(f=s())==null||f({type:"rename_agent",payload:{agentId:r,name:i}})},updateAgentProperties(r,i){var f;const d=t().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.provider!==void 0&&(m.provider=i.provider),i.codexConfig!==void 0&&(m.codexConfig=i.codexConfig),i.codexModel!==void 0&&(m.codexModel=i.codexModel),i.useChrome!==void 0&&(m.useChrome=i.useChrome),i.cwd!==void 0&&(m.cwd=i.cwd);const b=new Map(h.agents);b.set(r,m),h.agents=b}),n()),(f=s())==null||f({type:"update_agent_properties",payload:{agentId:r,updates:i}})},getTotalTokens(){let r=0;for(const i of t().agents.values())r+=i.tokensUsed;return r},getSelectedAgents(){const r=t(),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()}),n()},addToolExecution(r,i,c){const f=t().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()}),n()},addFileChange(r,i,c){const f=t().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()}),n()},async loadToolHistory(){try{const i=await(await Bt(Rt("/api/agents/tool-history?limit=100"))).json();e(c=>{i.toolExecutions&&(c.toolExecutions=i.toolExecutions),i.fileChanges&&(c.fileChanges=i.fileChanges)}),n()}catch(r){console.error("[Store] Failed to load tool history:",r)}}}}const dS=200;function fS(t){return t.length<=dS?t:t.slice(-dS)}function AO(t,e,n,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=fS([...d,r]);Uu.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}),n()},clearOutputs(a){e(r=>{const i=new Map(r.agentOutputs);i.delete(a),r.agentOutputs=i}),n()},getOutputs(a){return t().agentOutputs.get(a)||[]},addUserPromptToOutput(a,r){this.addOutput(a,{text:r,isStreaming:!1,timestamp:Date.now(),isUserPrompt:!0})},getLastPrompt(a){return t().lastPrompts.get(a)},setLastPrompt(a,r){e(i=>{i.lastPrompts.set(a,{text:r,timestamp:Date.now()})}),n()},preserveOutputs(){const a=t(),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=fS(c),e(d=>{const f=new Map(d.agentOutputs);f.set(a,c),d.agentOutputs=f}),n(),c}}}function jO(t,e,n,s){return{setSupervisorReport(a){e(r=>{r.supervisor.lastReport=a,r.supervisor.lastReportTime=a.timestamp;const i=new Map(r.supervisor.agentHistories);for(const c of a.agentSummaries){const d=i.get(c.agentId)||[],f={id:`${a.id}-${c.agentId}`,timestamp:a.timestamp,reportId:a.id,analysis:c};if(!d.some(h=>h.reportId===a.id)){const h=[f,...d];h.length>50&&h.pop(),i.set(c.agentId,h)}}r.supervisor.agentHistories=i,r.supervisor.generatingReport=!1}),n()},addNarrative(a,r){e(i=>{const c=i.supervisor.narratives.get(a)||[];c.unshift(r),c.length>50&&c.pop();const d=new Map(i.supervisor.narratives);d.set(a,c),i.supervisor.narratives=d}),n()},getNarratives(a){return t().supervisor.narratives.get(a)||[]},setSupervisorStatus(a){e(r=>{r.supervisor.enabled=a.enabled,a.autoReportOnComplete!==void 0&&(r.supervisor.autoReportOnComplete=a.autoReportOnComplete),r.supervisor.lastReportTime=a.lastReportTime,r.supervisor.nextReportTime=a.nextReportTime}),n()},setSupervisorConfig(a){var r;(r=s())==null||r({type:"set_supervisor_config",payload:a})},requestSupervisorReport(){var a;e(r=>{r.supervisor.generatingReport=!0}),n(),(a=s())==null||a({type:"request_supervisor_report",payload:{}})},requestAgentSupervisorHistory(a){var r;e(i=>{i.supervisor.loadingHistoryForAgent=a}),n(),(r=s())==null||r({type:"request_agent_supervisor_history",payload:{agentId:a}})},setAgentSupervisorHistory(a){e(r=>{const i=new Map(r.supervisor.agentHistories);i.set(a.agentId,a.entries),r.supervisor.agentHistories=i,r.supervisor.historyFetchedForAgents.add(a.agentId),r.supervisor.loadingHistoryForAgent===a.agentId&&(r.supervisor.loadingHistoryForAgent=null)}),n()},getAgentSupervisorHistory(a){return t().supervisor.agentHistories.get(a)||[]},addAgentAnalysis(a,r){e(i=>{const c=new Map(i.supervisor.agentHistories),d=c.get(a)||[],f={id:`single-${Date.now()}-${a}`,timestamp:Date.now(),reportId:`single-${Date.now()}`,analysis:r};if(!d.some(m=>Math.abs(m.timestamp-f.timestamp)<5e3&&m.analysis.statusDescription===r.statusDescription)){const m=[f,...d];m.length>50&&m.pop(),c.set(a,m),i.supervisor.agentHistories=c}}),n()},isLoadingHistoryForAgent(a){return t().supervisor.loadingHistoryForAgent===a},hasHistoryBeenFetched(a){return t().supervisor.historyFetchedForAgents.has(a)},setGlobalUsage(a){console.log("[Supervisor] setGlobalUsage called with:",a),e(r=>{r.supervisor.globalUsage=a,r.supervisor.refreshingUsage=!1}),n()},requestGlobalUsage(){console.log("[Supervisor] requestGlobalUsage called"),e(r=>{r.supervisor.refreshingUsage=!0}),n();const a=s();console.log("[Supervisor] sendMessage function:",a?"available":"null"),a?(console.log("[Supervisor] Sending request_global_usage message"),a({type:"request_global_usage",payload:{}})):console.warn("[Supervisor] Cannot send request_global_usage - no sendMessage function")},getGlobalUsage(){return t().supervisor.globalUsage}}}function NO(t,e,n,s){const a=()=>{var c;const i=Array.from(t().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)}),n()},selectArea(i){e(c=>{c.selectedAreaId=i}),n()},addArea(i){if(i.zIndex===void 0||i.zIndex===null){const c=Array.from(t().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(),n()},updateArea(i,c){t().areas.get(i)&&(e(h=>{Object.assign(h.areas.get(i),c)}),r(),a(),n())},updateAreaLocal(i,c){t().areas.get(i)&&(e(h=>{Object.assign(h.areas.get(i),c)}),r(),n())},deleteArea(i){e(c=>{c.areas.delete(i),c.selectedAreaId===i&&(c.selectedAreaId=null)}),r(),a(),n()},assignAgentToArea(i,c){const f=t().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(),n())},unassignAgentFromArea(i,c){const f=t().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(),n())}},addDirectoryToArea(i,c){const f=t().areas.get(i);f&&!f.directories.includes(c)&&(e(h=>{h.areas.get(i).directories.push(c)}),r(),a(),n())},removeDirectoryFromArea(i,c){const f=t().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(),n())}},getAreaDirectories(i){const c=t().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=t(),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}),n()},getAreasInZOrder(){return Array.from(t().areas.values()).sort((c,d)=>(c.zIndex??0)-(d.zIndex??0))},getNextZIndex(){const i=Array.from(t().areas.values());return i.length===0?0:Math.max(...i.map(d=>d.zIndex??0))+1},bringAreaToFront(i){const c=t(),d=c.areas.get(i);if(!d)return;const f=Array.from(c.areas.values()),h=f.length===0?-1:Math.max(...f.map(w=>w.zIndex??0)),m=h+1,b=d.zIndex??0,y=f.filter(w=>(w.zIndex??0)===h);b===h&&y.length===1||(e(w=>{w.areas.get(i).zIndex=m}),r(),a(),n())},sendAreaToBack(i){const c=t(),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 w of y.areas.values())w.id!==i&&(w.zIndex=(w.zIndex??0)+1);y.areas.get(i).zIndex=0}),r(),a(),n())},setAreaZIndex(i,c){t().areas.get(i)&&(e(h=>{h.areas.get(i).zIndex=c}),r(),a(),n())},archiveArea(i,c){const f=t().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(),n()}},restoreArchivedArea(i,c){const d=t(),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,w=Array.from(d.areas.values()),N=(w.length===0?-1:Math.max(...w.map(k=>k.zIndex??0)))+1;e(k=>{const j=k.areas.get(i);if(j.archived=!1,j.archivedAt=void 0,j.center=m,j.zIndex=N,b!==0||y!==0)for(const S of j.assignedAgentIds){const T=k.agents.get(S);T&&(T.position={x:T.position.x+b,y:T.position.y,z:T.position.z+y})}}),r(),a(),n()},getArchivedAreas(){return Array.from(t().areas.values()).filter(i=>i.archived===!0)},getVisibleAreas(){return Array.from(t().areas.values()).filter(i=>!i.archived)},isAgentInArchivedArea(i){const c=t();for(const d of c.areas.values())if(d.archived&&d.assignedAgentIds.includes(i))return!0;return!1}}}const qj="tide:bottom-pm2-log-retention",Fg=5e3,TO=[1e3,2500,5e3,1e4,null];function Vj(){if(typeof window>"u")return Fg;try{const t=window.localStorage.getItem(qj);if(!t)return Fg;if(t==="unlimited")return null;const e=Number(t);if(Number.isFinite(e)&&e>0)return Math.floor(e)}catch{}return Fg}function _O(t){if(!(typeof window>"u"))try{window.localStorage.setItem(qj,t===null?"unlimited":String(t))}catch{}}function Yj(t,e){if(!t||e===null)return t;const n=t.split(`
44
44
  `);return n.length<=e?t:n.slice(-e).join(`
45
45
  `)}function EO(t,e,n,s){const a=()=>{var c;const i=Array.from(t().buildings.values());(c=s())==null||c({type:"sync_buildings",payload:i})},r={selectBuilding(i){e(c=>{c.selectedBuildingIds.clear(),i&&c.selectedBuildingIds.add(i)}),n()},selectMultipleBuildings(i){e(c=>{c.selectedBuildingIds.clear();for(const d of i)c.selectedBuildingIds.add(d)}),n()},toggleBuildingSelection(i){e(c=>{c.selectedBuildingIds.has(i)?c.selectedBuildingIds.delete(i):c.selectedBuildingIds.add(i)}),n()},isBuildingSelected(i){return t().selectedBuildingIds.has(i)},getSelectedBuildingIds(){return Array.from(t().selectedBuildingIds)},deleteSelectedBuildings(){var c,d,f;const i=t();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(),n()},addBuilding(i){e(c=>{const d=new Map(c.buildings);d.set(i.id,i),c.buildings=d}),a(),n()},updateBuilding(i,c){const f=t().buildings.get(i);f&&(e(h=>{const m=new Map(h.buildings);m.set(i,{...f,...c}),h.buildings=m}),a(),n())},updateBuildingLocal(i,c){const f=t().buildings.get(i);f&&(e(h=>{const m=new Map(h.buildings);m.set(i,{...f,...c}),h.buildings=m}),n())},deleteBuilding(i){var f,h,m;const d=t().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(),n()},moveBuilding(i,c){const f=t().buildings.get(i);f&&(e(h=>{const m=new Map(h.buildings);m.set(i,{...f,position:c}),h.buildings=m}),a(),n())},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}),n()},getBuildingLogs(i){return t().buildingLogs.get(i)||[]},clearBuildingLogs(i){e(c=>{const d=new Map(c.buildingLogs);d.delete(i),c.buildingLogs=d}),n()},setBuildingsFromServer(i){e(c=>{const d=new Map;for(const f of i)d.set(f.id,f);c.buildings=d}),n()},updateBuildingFromServer(i){e(c=>{const d=new Map(c.buildings);d.set(i.id,i),c.buildings=d}),n()},removeBuildingFromServer(i){e(c=>{const d=new Map(c.buildings);d.delete(i),c.buildings=d,c.selectedBuildingIds.delete(i)}),n()},startLogStreaming(i,c=100){var f,h,m;const d=t().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=t().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=Vj(),m=Yj(f+c,h),b=new Map(d.streamingBuildingLogs);b.set(i,m),d.streamingBuildingLogs=b}),n()},setStreamingStatus(i,c){e(d=>{const f=new Set(d.streamingBuildingIds);c?f.add(i):f.delete(i),d.streamingBuildingIds=f}),n()},getStreamingLogs(i){return t().streamingBuildingLogs.get(i)||""},clearStreamingLogs(i){e(c=>{const d=new Map(c.streamingBuildingLogs);d.delete(i),c.streamingBuildingLogs=d}),n()},isLogStreaming(i){return t().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=t().buildings.get(i);f&&(e(m=>{const b=new Map(m.buildings);b.set(i,{...f,subordinateBuildingIds:c}),m.buildings=b}),a(),n()),(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},w=[...b,y];w.length>1e3&&w.splice(0,w.length-1e3);const C=new Map(m.bossStreamingLogs);C.set(i,w),m.bossStreamingLogs=C}),n()},getBossStreamingLogs(i){return t().bossStreamingLogs.get(i)||[]},clearBossStreamingLogs(i){e(c=>{const d=new Map(c.bossStreamingLogs);d.delete(i),c.bossStreamingLogs=d}),n()},requestDockerContainersList(){var i;(i=s())==null||i({type:"docker_list_containers",payload:{}})},setDockerContainersList(i,c){e(d=>{d.dockerContainersList=i,d.dockerComposeProjectsList=c}),n()},getDockerContainersList(){return t().dockerContainersList},getDockerComposeProjectsList(){return t().dockerComposeProjectsList}};return r}function MO(t,e,n,s){return{addPermissionRequest(a){e(r=>{const i=new Map(r.permissionRequests);i.set(a.id,a),r.permissionRequests=i}),n()},resolvePermissionRequest(a,r){const c=t().permissionRequests.get(a);c&&(e(d=>{const f=new Map(d.permissionRequests);f.set(a,{...c,status:r?"approved":"denied"}),d.permissionRequests=f}),n(),setTimeout(()=>{e(d=>{const f=new Map(d.permissionRequests);f.delete(a),d.permissionRequests=f}),n()},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(t().permissionRequests.values()).filter(r=>r.agentId===a&&r.status==="pending")},clearAllPermissions(){e(a=>{a.permissionRequests=new Map}),n()}}}function DO(t,e,n,s){return{spawnBossAgent(a,r,i,c,d,f,h,m,b,y,w,C,N){var j;const k=c?{x:c.x,y:0,z:c.z}:void 0;(j=s())==null||j({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:w,customInstructions:C,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}}),n(),(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)}),n()},setDelegationHistory(a,r){e(i=>{const c=new Map(i.delegationHistories);c.set(a,r),i.delegationHistories=c}),n()},getDelegationHistory(a){return t().delegationHistories.get(a)||[]},getLastDelegationReceived(a){return t().lastDelegationReceived.get(a)||null},clearLastDelegationReceived(a){t().lastDelegationReceived.has(a)&&(e(i=>{const c=new Map(i.lastDelegationReceived);c.delete(a),i.lastDelegationReceived=c}),n())},updateBossSubordinates(a,r){const c=t().agents.get(a);c&&(e(d=>{const f={...c,subordinateIds:r},h=new Map(d.agents);h.set(a,f),d.agents=h}),n())},getSubordinates(a){const r=t(),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=t().agents.get(a);return(r==null?void 0:r.isBoss)===!0||(r==null?void 0:r.class)==="boss"},getBossForAgent(a){const r=t(),i=r.agents.get(a);return i!=null&&i.bossId&&r.agents.get(i.bossId)||null},getAvailableSubordinates(){return Array.from(t().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}),n()},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}),n()},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}),n()},getAgentTaskProgress(a){return t().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}}),n()},clearAllSubordinatesContext(a){const i=t().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}),n(),console.log("[Store] clearAllSubordinatesContext: Completed")}}}function RO(t,e,n,s){return{setSkillsFromServer(a){e(r=>{const i=new Map;for(const c of a)i.set(c.id,c);r.skills=i}),n()},addSkillFromServer(a){e(r=>{const i=new Map(r.skills);i.set(a.id,a),r.skills=i}),n()},updateSkillFromServer(a){e(r=>{const i=new Map(r.skills);i.set(a.id,a),r.skills=i}),n()},removeSkillFromServer(a){e(r=>{const i=new Map(r.skills);i.delete(a),r.skills=i}),n()},getSkill(a){return t().skills.get(a)},getAllSkills(){return Array.from(t().skills.values())},getSkillsForAgent(a){const r=t(),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}),n()},addCustomAgentClassFromServer(a){e(r=>{const i=new Map(r.customAgentClasses);i.set(a.id,a),r.customAgentClasses=i}),n()},updateCustomAgentClassFromServer(a){e(r=>{const i=new Map(r.customAgentClasses);i.set(a.id,a),r.customAgentClasses=i}),n()},removeCustomAgentClassFromServer(a){e(r=>{const i=new Map(r.customAgentClasses);i.delete(a),r.customAgentClasses=i}),n()},getCustomAgentClass(a){return t().customAgentClasses.get(a)},getAllCustomAgentClasses(){return Array.from(t().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 OO(t,e,n){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)}),n()},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(`
@@ -148,5 +148,5 @@ ${Ke}`:te=Ke}U.sendCommand(n,te),z==null||z(),r(""),c(!1),N(new Map),h([]),k(),w
148
148
  `)}function J5(t){return t.startsWith("Using tool:")||t.startsWith("Tool input:")||t.startsWith("Tool result:")||t.startsWith("Bash output:")||t.startsWith("Session started:")||t.startsWith("[thinking]")||t.startsWith("Tokens:")||t.startsWith("Cost:")||t.startsWith("Context (estimated from Codex turn usage):")||t.startsWith("🔄 [System]")||t.startsWith("📋 [System]")||t.startsWith("[System]")}function Z5(t,e){if(e.type==="rectangle"&&e.width&&e.height){const n=e.width/2,s=e.height/2;return t.x>=e.center.x-n&&t.x<=e.center.x+n&&t.z>=e.center.z-s&&t.z<=e.center.z+s}if(e.type==="circle"&&e.radius){const n=t.x-e.center.x,s=t.z-e.center.z;return n*n+s*s<=e.radius*e.radius}return!1}let eW=1;function Xf(){return`bp-${eW++}`}const tW=x.memo(function({buildingId:e,filterText:n,maxRetention:s}){const{streamingBuildingLogs:a}=Rs(),r=a.get(e)||"",i=x.useRef(null),c=x.useRef(!1),d=x.useRef(0),f=n.trim().toLowerCase(),h=30,m=x.useCallback(()=>{const S=i.current;if(!S)return;const T=S.scrollTop+S.clientHeight>=S.scrollHeight-h;c.current=!T},[]),b=x.useMemo(()=>Yj(r,s),[r,s]);x.useLayoutEffect(()=>{const S=i.current;if(!S)return;const T=d.current,D=S.scrollHeight;if(c.current){const E=T-D;E>0&&(S.scrollTop=Math.max(0,S.scrollTop-E))}else S.scrollTop=D;d.current=S.scrollHeight},[b,f]);const y=x.useMemo(()=>b?f?b.split(`
149
149
  `).filter(S=>S.toLowerCase().includes(f)).join(`
150
150
  `):b:"",[b,f]),w=x.useMemo(()=>y?y.split(`
151
- `):[],[y]),C=x.useMemo(()=>w.map(S=>Kl(S||" ")),[w]),N=x.useMemo(()=>b?f&&!y?"No log lines match the current filter.":null:"Waiting for logs...",[b,f,y]),k=DN({count:C.length,getScrollElement:()=>i.current,estimateSize:()=>20,overscan:12,measureElement:S=>S.getBoundingClientRect().height}),j=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:j.map(S=>o.jsx("div",{ref:k.measureElement,className:"guake-bottom-pm2-log-line","data-index":S.index,style:{transform:`translateY(${S.start}px)`},dangerouslySetInnerHTML:{__html:C[S.index]}},S.key))})})});x.memo(function({src:e,title:n}){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:n,allow:"clipboard-read; clipboard-write",loading:"lazy",tabIndex:-1,onLoad:()=>{r(!0),d(),f()}})]})});const nW=x.memo(function({onSaveSnapshot:e}={}){var xd,Ko,ti,yd,mc;const{t:n}=dt(["terminal","common"]),s=ed(),a=$x(),r=e1(),i=Ux(),c=r1(),d=i1(),f=t1(),h=Wx(),m=qx(),b=lL(),y=!!b,w=x.useMemo(()=>b?{id:b.agentId,name:b.agentName,class:b.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:b.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:b.createdAt,lastActivity:b.createdAt}:null,[b]),C=Array.from(a),k=C.length===1?C[0]:null,S=(Kj(k)||null)??(y?w:null),T=k??(y?(b==null?void 0:b.agentId)??null:null),D=!!(S!=null&&S.sessionId)&&!y,E=ur(),I=Hx(),O=x.useMemo(()=>{if(!T)return null;const Q=new Set,ue=[];for(const Ee of E.values())Ee.archived||Ee.directories.length===0||Ee.assignedAgentIds.includes(T)&&(Q.add(Ee.id),ue.push(Ee));const le=s.get(T);if(le)for(const Ee of E.values())Ee.archived||Ee.directories.length===0||Q.has(Ee.id)||Z5({x:le.position.x,z:le.position.z},Ee)&&(Q.add(Ee.id),ue.push(Ee));return ue.length===0?null:ue.flatMap(Ee=>Ee.directories.filter(nt=>nt&&nt.trim().length>0).map(nt=>({areaId:Ee.id,areaName:Ee.name,dir:nt})))},[T,E,s]),_=x.useMemo(()=>{var le;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Ee of I.values())Ee.type==="terminal"&&U.isPositionInArea(Ee.position,Q)&&ue.push({id:Ee.id,name:Ee.name,hasUrl:!!((le=Ee.terminalStatus)!=null&&le.url)});return ue},[T,I,E]),M=x.useMemo(()=>{var le;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Ee of I.values())Ee.type==="server"&&((le=Ee.pm2)!=null&&le.enabled)&&U.isPositionInArea(Ee.position,Q)&&ue.push({id:Ee.id,name:Ee.name});return ue},[T,I,E]),R=x.useMemo(()=>{if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const le of I.values())le.type==="database"&&le.database&&U.isPositionInArea(le.position,Q)&&ue.push({id:le.id,name:le.name});return ue},[T,I,E]),{branches:z,fetchRemote:$,fetchingDirs:W}=WH(O),{terminalHeight:L,terminalRef:F,handleResizeStart:H}=MH(),{mobileOverviewHeight:V,handleResizeMouseDown:G,handleResizeTouchStart:B}=OH(),K=EH(),[ne,q]=x.useState(()=>{const Q=Mx(pt.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,Q))}),xe=x.useRef(null),Ae=x.useCallback((Q,ue)=>{Q.preventDefault(),xe.current={startX:Q.clientX,startW:ne},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",U.setTerminalResizing(!0);let le=ne;const Ee=ut=>{if(!xe.current)return;const Nt=ut.clientX-xe.current.startX,_t=ue==="left"?-Nt:Nt;le=Math.max(280,Math.min(700,xe.current.startW+_t)),q(le)},nt=()=>{xe.current=null,document.body.style.cursor="",document.body.style.userSelect="",U.setTerminalResizing(!1),document.removeEventListener("mousemove",Ee),document.removeEventListener("mouseup",nt),Dx(pt.SIDE_PANEL_WIDTH,le)};document.addEventListener("mousemove",Ee),document.addEventListener("mouseup",nt)},[ne]),Z=Qj(T),ce=x.useMemo(()=>y&&b?b.outputs.map(Q=>({text:Q.text||"",timestamp:Q.timestamp,isStreaming:!1,isUserPrompt:!1})):Z,[y,b,Z]),me=x.useRef(null),ee=x.useRef(null),re=x.useRef(null),We=x.useRef(null),[ze,Pe]=x.useState(()=>{const Q=Fa(pt.VIEW_MODE);return Q==="simple"||Q==="chat"||Q==="advanced"?Q:Fa(pt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[ge,Te]=x.useState(()=>Ni(pt.TERMINAL_FULLSCREEN,!1)),[qe,it]=x.useState(null),[he,Be]=x.useState(null),[ie,de]=x.useState(null),[He,et]=x.useState(null),[ct,fe]=x.useState(!1);Xt("guake-image-modal",qe!==null,()=>it(null)),Xt("guake-bash-modal",he!==null,()=>Be(null)),Xt("guake-response-modal",He!==null,()=>et(null)),Xt("guake-context-confirm",ie!==null,()=>de(null)),Xt("guake-agent-info",ct,()=>fe(!1));const[X,se]=x.useState(!1),[Se,J]=x.useState(()=>vs.isEnabled()),[pe,Re]=x.useState(()=>Ni(pt.GIT_PANEL_OPEN,!1)),$e=x.useCallback(Q=>{Re(Q),Ti(pt.GIT_PANEL_OPEN,Q)},[]),[ye,Ie]=x.useState(()=>Ni(pt.BUILDINGS_PANEL_OPEN,!1)),te=x.useCallback(Q=>{Ie(Q),Ti(pt.BUILDINGS_PANEL_OPEN,Q)},[]),[be,we]=x.useState(()=>Ni(pt.WORKFLOW_PANEL_OPEN,!1)),Fe=x.useCallback(Q=>{we(Q),Ti(pt.WORKFLOW_PANEL_OPEN,Q)},[]),[Ke,st]=x.useState(!1);x.useEffect(()=>{if(!T){st(!1);return}let Q=!1;return(async()=>{try{const ue=await Bt(Rt("/api/workflows/definitions"));if(Q||!ue.ok)return;const Ee=(await ue.json()).some(nt=>nt.states.some(ut=>{var Nt,_t;return((Nt=ut.action)==null?void 0:Nt.type)==="agent_task"&&((_t=ut.action)==null?void 0:_t.agentId)===T}));Q||st(Ee)}catch{Q||st(!1)}})(),()=>{Q=!0}},[T]);const ft=hL(),wt=x.useCallback(Q=>U.setOverviewPanelOpen(Q),[]),[rt,gt]=x.useState([]),[ht,Gt]=x.useState({}),[tn,je]=x.useState(()=>Vj()),[Oe,Ye]=x.useState(()=>{try{return localStorage.getItem("tide:bottom-split-direction")==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[Ze,Ot]=x.useState(()=>{try{const Q=localStorage.getItem("tide:bottom-terminal-height");return Q?Math.max(120,Math.min(600,Number(Q))):250}catch{return 250}}),Ft=x.useRef(null),[Lt,Vt]=x.useState([1]),ln=x.useRef(null),bt=x.useRef(null),[at,xt]=x.useState(null),[$t,En]=x.useState(null),nn=x.useMemo(()=>rt.filter(Q=>Q.areaId===$t),[rt,$t]),Un=x.useMemo(()=>new Set(nn.map(Q=>Q.buildingId)),[nn]),Os=x.useRef(new Map);x.useEffect(()=>{try{const Q=localStorage.getItem("tide:bottom-panels-v2");if(Q){const ue=JSON.parse(Q);Os.current=new Map(ue.map(([le,Ee])=>[le,Ee.map(nt=>({id:nt.id??Xf(),type:nt.type,buildingId:nt.buildingId}))]))}else{const ue=localStorage.getItem("tide:bottom-terminals");if(ue){const le=JSON.parse(ue);for(const[Ee,nt]of le)Os.current.set(Ee,[{id:Xf(),type:"terminal",buildingId:nt}])}}}catch{}},[]);const ps=x.useCallback(Q=>{if(!T)return;const ue=U.getAreaForAgent(T);if(ue)try{Q.length>0?Os.current.set(ue.id,Q.map(Ee=>({id:Ee.id,type:Ee.type,buildingId:Ee.buildingId}))):Os.current.delete(ue.id);const le=Array.from(Os.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(le))}catch{}},[T]),ks=x.useCallback(()=>{if(!T)return null;const Q=U.getAreaForAgent(T);return(Q==null?void 0:Q.id)??null},[T]),Qn=x.useCallback((Q,ue)=>{const le=ks();Gt({}),gt(Ee=>{for(const _t of Ee)_t.areaId===le&&_t.type==="pm2-logs"&&U.stopLogStreaming(_t.buildingId);const nt=Ee.filter(_t=>_t.areaId!==le),ut={id:Xf(),type:ue,buildingId:Q,areaId:le??void 0},Nt=[...nt,ut];return ps([ut]),Nt})},[ps,ks]),Ss=x.useCallback((Q,ue,le)=>{const Ee=ks();Ye(le);try{localStorage.setItem("tide:bottom-split-direction",le)}catch{}gt(nt=>{const ut=nt.filter(sn=>sn.areaId===Ee);if(ut.length>=4||ut.some(sn=>sn.buildingId===Q))return nt;const Nt={id:Xf(),type:ue,buildingId:Q,areaId:Ee??void 0},_t=[...nt,Nt];return ps(ut.concat(Nt)),_t})},[ps,ks]),Fn=x.useCallback(Q=>{Gt(ue=>{if(!(Q in ue))return ue;const le={...ue};return delete le[Q],le}),gt(ue=>{const le=ue.find(ut=>ut.id===Q);(le==null?void 0:le.type)==="pm2-logs"&&U.stopLogStreaming(le.buildingId);const Ee=ue.filter(ut=>ut.id!==Q),nt=le==null?void 0:le.areaId;return nt&&ps(Ee.filter(ut=>ut.areaId===nt)),Ee})},[ps]);x.useCallback(()=>{Gt({}),gt(Q=>{for(const ue of Q)ue.type==="pm2-logs"&&U.stopLogStreaming(ue.buildingId);return ps([]),[]})},[ps]),x.useEffect(()=>{if(!T){En(null);return}const Q=U.getAreaForAgent(T);if(!Q){En(null);return}En(Q.id),gt(ue=>{if(ue.filter(ut=>ut.areaId===Q.id).length>0)return ue;const Ee=Os.current.get(Q.id);if(!Ee||Ee.length===0)return ue;const nt=Ee.map(ut=>({id:ut.id,type:ut.type,buildingId:ut.buildingId,areaId:Q.id}));return[...ue,...nt]})},[T]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&Qn(le.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",Q),()=>window.removeEventListener("tide:open-bottom-terminal",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&Qn(le.buildingId,"pm2-logs")};return window.addEventListener("tide:open-bottom-pm2-logs",Q),()=>window.removeEventListener("tide:open-bottom-pm2-logs",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&Qn(le.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",Q),()=>window.removeEventListener("tide:open-bottom-database",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&(le!=null&&le.type)&&(le!=null&&le.direction)&&(nn.length===0?Qn(le.buildingId,le.type):Ss(le.buildingId,le.type,le.direction))};return window.addEventListener("tide:split-bottom-panel",Q),()=>window.removeEventListener("tide:split-bottom-panel",Q)},[nn.length,Qn,Ss]),x.useEffect(()=>{Vt(Q=>Q.length===nn.length?Q:nn.length<=1?[1]:(nn.length>Q.length,Array(nn.length).fill(1)))},[nn.length]);const Ls=x.useCallback((Q,ue)=>{var sn;Q.preventDefault();const le=Oe==="horizontal";ln.current={index:ue,startPos:le?Q.clientX:Q.clientY,startRatios:[...Lt]},document.body.style.cursor=le?"col-resize":"row-resize",document.body.style.userSelect="none";const Ee=(sn=bt.current)==null?void 0:sn.querySelectorAll("iframe");Ee==null||Ee.forEach(gn=>gn.style.pointerEvents="none");const nt=bt.current,ut=nt?le?nt.offsetWidth:nt.offsetHeight:1,Nt=gn=>{const qn=ln.current;if(!qn||!nt)return;const Qo=(le?gn.clientX:gn.clientY)-qn.startPos,Ki=qn.startRatios.reduce((bc,vd)=>bc+vd,0),gc=Qo/ut*Ki,Xo=[...qn.startRatios],Jo=.1*Ki;Xo[ue]=Math.max(Jo,qn.startRatios[ue]+gc),Xo[ue+1]=Math.max(Jo,qn.startRatios[ue+1]-gc),Vt(Xo)},_t=()=>{ln.current=null,document.body.style.cursor="",document.body.style.userSelect="",Ee==null||Ee.forEach(gn=>gn.style.pointerEvents=""),document.removeEventListener("mousemove",Nt),document.removeEventListener("mouseup",_t)};document.addEventListener("mousemove",Nt),document.addEventListener("mouseup",_t)},[Oe,Lt]),Is=x.useRef(new Set);x.useEffect(()=>{const Q=new Set(rt.filter(ue=>ue.type==="pm2-logs").map(ue=>ue.buildingId));for(const ue of Q)Is.current.has(ue)||U.startLogStreaming(ue,200);Is.current=Q},[rt]);const wn=x.useRef(new Set);x.useEffect(()=>{var le;const Q=rt.filter(Ee=>Ee.type==="terminal");for(const Ee of Q){const nt=I.get(Ee.buildingId);!!((le=nt==null?void 0:nt.terminalStatus)!=null&&le.url)?wn.current.add(Ee.buildingId):wn.current.has(Ee.buildingId)&&(wn.current.delete(Ee.buildingId),Fn(Ee.id))}const ue=new Set(Q.map(Ee=>Ee.buildingId));for(const Ee of wn.current)ue.has(Ee)||wn.current.delete(Ee)},[rt,I,Fn]);const Po=x.useCallback(Q=>{Q.preventDefault(),Ft.current={startY:Q.clientY,startH:Ze};let ue=Ze;const le=nt=>{if(!Ft.current)return;const ut=Ft.current.startY-nt.clientY;ue=Math.max(120,Math.min(600,Ft.current.startH+ut)),Ot(ue)},Ee=()=>{Ft.current=null,document.removeEventListener("mousemove",le),document.removeEventListener("mouseup",Ee);try{localStorage.setItem("tide:bottom-terminal-height",String(ue))}catch{}};document.addEventListener("mousemove",le),document.addEventListener("mouseup",Ee)},[Ze]),[Bo,Ps]=x.useState(!1),[Ua,Bi]=x.useState(null),Fi=x.useRef(null),Bs=x.useRef(null),[lc,Ma]=x.useState(!1),[Ts,hs]=x.useState(!1),[Mn,zi]=x.useState(!1),[Ne,Je]=x.useState(!1),Ct=x.useRef(0),ot=r&&S!==null,jn=x.useRef([]),Mt=x.useRef(-1),At=x.useRef(!1),kn=x.useRef(!1),ms=x.useRef(!1),Dn=x.useRef(null),[Fs,Qr]=x.useState(!1),[pa,mh]=x.useState(!1),ha=x.useCallback(()=>{const Q=jn.current,ue=Mt.current;Qr(ue>0),mh(ue>=0&&ue<Q.length-1)},[]),$i=x.useCallback(Q=>{const ue=jn.current;if(ue.length===0)return;let le=Mt.current+Q;for(;le>=0&&le<ue.length;){const Ee=ue[le];if(s.has(Ee)){At.current=!0,Mt.current=le,ha(),U.selectAgent(Ee);return}le+=Q}},[s,ha]),gr=x.useCallback(()=>{$i(-1)},[$i]),Ui=x.useCallback(()=>{$i(1)},[$i]),cc=x.useCallback((Q,ue)=>{if(typeof window>"u")return;const le=window.history.state,nt={...typeof le=="object"&&le!==null?le:{},__guakeAgentNav:{agentId:Q}};ue==="replace"?window.history.replaceState(nt,"",window.location.href):window.history.pushState(nt,"",window.location.href)},[]),Fo=x.useCallback(()=>{Te(Q=>{const ue=!Q;return Ti(pt.TERMINAL_FULLSCREEN,ue),ue})},[]),It=Wj({selectedAgentId:T,hasSessionId:D,reconnectCount:c,historyRefreshTrigger:d,lastPrompts:i,outputScrollRef:me}),Hn=LH({agents:s,selectedAgentId:T,isOpen:ot,overviewPanelOpen:ft,loadingHistory:It.fetchingHistory,hasModalOpen:!!(qe||he||He||h||m),outputRef:me});x.useEffect(()=>{const Q=F.current;if(!Q||!ot)return;const ue=Ee=>{Ee.button===3?(Ee.preventDefault(),Ee.stopPropagation(),gr()):Ee.button===4&&(Ee.preventDefault(),Ee.stopPropagation(),Ui())},le=Ee=>{(Ee.button===3||Ee.button===4)&&Ee.preventDefault()};return Q.addEventListener("mouseup",ue),Q.addEventListener("mousedown",le),()=>{Q.removeEventListener("mouseup",ue),Q.removeEventListener("mousedown",le)}},[ot,gr,Ui]);const uc=x.useCallback(Q=>{U.setLastSelectionViaDirectClick(!0),U.selectAgent(Q)},[]),Xr=typeof window<"u"&&window.innerWidth<=768&&ft&&ot,Jr=tR({gestureRef:me,agentListRef:ee,enabled:Xr,onSelect:uc}),ts=$H({selectedAgentId:k}),zo=KO(),cd=x.useMemo(()=>y||!T?[]:Array.from(zo.values()).filter(Q=>Q.agentId===T&&Q.status==="pending"),[y,T,zo]),Ha=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),zs=nL(!y&&Ha?T:null),Hi=x.useMemo(()=>Array.from(zs.values()).filter(Q=>Q.status==="working"),[zs]),br=x.useMemo(()=>Array.from(zs.values()).filter(Q=>Q.status==="completed"||Q.status==="failed").map(Q=>Q.agentId),[zs]),[ma,$o]=x.useState(!0),Uo=sL(y?null:T),ud=pL(y?null:T);x.useEffect(()=>{X&&!Se&&(J(!0),vs.setEnabled(!0))},[X,Se]),x.useEffect(()=>{ot||fe(!1)},[ot]),x.useEffect(()=>{if(!T||!Ha||y||br.length===0)return;const Q=window.setTimeout(()=>{br.forEach(ue=>{U.clearAgentTaskProgress(T,ue)})},300);return()=>window.clearTimeout(Q)},[T,Ha,y,br]),x.useEffect(()=>{const Q=S==null?void 0:S.status;if(Fi.current==="working"&&Q==="idle"){Bs.current&&clearTimeout(Bs.current);const le=T?i.get(T):void 0;Bi(le!=null&&le.timestamp?Date.now()-le.timestamp:null),Ps(!0),Bs.current=setTimeout(()=>{Ps(!1),Bi(null),Bs.current=null},4e3)}else Q==="working"&&(Bs.current&&(clearTimeout(Bs.current),Bs.current=null),Ps(!1),Bi(null));return Fi.current=Q||null,()=>{Bs.current&&clearTimeout(Bs.current)}},[S==null?void 0:S.status]);const Wi=x.useMemo(()=>{const{history:Q}=It,ue=new Map;for(const Ee of Q)Ee.type==="tool_result"&&Ee.toolUseId&&ue.set(Ee.toolUseId,Ee.content);return(Ee=>Ee.map(nt=>{if(nt.type==="tool_use"&&nt.toolName==="Bash"&&nt.toolUseId){const ut=ue.get(nt.toolUseId);let Nt;try{Nt=(nt.toolInput||(nt.content?JSON.parse(nt.content):{})).command}catch{}return{...nt,_bashOutput:ut,_bashCommand:Nt}}return nt}))(Q)},[It.history,ze]),qi=_T({outputs:ce,viewMode:ze}),Wa=x.useMemo(()=>{const Q=[],ue=new Set,le=new Set;let Ee=null,nt=0;for(const ut of Wi){if(ut.type==="assistant"){const gn=ut.uuid?`uuid:${ut.uuid}:${Qf(ut.content)}`:`sig:${ut.timestamp}:${Qf(ut.content)}`;if(ue.has(gn))continue;ue.add(gn),Q.push(ut);continue}if(ut.type!=="user"){Q.push(ut);continue}const Nt=Eb(ut.content),_t=ut.uuid?`uuid:${ut.uuid}:${Nt}`:null;if(_t&&le.has(_t))continue;const sn=ut.timestamp?new Date(ut.timestamp).getTime():0;Ee===Nt&&Math.abs(sn-nt)<=VA||(Q.push(ut),_t&&le.add(_t),Ee=Nt,nt=sn)}return Q},[Wi]),Wn=x.useMemo(()=>{const Q=new Map,ue=new Set,le=new Map;for(const Nt of Wa){const _t=Nt.timestamp?new Date(Nt.timestamp).getTime():0;if(Nt.type==="user"){const qn=Eb(Nt.content),Va=Q.get(qn)??0;_t>Va&&Q.set(qn,_t);continue}if(Nt.type!=="assistant")continue;Nt.uuid&&ue.add(Nt.uuid);const sn=Qf(Nt.content),gn=le.get(sn)??0;_t>gn&&le.set(sn,_t)}const Ee=[];let nt=null,ut=0;for(const Nt of qi){if(!Nt.isUserPrompt){if(!Nt.isStreaming&&!J5(Nt.text)){if(Nt.uuid&&ue.has(Nt.uuid))continue;const qn=Qf(Nt.text),Va=Nt.timestamp||0,Qo=le.get(qn);if(Qo&&Math.abs(Va-Qo)<=K5)continue}Ee.push(Nt);continue}const _t=Eb(Nt.text),sn=Nt.timestamp||0,gn=Q.get(_t);gn&&sn>=gn&&sn-gn<=G5||nt===_t&&Math.abs(sn-ut)<=VA||(Ee.push(Nt),nt=_t,ut=sn)}return Ee},[qi,Wa]),xr=x.useMemo(()=>[...Wa,...Wn],[Wa,Wn]),Ln=BH({selectedAgentId:T,isOpen:ot,allItems:xr,viewMode:ze,hasMoreHistory:It.hasMore,loadAllHistory:It.loadAllHistory,loadingMore:It.loadingMore}),Vi=Wa.length+Wn.length,dd=UH({totalMessages:Vi,isOpen:ot,hasModalOpen:!!(qe||he||He||h),scrollContainerRef:me,selectedAgentId:T,inputRef:re,textareaRef:We,useTextarea:ts.useTextarea});x.useEffect(()=>{if(!(!(he!=null&&he.isLive)||!he.command)){for(const Q of Wn)if(Q._bashCommand===he.command&&Q._bashOutput){Be({command:he.command,output:Q._bashOutput,isLive:!1});return}}},[he,Wn]);const Ho=x.useCallback((Q,ue)=>{it({url:Q,name:ue})},[]),Wo=x.useCallback((Q,ue)=>{const le=sh(Q,S==null?void 0:S.cwd),Ee=le.line?{...ue||{},targetLine:le.line}:ue;U.setFileViewerPath(le.path,Ee,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),Zr=x.useCallback((Q,ue)=>{Be({command:Q,output:ue,isLive:ue==="Running..."})},[]),qo=x.useCallback(Q=>{et(Q)},[]),fd=x.useCallback(()=>{fe(Q=>!Q)},[]),[gh,Vo]=x.useState(!0),[pd,ei]=x.useState(0),[dc,fc]=x.useState(!1),Yi=x.useRef(!1),pc=x.useRef(!1),Yo=x.useRef(!1),hd=x.useCallback(()=>{Yo.current||(Yi.current=!0,Vo(!1))},[]),bh=x.useCallback(()=>hs(!1),[]),xh=x.useCallback(()=>{Yi.current=!1,Vo(!0)},[]),yh=x.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(fc(!0),ei(Q5),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{U.setMobileView("3d"),fc(!1),ei(0)},X5))},[]),vh=x.useCallback(Q=>{dc||ei(Q)},[dc]);x.useEffect(()=>{Vo(!0),ei(0),fc(!1),Yi.current=!1,pc.current=!0,Yo.current=!0;const Q=setTimeout(()=>{Yo.current=!1},3e3);return()=>clearTimeout(Q)},[T]),x.useEffect(()=>{if(!T){jn.current=[],Mt.current=-1,ha(),ms.current=!1,Dn.current=null;return}const Q=jn.current;if(At.current){At.current=!1,ha();return}const ue=Mt.current;if(ue>=0&&Q[ue]===T){ha();return}const le=ue<Q.length-1?Q.slice(0,ue+1):Q.slice();le.push(T),le.length>100&&le.shift(),jn.current=le,Mt.current=le.length-1,ha()},[T,ha]),x.useEffect(()=>{if(!(!ot||!T)){if(!ms.current){cc(T,"replace"),ms.current=!0,Dn.current=T;return}if(kn.current){kn.current=!1,Dn.current=T;return}Dn.current!==T&&(cc(T,"push"),Dn.current=T)}},[ot,T,cc]),x.useEffect(()=>{if(!ot)return;const Q=ue=>{var ut,Nt;const le=(Nt=(ut=ue.state)==null?void 0:ut.__guakeAgentNav)==null?void 0:Nt.agentId;if(!le||typeof le!="string"||!s.has(le)||le===k)return;kn.current=!0,At.current=!0;const Ee=jn.current,nt=Ee.lastIndexOf(le);nt>=0?Mt.current=nt:(Ee.push(le),Mt.current=Ee.length-1),ha(),U.selectAgent(le)};return window.addEventListener("popstate",Q),()=>window.removeEventListener("popstate",Q)},[ot,s,k,ha]),x.useEffect(()=>{if(!pc.current||!T||Mn||It.fetchingHistory)return;let Q=0,ue=0;return Q=requestAnimationFrame(()=>{ue=requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=me.current.scrollHeight),pc.current=!1})}),()=>{cancelAnimationFrame(Q),cancelAnimationFrame(ue)}},[T,Mn,It.fetchingHistory,It.historyLoadVersion]);const Go=x.useRef(It.handleScroll);Go.current=It.handleScroll;const wh=x.useCallback(()=>{if(!me.current||K.keyboardScrollLockRef.current)return;const{scrollTop:Q,scrollHeight:ue,clientHeight:le}=me.current,Ee=ue-Q-le<150;Yo.current||(Yi.current=!Ee,Ee&&Vo(!0)),Go.current(K.keyboardScrollLockRef)},[me,K.keyboardScrollLockRef]),kh=Z.length>0&&((Ko=(xd=Z[Z.length-1])==null?void 0:xd.text)==null?void 0:Ko.length)||0;x.useEffect(()=>{K.keyboardScrollLockRef.current||Yi.current||requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=me.current.scrollHeight)})},[Z.length,kh,K.keyboardScrollLockRef,me]);const md=x.useRef(null);x.useLayoutEffect(()=>{const Q=md.current;Q!==null&&Q!==k?(Ma(!1),k&&It.hasCachedHistory(k)||zi(!0),U.getState().currentSnapshot&&U.setCurrentSnapshot(null)):k||Ma(!1),md.current=k},[k]),x.useEffect(()=>{if(!Mn||It.fetchingHistory)return;const Q=requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=me.current.scrollHeight),zi(!1)});return()=>cancelAnimationFrame(Q)},[Mn,It.fetchingHistory,It.historyLoadVersion]);const qa=x.useRef(!1);x.useEffect(()=>{ot&&k&&U.clearUnseenForAgent(k)},[ot,k]),x.useEffect(()=>{qa.current=!0,hs(!0)},[T,c]),x.useEffect(()=>{It.fetchingHistory&&(qa.current=!0,hs(!0))},[It.fetchingHistory]),x.useEffect(()=>{if(!Ts||!ot||It.fetchingHistory)return;const Q=me.current;if(!Q)return;let ue=null;const le=performance.now();let Ee=0,nt=-1;const ut=()=>{const{scrollTop:_t,scrollHeight:sn,clientHeight:gn}=Q;return sn-_t-gn<=2},Nt=()=>{const _t=performance.now(),sn=Q.scrollHeight,gn=Math.abs(sn-nt)<=1,qn=ut();if(gn&&qn?Ee+=1:Ee=0,nt=sn,Ee>=3){hs(!1),ue=null;return}if(_t-le>8e3){hs(!1),ue=null;return}ue=requestAnimationFrame(Nt)};return ue=requestAnimationFrame(Nt),()=>{ue!==null&&cancelAnimationFrame(ue)}},[Ts,ot,It.fetchingHistory,It.historyLoadVersion]);const gd=x.useRef(!1);x.useEffect(()=>{gd.current&&!Ts&&qa.current&&(qa.current=!1,Ma(!0)),gd.current=Ts},[Ts]),x.useEffect(()=>{if(!ot||!qa.current||Ts||It.fetchingHistory)return;const Q=requestAnimationFrame(()=>{qa.current&&(qa.current=!1,Ma(!0))});return()=>cancelAnimationFrame(Q)},[It.historyLoadVersion,ot,Ts,It.fetchingHistory]),x.useEffect(()=>{const Q=ue=>{if(ue.key==="`"&&!ue.ctrlKey&&!ue.altKey&&S){const le=ue.target;le.tagName!=="INPUT"&&le.tagName!=="TEXTAREA"&&(ue.preventDefault(),U.toggleTerminal())}};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[S]),x.useEffect(()=>{if(!ot)return;const Q=ue=>{ue.altKey&&(ue.key!=="ArrowLeft"&&ue.key!=="ArrowRight"||(ue.key==="ArrowLeft"&&Fs?(ue.preventDefault(),gr()):ue.key==="ArrowRight"&&pa&&(ue.preventDefault(),Ui())))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[ot,Fs,pa,gr,Ui]),x.useEffect(()=>{const Q=ue=>{ue.key==="Escape"&&(h?(ue.stopImmediatePropagation(),U.clearFileViewerPath()):m?(ue.stopImmediatePropagation(),U.closeContextModal()):He?(ue.stopImmediatePropagation(),et(null)):he?(ue.stopImmediatePropagation(),Be(null)):qe?(ue.stopImmediatePropagation(),it(null)):Ln.searchMode&&(ue.stopImmediatePropagation(),Ln.closeSearch()))};return document.addEventListener("keydown",Q,!0),()=>document.removeEventListener("keydown",Q,!0)},[qe,he,He,Ln,h,m]);const bd=x.useRef(ot),Gi=x.useRef(!1);x.useEffect(()=>{bd.current=ot},[ot]),x.useEffect(()=>{if(window.innerWidth<=768)return;const ue=nt=>{var sn;if(!(nt instanceof Element))return!1;const ut=(sn=F.current)==null?void 0:sn.contains(nt),Nt=nt.closest(".agent-bar"),_t=!!nt.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");return!!ut||!!Nt||_t},le=nt=>{if(!bd.current){Gi.current=!1;return}if(XD("terminal")){Gi.current=!1;return}Gi.current=!ue(nt.target)},Ee=nt=>{Gi.current&&(ue(nt.target)||U.setTerminalOpen(!1),Gi.current=!1)};return document.addEventListener("mousedown",le,!0),document.addEventListener("mouseup",Ee,!0),()=>{document.removeEventListener("mousedown",le,!0),document.removeEventListener("mouseup",Ee,!0)}},[]),x.useEffect(()=>{const Q=()=>{document.hidden&&K.cleanup()};return document.addEventListener("visibilitychange",Q),()=>document.removeEventListener("visibilitychange",Q)},[K]),x.useEffect(()=>()=>K.cleanup(),[T,K]);const hc=typeof window<"u"&&window.innerWidth<=768;if(!S)return hc&&f==="terminal"&&a.size===0?o.jsx("div",{ref:F,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${L}%`},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:n("terminal:empty.tapAgent")}),o.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:n("terminal:empty.switchTo3D")})]})})})}):hc&&f==="terminal"&&a.size>0?o.jsx("div",{ref:F,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${L}%`},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:[n("terminal:empty.loadingTerminal"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]})})})}):null;if(!T)return null;const Sh=Q=>{Q.preventDefault(),Q.stopPropagation(),Ct.current++,Q.dataTransfer.types.includes("Files")&&Je(!0)},Ch=Q=>{Q.preventDefault(),Q.stopPropagation()},Ah=Q=>{Q.preventDefault(),Q.stopPropagation(),Ct.current--,Ct.current===0&&Je(!1)},jh=async Q=>{Q.preventDefault(),Q.stopPropagation(),Ct.current=0,Je(!1);const ue=Q.dataTransfer.files;if(ue.length)for(const le of ue){const Ee=await ts.uploadFile(le);Ee&&ts.setAttachedFiles(nt=>[...nt,Ee])}};return o.jsxs("div",{ref:F,className:`guake-terminal ${ot?"open":"collapsed"} ${ge&&ot?"fullscreen":""} ${X&&ot?"with-debug-panel":""} ${pe&&ot?"with-git-panel":""} ${ye&&ot?"with-buildings-panel":""} ${be&&ot?"with-workflow-panel":""} ${ft&&ot?"with-overview-panel":""} ${Ne?"drag-over":""} ${pd>0?"mobile-swipe-close-active":""} ${dc?"mobile-swipe-close-closing":""}`,style:{"--terminal-height":`${L}%`,"--mobile-swipe-close-offset":`${pd}px`,"--guake-side-panel-width":`${ne}px`,...V>0?{"--guake-mobile-overview-height":`${V}px`}:{}},onDragEnter:Sh,onDragOver:Ch,onDragLeave:Ah,onDrop:jh,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:n("terminal:input.dropToAttach")})]}),!y&&X&&ot&&T&&o.jsx(o5,{agentId:T,onClose:()=>se(!1)}),!y&&pe&&ot&&T&&o.jsx(b5,{agentId:T,agents:s,onClose:()=>$e(!1),branchInfoMap:z,fetchRemote:$,fetchingDirs:W}),!y&&ye&&ot&&T&&o.jsx(D5,{agentId:T,onClose:()=>te(!1)}),!y&&be&&ot&&T&&o.jsx(L5,{agentId:T,onClose:()=>Fe(!1)}),!y&&(X||pe||ye||be)&&ot&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:Q=>Ae(Q,"right")}),!y&&ft&&ot&&T&&o.jsx(_5,{activeAgentId:T,onClose:()=>wt(!1),onSelectAgent:Q=>{U.setLastSelectionViaDirectClick(!0),U.selectAgent(Q)},agentListRef:ee,twoFingerState:Jr}),!y&&ft&&ot&&T&&o.jsx("div",{className:"guake-side-panel-resize left",onMouseDown:Q=>Ae(Q,"left")}),!y&&ft&&ot&&T&&o.jsx("div",{className:"aop-resize-handle",onMouseDown:G,onTouchStart:B}),o.jsxs("div",{className:"guake-content",children:[o.jsx(A6,{selectedAgent:S,selectedAgentId:T,sortedAgents:Hn.sortedAgents,swipeOffset:Hn.swipeOffset,viewMode:ze,setViewMode:Pe,searchMode:Ln.searchMode,toggleSearch:Ln.toggleSearch,closeSearch:Ln.closeSearch,debugPanelOpen:X,setDebugPanelOpen:se,debuggerEnabled:Se,setDebuggerEnabled:J,gitPanelOpen:pe,setGitPanelOpen:$e,buildingsPanelOpen:ye,setBuildingsPanelOpen:te,workflowPanelOpen:be,setWorkflowPanelOpen:Fe,hasWorkflow:Ke,overviewPanelOpen:ft,setOverviewPanelOpen:wt,agentInfoOpen:ct,onToggleAgentInfo:fd,isFullscreen:ge,onToggleFullscreen:Fo,onNavigateBack:gr,onNavigateForward:Ui,canNavigateBack:Fs,canNavigateForward:pa,outputsLength:Wa.length+Wn.length,setContextConfirm:de,headerRef:Hn.headerRef,onSaveSnapshot:y?void 0:e,isSnapshotView:y}),Ln.searchMode&&o.jsx(j6,{searchInputRef:Ln.searchInputRef,searchQuery:Ln.searchQuery,setSearchQuery:Ln.setSearchQuery,closeSearch:Ln.closeSearch,matchCount:Ln.matchIndices.length,currentMatch:Ln.currentMatch,navigateNext:Ln.navigateNext,navigatePrev:Ln.navigatePrev,loadingFullHistory:Ln.loadingFullHistory}),o.jsxs("div",{className:`guake-swipe-container ${Hn.swipeAnimationClass}`,style:Hn.swipeOffset!==0?{transform:`translateX(${Hn.swipeOffset*40}%)`}:void 0,children:[Hn.sortedAgents.length>1&&Hn.swipeOffset!==0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`swipe-indicator left ${Hn.swipeOffset>.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-icon",children:"←"}),o.jsx("span",{className:"indicator-name",children:(ti=Hn.nextAgent)==null?void 0:ti.name})]}),o.jsxs("div",{className:`swipe-indicator right ${Hn.swipeOffset<-.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-name",children:(yd=Hn.prevAgent)==null?void 0:yd.name}),o.jsx("span",{className:"indicator-icon",children:"→"})]})]}),Hn.sortedAgents.length>1&&Hn.sortedAgents.length<=8&&Hn.swipeOffset!==0&&o.jsx("div",{className:`swipe-dots ${Math.abs(Hn.swipeOffset)>.1?"visible":""}`,children:Hn.sortedAgents.map((Q,ue)=>o.jsx("div",{className:`swipe-dot ${ue===Hn.currentAgentIndex?"active":""}`},Q.id))}),o.jsx("div",{className:"guake-output",ref:me,onScroll:wh,children:o.jsxs("div",{className:`guake-history-content ${lc?"fade-in":""}`,children:[Mn&&o.jsxs("div",{className:"guake-empty loading",children:[n("terminal:empty.loadingConversation"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]}),!Mn&&It.loadingHistory&&It.history.length===0&&Z.length===0&&o.jsxs("div",{className:"guake-empty loading",children:[n("terminal:empty.loadingConversation"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]}),!Mn&&!It.loadingHistory&&It.history.length===0&&ce.length===0&&S.status!=="working"&&o.jsx("div",{className:"guake-empty",children:n("terminal:empty.noOutput")}),!Mn&&It.hasMore&&!Ln.searchMode&&o.jsx("div",{className:"guake-load-more",children:It.loadingMore?o.jsx("span",{children:n("terminal:empty.loadingOlder")}):o.jsx("button",{onClick:It.loadMoreHistory,children:n("terminal:empty.loadMore",{count:It.totalCount-It.history.length})})}),!Mn&&o.jsx(i5,{historyMessages:Wa,liveOutputs:Wn,agentId:T,execTasks:Uo,subagents:ud,viewMode:ze,searchHighlight:Ln.highlightQuery,searchActiveIndex:Ln.scrollToIndex,selectedMessageIndex:dd.selectedIndex,isMessageSelected:dd.isSelected,onImageClick:Ho,onFileClick:Wo,onBashClick:Zr,onViewMarkdown:qo,scrollContainerRef:me,onScrollTopReached:It.loadMoreHistory,isLoadingMore:It.loadingMore,hasMore:It.hasMore,shouldAutoScroll:gh,onUserScroll:hd,pinToBottom:Ts,onPinCancel:bh,isLoadingHistory:It.fetchingHistory},T),!Mn&&Ha&&Hi.length>0&&o.jsxs("div",{className:`agent-progress-container ${ma?"collapsed":"expanded"}`,children:[o.jsxs("div",{className:"agent-progress-container-header",onClick:()=>$o(Q=>!Q),role:"button",tabIndex:0,onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),$o(ue=>!ue))},children:[o.jsx("span",{className:"progress-crown",children:"👑"}),o.jsx("span",{children:n("terminal:empty.subordinateProgress")}),o.jsx("span",{className:"progress-count",children:n("terminal:empty.activeCount",{count:Hi.length})}),o.jsx("span",{className:"agent-progress-container-toggle",children:ma?"▶":"▼"})]}),!ma&&Hi.map(Q=>o.jsx($5,{progress:Q,defaultExpanded:Q.status==="working",onAgentClick:ue=>{U.selectAgent(ue),U.setTerminalOpen(!0)},onDismiss:ue=>{T&&U.clearAgentTaskProgress(T,ue)},onFileClick:Wo,onBashClick:Zr},Q.agentId))]})]})})]}),o.jsx(O6,{selectedAgent:S,selectedAgentId:T,isOpen:ot,command:ts.command,setCommand:ts.setCommand,forceTextarea:ts.forceTextarea,setForceTextarea:ts.setForceTextarea,useTextarea:ts.useTextarea,attachedFiles:ts.attachedFiles,setAttachedFiles:ts.setAttachedFiles,removeAttachedFile:ts.removeAttachedFile,uploadFile:ts.uploadFile,pastedTexts:ts.pastedTexts,expandPastedTexts:ts.expandPastedTexts,incrementPastedCount:ts.incrementPastedCount,setPastedTexts:ts.setPastedTexts,resetPastedCount:ts.resetPastedCount,handleInputFocus:K.handleInputFocus,handleInputBlur:K.handleInputBlur,pendingPermissions:cd,showCompletion:Bo,completionElapsed:Ua,onImageClick:Ho,inputRef:re,textareaRef:We,isSnapshotView:y,onClearHistory:It.clearHistory,onSendCommand:xh,canSwipeClose:hc&&f==="terminal"&&!Mn&&!Ln.searchMode&&!It.fetchingHistory,onSwipeCloseOffsetChange:vh,onSwipeClose:yh}),o.jsxs("div",{className:"guake-agent-status-bar",children:[!y&&(S==null?void 0:S.isDetached)&&o.jsx(os,{content:o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",n("terminal:empty.reattachingSessionTitle")]}),o.jsxs("div",{className:"tide-tooltip__text",children:[n("terminal:empty.reattachingSessionDesc"),o.jsx("br",{}),o.jsx("br",{}),o.jsxs("strong",{children:[n("common:labels.status"),":"]})," ",n("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:o.jsxs("span",{className:"guake-detached-badge",title:n("terminal:empty.reattachingBadge"),children:[o.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",n("terminal:empty.reattaching")]})}),(S==null?void 0:S.cwd)&&o.jsxs("span",{className:"guake-agent-cwd",title:S.cwd,children:["📁 ",S.cwd.split("/").filter(Boolean).slice(-2).join("/")||S.cwd]}),O&&O.map(({areaId:Q,areaName:ue,dir:le})=>{const Ee=z.get(le),nt=W.has(le);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${ue}: ${le}${Ee?` (${Ee.branch}${Ee.ahead?` ↑${Ee.ahead}`:""}${Ee.behind?` ↓${Ee.behind}`:""})`:""}`,onClick:()=>U.openFileExplorerForAreaFolder(Q,le),children:["📂 ",le.split("/").filter(Boolean).pop()||le,Ee&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",Ee.branch]}),Ee.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${Ee.ahead} ahead`,children:["↑",Ee.ahead]}),Ee.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${Ee.behind} behind`,children:["↓",Ee.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${nt?"fetching":""}`,title:"Git fetch",onClick:ut=>{ut.stopPropagation(),$(le)},children:nt?"⏳":"⇣"})]})]},`${Q}:${le}`)}),!y&&S&&(()=>{const Q=S.contextStats,ue=!!Q,le=Q?Q.totalTokens:S.contextUsed||0,Ee=Q?Q.contextWindow:S.contextLimit||2e5,nt=Q?Q.usedPercent:Math.round(le/Ee*100),ut=Math.max(0,Math.min(100,nt)),Nt=Math.max(0,100-ut),_t=ut>=80?"#ff4a4a":ut>=60?"#ff9e4a":ut>=40?"#ffd700":"#4aff9e",sn=(le/1e3).toFixed(1),gn=(Ee/1e3).toFixed(1);return o.jsxs("span",{className:"guake-agent-context",onClick:()=>U.setContextModalAgentId(T),title:n(ue?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[o.jsx("span",{className:"context-icon",children:"📊"}),o.jsxs("span",{className:"context-label",children:[n("terminal:agentInfo.context"),":"]}),o.jsx("span",{className:"context-bar-mini",children:o.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,ut)}%`,backgroundColor:_t}})}),o.jsxs("span",{className:"context-tokens",style:{color:_t},children:[sn,"k/",gn,"k"]}),o.jsxs("span",{className:"context-free",children:["(",n("terminal:context.percentFree",{percent:Nt}),")"]}),!ue&&o.jsx("span",{className:"context-warning",title:n("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),o.jsxs("span",{className:"guake-status-right",children:[_.length>0&&o.jsx("span",{className:"guake-status-terminals",children:_.map(Q=>{const ue=Un.has(Q.id);return o.jsx("button",{className:`guake-status-terminal-btn ${ue?"active":""} ${Q.hasUrl?"":"offline"}`,title:`${ue?"Hide":"Show"} terminal: ${Q.name}${Q.hasUrl?"":" (starting...)"}`,onClick:()=>{if(ue){const le=rt.find(Ee=>Ee.buildingId===Q.id);le&&Fn(le.id)}else Q.hasUrl||U.sendBuildingCommand(Q.id,"start"),Qn(Q.id,"terminal")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Un.has(Q.id)||xt({position:{x:le.clientX,y:le.clientY},buildingId:Q.id,type:"terminal"})},children:"💻"},Q.id)})}),M.length>0&&o.jsx("span",{className:"guake-status-terminals",children:M.map(Q=>{const ue=Un.has(Q.id);return o.jsx("button",{className:`guake-status-terminal-btn ${ue?"active":""}`,title:`${ue?"Hide":"Show"} logs: ${Q.name}`,onClick:()=>{if(ue){const le=rt.find(Ee=>Ee.buildingId===Q.id);le&&Fn(le.id)}else Qn(Q.id,"pm2-logs")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Un.has(Q.id)||xt({position:{x:le.clientX,y:le.clientY},buildingId:Q.id,type:"pm2-logs"})},children:"📜"},Q.id)})}),R.length>0&&o.jsx("span",{className:"guake-status-terminals",children:R.map(Q=>{const ue=Un.has(Q.id);return o.jsx("button",{className:`guake-status-terminal-btn ${ue?"active":""}`,title:`${ue?"Hide":"Show"} database: ${Q.name}`,onClick:()=>{if(ue){const le=rt.find(Ee=>Ee.buildingId===Q.id);le&&Fn(le.id)}else Qn(Q.id,"database")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Un.has(Q.id)||xt({position:{x:le.clientX,y:le.clientY},buildingId:Q.id,type:"database"})},children:"🗄️"},Q.id)})}),o.jsx(H5,{})]})]}),(()=>{const Q=[];return at&&(Q.push({id:"open",label:"Open",icon:"⬇",onClick:()=>Qn(at.buildingId,at.type)}),nn.length>0&&(Q.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Ss(at.buildingId,at.type,"horizontal")}),Q.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Ss(at.buildingId,at.type,"vertical")}))),o.jsx(pr,{children:o.jsx(Do,{isOpen:at!==null,position:(at==null?void 0:at.position)||{x:0,y:0},worldPosition:{x:0,z:0},actions:Q,onClose:()=>xt(null)})})})(),nn.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:Po}),o.jsx("div",{ref:bt,className:`guake-bottom-panels-container ${Oe}`,style:{height:Ze},onWheel:Q=>Q.stopPropagation(),children:nn.map((Q,ue)=>{const le=I.get(Q.buildingId);if(!le)return null;const Ee=Lt[ue]??1,nt=(()=>{var ut;if(Q.type==="terminal")return(ut=le.terminalStatus)!=null&&ut.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>Fn(Q.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(Ax,{terminalUrl:le.terminalStatus.url,visible:!0})]},Q.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name," (starting...)"]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>Fn(Q.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..."})})]},Q.id);if(Q.type==="pm2-logs"){const Nt=ht[Q.id]||"";return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",le.name]}),o.jsxs("div",{className:"guake-bottom-terminal-controls",children:[o.jsx("input",{type:"text",className:"guake-bottom-terminal-filter",value:Nt,onChange:_t=>{const sn=_t.target.value;Gt(gn=>{if(!sn.trim()){if(!(Q.id in gn))return gn;const qn={...gn};return delete qn[Q.id],qn}return{...gn,[Q.id]:sn}})},placeholder:"Filter logs","aria-label":`Filter logs for ${le.name}`,spellCheck:!1}),o.jsx("select",{className:"guake-bottom-terminal-retention",value:tn===null?"unlimited":String(tn),onChange:_t=>{const sn=_t.target.value==="unlimited"?null:Number(_t.target.value);je(sn),_O(sn)},"aria-label":`Max log retention for ${le.name}`,children:TO.map(_t=>o.jsx("option",{value:_t===null?"unlimited":String(_t),children:_t===null?"Unlimited":`${_t.toLocaleString()} lines`},_t===null?"unlimited":_t))}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>U.clearStreamingLogs(Q.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:()=>U.sendBuildingCommand(Q.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:()=>Fn(Q.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(tW,{buildingId:Q.buildingId,filterText:Nt,maxRetention:tn})]},Q.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>Fn(Q.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(_H,{building:le})]},Q.id)})();return ue>0?o.jsxs(Ce.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${Oe}`,onMouseDown:ut=>Ls(ut,ue-1)}),nt]},Q.id):nt})})]}),rt.filter(Q=>Q.areaId!==$t&&Q.type==="terminal").map(Q=>{var le;const ue=I.get(Q.buildingId);return(le=ue==null?void 0:ue.terminalStatus)!=null&&le.url?o.jsx(Ax,{terminalUrl:ue.terminalStatus.url,visible:!1},Q.id):null})]}),ot&&!ge&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:H,title:n("common:rightPanel.dragToResize")}),!(ot&&ge)&&o.jsxs("div",{className:"guake-handle",onClick:()=>{ot&&U.toggleTerminal()},onDoubleClick:()=>{ot||U.toggleTerminal()},style:{top:ot?`min(${L}%, calc(100vh - 72px))`:"0"},children:[o.jsx("span",{className:"guake-handle-icon",children:ot?"▲":"▼"}),o.jsx("span",{className:"guake-handle-text",children:S.name})]}),qe&&o.jsx(I6,{url:qe.url,name:qe.name,onClose:()=>it(null)}),he&&o.jsx(P6,{state:he,onClose:()=>Be(null)}),ie&&o.jsx(B6,{action:ie,selectedAgentId:T,subordinateCount:((mc=S==null?void 0:S.subordinateIds)==null?void 0:mc.length)||0,onClose:()=>de(null),onClearHistory:It.clearHistory}),o.jsx(F6,{}),o.jsx(z6,{}),o.jsx(U6,{agent:S,isOpen:ct,onClose:()=>fe(!1)}),!y&&o.jsx($6,{agent:S,content:He,onClose:()=>et(null)})]})});function sW(t){return t.trim().replace(/^v/i,"")}function YA(t){const n=sW(t).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!n)return null;const s=n[1].split(".").map(r=>Number.parseInt(r,10));if(s.some(Number.isNaN))return null;const a=n[2]?n[2].split("."):[];return{core:s,prerelease:a}}function aW(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;const n=Math.max(t.length,e.length);for(let s=0;s<n;s+=1){const a=t[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 rW(t,e){const n=YA(t),s=YA(e);if(!n||!s)return null;const a=Math.max(n.core.length,s.core.length);for(let r=0;r<a;r+=1){const i=n.core[r]??0,c=s.core[r]??0;if(i>c)return 1;if(i<c)return-1}return aW(n.prerelease,s.prerelease)}function iW(t,e){const n=rW(t,e);return n===null?"unknown":n<0?"behind":n>0?"ahead":"equal"}async function oW(t,e={}){const{timeoutMs:n=5e3,fetchImpl:s=fetch}=e;try{const a=new AbortController,r=setTimeout(()=>a.abort(),n),i=Date.now(),c=await s(`https://registry.npmjs.org/${encodeURIComponent(t)}/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 lW(t,e,n={}){const s=await oW(t,n);return s?{currentVersion:e,latestVersion:s,relation:iW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const cW="tide-commander",Mb="1.37.2";function uW(){const[t,e]=x.useState({currentVersion:Mb,latestVersion:null,relation:"unknown",isChecking:!1}),n=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await lW(cW,Mb);e({currentVersion:Mb,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return x.useEffect(()=>{n()},[n]),{...t,refresh:n}}const dW=x.memo(function({agent:e,currentIndex:n,agentIndex:s,isTouchInput:a,isTouchDragEnabled:r,isSelected:i,hasUnseenOutput:c,isDragging:d,isDragOver:f,customClasses:h,onDragStart:m,onDragEnd:b,onDragOver:y,onDragEnter:w,onDragLeave:C,onDrop:N,onAgentClick:k,onAgentDoubleClick:j,onTouchStart:S,onTouchMove:T,onTouchEnd:D,onTouchCancel:E,onHoverEnter:I,onHoverLeave:O,onItemRef:_}){const M=x.useMemo(()=>fr(e.class,h),[e.class,h]),R=!a||r,z=x.useCallback($=>{_(e.id,$)},[e.id,_]);return o.jsxs("div",{ref:z,className:`agent-bar-item ${i?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${d?"dragging":""} ${f?"drag-over":""} ${r?"touch-drag-enabled":""}`,draggable:R,onDragStart:$=>m($,e),onDragEnd:b,onDragOver:$=>y($,s),onDragEnter:$=>w($,s),onDragLeave:C,onDrop:$=>N($,s),onTouchStart:$=>S($,e.id),onTouchMove:T,onTouchEnd:D,onTouchCancel:E,onClick:$=>k(e,$),onDoubleClick:()=>j(e),onMouseEnter:()=>I(e),onMouseLeave:O,title:a?`${e.name} (${n+1}) - Long press to reorder`:`${e.name} (${n+1}) - Drag to reorder within group`,children:[o.jsxs("div",{className:"agent-bar-avatar",children:[o.jsx("span",{className:"agent-bar-icon",children:M.icon}),o.jsx("span",{className:"agent-bar-status",style:{backgroundColor:_x(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:Tx(e.lastActivity)},title:Ex(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${n+1}`,children:["^",n+1]})]})}),fW=x.memo(function({onFocusAgent:e,onSpawnClick:n,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=dt(["common"]),c=ed(),d=ur(),f=$x(),h=HO(),m=Ux(),b=Vr(),y=dr(),w=l1(),[C]=Bj(),[N,k]=x.useState(!1);Mj("AgentBar");const j=x.useRef(null),S=x.useRef(null),T=x.useRef(null),D=x.useRef(new Map);x.useEffect(()=>{{k(!1);return}},[b.experimental2DView]),x.useEffect(()=>{const we=S.current;if(!we)return;const Fe=Ke=>{we.scrollWidth<=we.clientWidth||(Ke.preventDefault(),Math.abs(Ke.deltaX)>Math.abs(Ke.deltaY)?we.scrollLeft+=Ke.deltaX:we.scrollLeft+=Ke.deltaY)};return we.addEventListener("wheel",Fe,{passive:!1}),()=>we.removeEventListener("wheel",Fe)},[]);const[E,I]=x.useState(null),[O,_]=x.useState(new Map),[M,R]=x.useState(null),[z,$]=x.useState(null),W=x.useRef(0),[L,F]=x.useState(null),H=x.useRef(null),V=x.useRef(null),G=x.useRef(null),B=x.useRef(null),K=350,ne=8,q=x.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),xe=x.useMemo(()=>Array.from(c.values()).filter(we=>{if(U.isAgentInArchivedArea(we.id))return!1;if(C){const Fe=U.getAreaForAgent(we.id);if(!Fx((Fe==null?void 0:Fe.id)??null))return!1}return!0}).sort((we,Fe)=>(we.createdAt||0)-(Fe.createdAt||0)),[c,d,C]),{orderedAgents:Ae,moveAgent:Z}=hO(xe),ce=Ae,me=x.useMemo(()=>{const we=new Map;for(const Fe of ce)we.set(Fe.id,U.getAreaForAgent(Fe.id));return we},[ce,d]),ee=x.useMemo(()=>{const we=new Map;for(const Ke of ce){const st=me.get(Ke.id)||null,ft=(st==null?void 0:st.id)||null;we.has(ft)||we.set(ft,{area:st,agents:[]}),we.get(ft).agents.push(Ke)}const Fe=Array.from(we.values());return Fe.sort((Ke,st)=>{var ft,wt;return!Ke.area&&st.area?1:Ke.area&&!st.area?-1:!Ke.area&&!st.area?0:(((ft=Ke.area)==null?void 0:ft.name)||"").localeCompare(((wt=st.area)==null?void 0:wt.name)||"")}),Fe},[ce,me]),re=x.useRef(e);re.current=e;const We=x.useRef(M);We.current=M;const ze=x.useRef(ce);ze.current=ce;const Pe=x.useRef(me);Pe.current=me;const ge=x.useRef(Z);ge.current=Z,x.useEffect(()=>{const we=new Map(O);let Fe=!1;for(const Ke of ce){const st=O.get(Ke.id);Ke.currentTool?(!st||st.tool!==Ke.currentTool)&&(we.set(Ke.id,{tool:Ke.currentTool,key:Date.now()}),Fe=!0):st&&setTimeout(()=>{_(ft=>{const wt=new Map(ft);return wt.delete(Ke.id),wt})},1500)}Fe&&_(we)},[ce.map(we=>we.currentTool).join(",")]),x.useEffect(()=>{const we=h;if(!we)return;const Fe=D.current.get(we),Ke=S.current;Fe&&Ke&&requestAnimationFrame(()=>{const st=Fe.getBoundingClientRect(),ft=Ke.getBoundingClientRect(),rt=st.left-ft.left+Ke.scrollLeft+st.width/2,gt=Ke.clientWidth;Ke.scrollTo({left:rt-gt/2,behavior:"smooth"})})},[h]);const Te=x.useCallback((we,Fe)=>{if(G.current===we.id){G.current=null,Fe.preventDefault(),Fe.stopPropagation();return}U.setLastSelectionViaDirectClick(!0),Fe.shiftKey?U.addToSelection(we.id):U.selectAgent(we.id),U.setTerminalOpen(!0)},[]),qe=x.useCallback(we=>{var Fe;(Fe=re.current)==null||Fe.call(re,we.id),U.setTerminalOpen(!0)},[]),it=x.useCallback(()=>I(null),[]),he=x.useCallback((we,Fe)=>{Fe?D.current.set(we,Fe):D.current.delete(we)},[]),Be=x.useCallback((we,Fe)=>{R(Fe),F(Fe.id),we.dataTransfer.effectAllowed="move",we.dataTransfer.setData("text/plain",Fe.id),requestAnimationFrame(()=>{we.target.classList.add("dragging")})},[]),ie=x.useCallback(we=>{R(null),$(null),F(null),W.current=0,we.target.classList.remove("dragging")},[]),de=x.useCallback((we,Fe)=>{we.preventDefault();const Ke=We.current;if(Ke){const st=Pe.current.get(Ke.id),ft=ze.current[Fe],wt=ft?Pe.current.get(ft.id):null,rt=(st==null?void 0:st.id)??null,gt=(wt==null?void 0:wt.id)??null;we.dataTransfer.dropEffect=rt===gt?"move":"none"}else we.dataTransfer.dropEffect="move"},[]),He=x.useCallback((we,Fe)=>{we.preventDefault(),W.current++;const Ke=We.current;if(Ke){const st=Pe.current.get(Ke.id),ft=ze.current[Fe],wt=ft?Pe.current.get(ft.id):null,rt=(st==null?void 0:st.id)??null,gt=(wt==null?void 0:wt.id)??null;$(rt===gt?Fe:null)}else $(Fe)},[]),et=x.useCallback(we=>{W.current--,W.current===0&&$(null)},[]),ct=x.useCallback((we,Fe)=>{we.preventDefault();const Ke=We.current;if(!Ke)return;const st=ze.current,ft=Pe.current,wt=st.findIndex(rt=>rt.id===Ke.id);if(wt!==-1&&wt!==Fe){const rt=ft.get(Ke.id),gt=st[Fe],ht=gt?ft.get(gt.id):null,Gt=(rt==null?void 0:rt.id)??null,tn=(ht==null?void 0:ht.id)??null;Gt===tn&&ge.current(wt,Fe)}R(null),$(null),F(null),W.current=0},[]),fe=x.useCallback(()=>{H.current&&(clearTimeout(H.current),H.current=null)},[]),X=x.useCallback(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),se=x.useCallback((we,Fe)=>{if(!q||we.touches.length!==1)return;fe(),X(),F(null);const Ke=we.touches[0];V.current={agentId:Fe,x:Ke.clientX,y:Ke.clientY},H.current=setTimeout(()=>{F(Fe),G.current=Fe,H.current=null},K)},[fe,X,q]),Se=x.useCallback(we=>{if(!q||we.touches.length!==1)return;const Fe=V.current;if(!Fe||!H.current)return;const Ke=we.touches[0],st=Ke.clientX-Fe.x,ft=Ke.clientY-Fe.y;Math.sqrt(st*st+ft*ft)>ne&&(fe(),V.current=null)},[fe,q]),J=x.useCallback(()=>{fe(),V.current=null,We.current||F(null),X(),B.current=setTimeout(()=>{G.current=null,B.current=null},450)},[fe,X]);x.useEffect(()=>()=>{fe(),X()},[fe,X]);const pe=we=>{const Fe=`common:status.${we}`;return i(Fe,{defaultValue:i("common:status.unknown")})},{currentVersion:Re,latestVersion:$e,relation:ye,isChecking:Ie}=uW(),te=Re;let be=0;return o.jsxs("div",{className:"agent-bar",ref:j,children:[o.jsxs("div",{className:"agent-bar-scroll",ref:S,children:[o.jsxs("div",{className:"agent-bar-version",title:$e?`Tide Commander v${te} (npm: v${$e})`:`Tide Commander v${te}`,children:[o.jsxs("span",{children:["v",te]}),ye==="behind"&&$e?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${$e}`,children:["npm v",$e]}):ye==="ahead"&&$e?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${$e}`,children:["npm v",$e]}):null,ye==="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)"})}):ye==="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)"})}):ye==="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")}):Ie?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(os,{content:"Refresh 3D Scene (HMR changes pending)",position:"bottom",children:o.jsx("button",{className:"agent-bar-hmr-refresh",onClick:Uj,children:"↻"})})]}),o.jsxs("div",{className:"agent-bar-list",ref:T,children:[o.jsx(os,{content:i("common:agentBar.spawnNewAgent"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn",onClick:n,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(os,{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(os,{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(os,{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")})]})}),ee.map(we=>{var st,ft,wt,rt,gt;const Fe=we.agents,Ke=!we.area;return o.jsxs("div",{className:`agent-bar-group ${Ke?"unassigned":""}`,style:{borderColor:((st=we.area)==null?void 0:st.color)||void 0,background:we.area?`${we.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:((ft=we.area)==null?void 0:ft.color)||"#888"},children:((wt=we.area)==null?void 0:wt.name)||i("common:agentBar.unassigned")})}),((rt=we.area)==null?void 0:rt.directories)&&we.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:we.area.directories.map((ht,Gt)=>o.jsxs("div",{className:"agent-bar-folder-item",onClick:tn=>{tn.stopPropagation(),U.openFileExplorer(ht)},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:ht}),o.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},Gt))}),Fe.map(ht=>{const Gt=be++,tn=ce.findIndex(je=>je.id===ht.id);return o.jsx(dW,{agent:ht,currentIndex:Gt,agentIndex:tn,isTouchInput:q,isTouchDragEnabled:L===ht.id,isSelected:f.has(ht.id),hasUnseenOutput:w.has(ht.id),isDragging:(M==null?void 0:M.id)===ht.id,isDragOver:z===tn,customClasses:y,onDragStart:Be,onDragEnd:ie,onDragOver:de,onDragEnter:He,onDragLeave:et,onDrop:ct,onAgentClick:Te,onAgentDoubleClick:qe,onTouchStart:se,onTouchMove:Se,onTouchEnd:J,onTouchCancel:J,onHoverEnter:I,onHoverLeave:it,onItemRef:he},ht.id)})]},((gt=we.area)==null?void 0:gt.id)||"unassigned")})]})]}),Array.from(O.entries()).map(([we,Fe])=>{const Ke=D.current.get(we);if(!Ke)return null;const st=Ke.getBoundingClientRect(),ft=fs[Fe.tool]||fs.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:Fe.tool,style:{position:"fixed",left:st.left+st.width/2,bottom:window.innerHeight-st.top+8},children:[o.jsx("span",{className:"agent-bar-tool-icon",children:ft}),o.jsx("span",{className:"agent-bar-tool-name",children:Fe.tool})]},`tool-${we}-${Fe.key}`)}),E&&(()=>{const we=U.getAreaForAgent(E.id),Fe=m.get(E.id),Ke=fr(E.class,y),st=U.getAgentSupervisorHistory(E.id),ft=st.length>0?st[st.length-1]:void 0,wt=Date.now()-(E.createdAt||Date.now()),rt=Math.floor(wt/6e4),gt=Math.floor(rt/60),ht=gt>0?`${gt}h ${rt%60}m`:`${rt}m`,Gt=Ze=>Ze>=1e6?`${(Ze/1e6).toFixed(1)}M`:Ze>=1e3?`${(Ze/1e3).toFixed(1)}K`:Ze.toString(),tn=E.contextLimit>0?Math.round(E.contextUsed/E.contextLimit*100):0,je=Ze=>{switch(Ze){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Oe=D.current.get(E.id),Ye={};if(Oe){const Ze=Oe.getBoundingClientRect();Ye.position="fixed",Ye.left=Ze.left+Ze.width/2,Ye.bottom=window.innerHeight-Ze.top+12}return o.jsxs("div",{className:"agent-bar-tooltip",style:Ye,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:Ke.icon}),o.jsxs("span",{className:"agent-bar-tooltip-name",children:[o.jsx("img",{src:E.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:E.provider,className:"agent-bar-provider-icon",title:E.provider==="codex"?"Codex Agent":"Claude Agent"}),E.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:_x(E.status)},children:pe(E.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:[E.class," — ",Ke.description]})]}),we&&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:we.color},children:we.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:E.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:ht})]}),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:[Gt(E.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:tn>80?"#ff4a4a":tn>60?"#ff9e4a":void 0},children:[Gt(E.contextUsed)," / ",Gt(E.contextLimit)," (",tn,"%)"]})]}),E.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:[fs[E.currentTool]||fs.default," ",E.currentTool]})]}),E.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:E.taskLabel})]}),E.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:[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:[i("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?"...":""]})]}),Fe&&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:[Fe.text.substring(0,300),Fe.text.length>300?"...":""]})]}),ft&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"agent-bar-tooltip-divider"}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.supervisor"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",style:{color:je(ft.analysis.progress)},children:ft.analysis.progress.replace("_"," ")})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.status"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:ft.analysis.statusDescription})]}),ft.analysis.recentWorkSummary&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.summary"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[ft.analysis.recentWorkSummary.substring(0,300),ft.analysis.recentWorkSummary.length>300?"...":""]})]}),ft.analysis.concerns&&ft.analysis.concerns.length>0&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.concerns"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:ft.analysis.concerns.join("; ")})]})]})]})]})})()]})});function pW({activeTool:t,onExit:e}){const{t:n}=dt(["notifications","terminal"]);if(!t||t==="select")return null;const s=n(t==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=t==="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:[n("terminal:drawingMode.drawingArea"),": ",s]}),o.jsxs("span",{className:"drawing-mode-hint",children:[n("terminal:drawingMode.clickAndDrag")," • ",n("terminal:drawingMode.pressEscape")]})]})]}),o.jsx("button",{className:"drawing-mode-exit",onClick:e,title:n("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const hW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Db=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),mW=t=>{switch(t){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},gW=x.memo(function({agent:e,screenPos:n,onClose:s}){const{t:a}=dt(["common"]),r=dr(),i=U.getAreaForAgent(e.id),c=U.getState().lastPrompts.get(e.id),d=fr(e.class,r),f=U.getAgentSupervisorHistory(e.id),h=f.length>0?f[f.length-1]:void 0,m=Date.now()-(e.createdAt||Date.now()),b=Math.floor(m/6e4),y=Math.floor(b/60),w=y>0?`${y}h ${b%60}m`:`${b}m`,C=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,N=x.useMemo(()=>{let S=n.x-150,T=n.y-320-10;return typeof window<"u"&&(S<10?S=10:S+300>window.innerWidth-10&&(S=window.innerWidth-300-10),T<10&&(T=n.y+10)),{position:"fixed",left:S,top:T,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[n.x,n.y]);return o.jsxs("div",{className:"agent-hover-popup",style:N,onMouseLeave:s,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:d.icon}),o.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:_x(e.status)},children:a(hW[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:w})]}),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:[Db(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:C>80?"#ff4a4a":C>60?"#ff9e4a":void 0},children:[Db(e.contextUsed)," / ",Db(e.contextLimit)," (",C,"%)"]})]}),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:[fs[e.currentTool]||fs.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?"...":""]})]}),h&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"agent-bar-tooltip-divider"}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.supervisor"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",style:{color:mW(h.analysis.progress)},children:h.analysis.progress.replace("_"," ")})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.status"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:h.analysis.statusDescription})]}),h.analysis.recentWorkSummary&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.summary"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[h.analysis.recentWorkSummary.substring(0,300),h.analysis.recentWorkSummary.length>300?"...":""]})]}),h.analysis.concerns&&h.analysis.concerns.length>0&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.concerns"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:h.analysis.concerns.join("; ")})]})]})]})]})});function GA(t){if(t===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,s)).toFixed(1))+" "+n[s]}function KA(t){const n=Date.now()-t,s=Math.floor(n/(1e3*60*60)),a=Math.floor(n%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const QA={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 bW(t){const e=[],n=/\x1B\[([0-9;]*)m/g;let s=0,a=null,r;for(;(r=n.exec(t))!==null;){if(r.index>s){const c=t.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:QA[c]&&(a=QA[c]);s=n.lastIndex}if(s<t.length){const i=t.slice(s);a?e.push(o.jsx("span",{style:{color:a},children:i},e.length)):e.push(i)}return e.length>0?e:[t]}const xW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var F,H,V,G,B,K,ne,q,xe,Ae,Z,ce,me,ee,re,We,ze,Pe,ge,Te;const{t:c}=dt(["terminal","common"]),[d,f]=x.useState(!1),[h,m]=x.useState(null),[b,y]=x.useState(!1),w=x.useRef(null),C=x.useRef(h);C.current=h;const{buildingLogs:N}=Rs(),k=U.getBuildingLogs(e.id),j=(F=e.pm2)==null?void 0:F.enabled,S=(H=e.docker)==null?void 0:H.enabled,T=x.useRef(null),D=x.useRef(null),E=x.useCallback(qe=>{qe.preventDefault();const it=C.current?C.current.x:0,he=C.current?C.current.y:0;w.current={mouseX:qe.clientX,mouseY:qe.clientY,popupX:it,popupY:he},y(!0),T.current=Be=>{if(!w.current)return;const ie=Be.clientX-w.current.mouseX,de=Be.clientY-w.current.mouseY;m({x:w.current.popupX+ie,y:w.current.popupY+de})},D.current=()=>{y(!1),w.current=null,T.current&&document.removeEventListener("mousemove",T.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",T.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{T.current&&document.removeEventListener("mousemove",T.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const I=qe=>{if(qe==="logs"){if((j||S)&&r){r();return}U.sendBuildingCommand(e.id,qe),f(!0)}else U.sendBuildingCommand(e.id,qe)},O=(qe,it)=>{if(qe){const he=`http://localhost:${qe}`;it&&i?i(he):window.open(he,"_blank")}},_=((V=e.pm2Status)==null?void 0:V.ports)||[],M=((B=(G=e.dockerStatus)==null?void 0:G.ports)==null?void 0:B.map(qe=>qe.host))||[],R=j?_:S?M:[],z=j?!!((K=e.pm2)!=null&&K.script):S?!!((ne=e.docker)!=null&&ne.image)||((q=e.docker)==null?void 0:q.mode)==="compose"||((xe=e.docker)==null?void 0:xe.mode)==="existing":!!((Ae=e.commands)!=null&&Ae.start),$=j?!!((Z=e.pm2)!=null&&Z.script):S?!0:!!((ce=e.commands)!=null&&ce.stop),W=j?!!((me=e.pm2)!=null&&me.script):S?!0:!!((ee=e.commands)!=null&&ee.restart),L=x.useMemo(()=>{const it=d?400:250;let he=n.x+20,Be=n.y-80;return typeof window<"u"&&!h&&(n.x+20+280>window.innerWidth&&(he=n.x-280-20),n.y-80<0?Be=10:n.y-80+it>window.innerHeight&&(Be=window.innerHeight-it-10)),{position:"fixed",left:he+((h==null?void 0:h.x)||0),top:Be+((h==null?void 0:h.y)||0),zIndex:1e3,cursor:b?"grabbing":void 0}},[n.x,n.y,d,h,b]);return o.jsxs("div",{className:"building-action-popup",style:L,onClick:qe=>qe.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header ${b?"dragging":""}`,onMouseDown:E,children:[o.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&o.jsx("span",{className:"building-popup-ports",children:R.map(qe=>o.jsxs("a",{href:`http://localhost:${qe}`,className:"building-popup-port-link",onClick:it=>{it.preventDefault(),it.stopPropagation(),O(qe,it.altKey)},onMouseDown:it=>it.stopPropagation(),title:`Open http://localhost:${qe} (Alt+Click for modal)`,children:[":",qe]},qe))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:qb[e.status]},children:e.status}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),j&&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:[((re=e.pm2Status.cpu)==null?void 0:re.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:GA(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:KA(e.pm2Status.uptime)})]})]}),S&&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:GA(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:KA(e.dockerStatus.startedAt)})]})]}),S&&((We=e.dockerStatus)==null?void 0:We.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((qe,it)=>o.jsxs("span",{className:"service-item",title:`${qe.name}: ${qe.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:qe.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:qe.name})]},it))}),(e.lastError||j&&((ze=e.pm2Status)==null?void 0:ze.status)==="errored"||S&&((Pe=e.dockerStatus)==null?void 0:Pe.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),j&&((ge=e.pm2Status)==null?void 0:ge.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),S&&((Te=e.dockerStatus)==null?void 0:Te.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:()=>I("start"),disabled:!z||e.status==="running"||e.status==="starting",title:c(z?"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:()=>I("stop"),disabled:!$||e.status==="stopped"||e.status==="stopping",title:c($?"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:()=>I("restart"),disabled:!W,title:c(W?"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:()=>I("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:qe=>O(R[0],qe.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(qe=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:it=>O(qe,it.altKey),title:`Open http://localhost:${qe} (Alt+Click for modal)`,children:[":",qe]},qe))]})]}),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:()=>U.clearBuildingLogs(e.id),children:c("terminal:logs.clear")})]}),o.jsx("div",{className:"logs-content",children:k.slice(-50).map((qe,it)=>o.jsx("pre",{children:bW(qe)},it))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function yW(t){if(t===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,s)).toFixed(1))+" "+n[s]}function vW(t){const n=Date.now()-t,s=Math.floor(n/(1e3*60*60)),a=Math.floor(n%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const wW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){const{t:c}=dt(["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:w}=Rs(),N=(e.subordinateBuildingIds||[]).map(_=>w.get(_)).filter(_=>_!==void 0),k=x.useRef(null),j=x.useRef(null),S=x.useCallback(_=>{_.preventDefault();const M=y.current?y.current.x:0,R=y.current?y.current.y:0;b.current={mouseX:_.clientX,mouseY:_.clientY,popupX:M,popupY:R},m(!0),k.current=z=>{if(!b.current)return;const $=z.clientX-b.current.mouseX,W=z.clientY-b.current.mouseY;f({x:b.current.popupX+$,y:b.current.popupY+W})},j.current=()=>{m(!1),b.current=null,k.current&&document.removeEventListener("mousemove",k.current),j.current&&document.removeEventListener("mouseup",j.current)},document.addEventListener("mousemove",k.current),document.addEventListener("mouseup",j.current)},[]);x.useEffect(()=>()=>{k.current&&document.removeEventListener("mousemove",k.current),j.current&&document.removeEventListener("mouseup",j.current)},[]);const T=_=>{U.sendBossBuildingCommand(e.id,_)},D=N.reduce((_,M)=>(_[M.status]=(_[M.status]||0)+1,_),{}),E=N.some(_=>{var M;return(M=_.pm2)==null?void 0:M.enabled}),I=(_,M)=>{const R=`http://localhost:${_}`;M&&i?i(R):window.open(R,"_blank")},O=x.useMemo(()=>{let R=n.x+20,z=n.y-80;return typeof window<"u"&&!d&&(n.x+20+340>window.innerWidth&&(R=n.x-340-20),n.y-80<0?z=10:n.y-80+350>window.innerHeight&&(z=window.innerHeight-350-10)),{position:"fixed",left:R+((d==null?void 0:d.x)||0),top:z+((d==null?void 0:d.y)||0),zIndex:1e3,cursor:h?"grabbing":void 0}},[n.x,n.y,d,h]);return o.jsxs("div",{className:"building-action-popup boss-building-popup",style:O,onClick:_=>_.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header boss-header ${h?"dragging":""}`,onMouseDown:S,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(([_,M])=>o.jsxs("span",{className:"status-badge",style:{backgroundColor:qb[_]||"#666"},children:[M," ",_]},_)),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(_=>{var M,R,z;return o.jsxs("div",{className:"subordinate-item",children:[o.jsx("span",{className:"sub-status-dot",style:{backgroundColor:qb[_.status]}}),o.jsx("span",{className:"sub-name",children:_.name}),((M=_.pm2Status)==null?void 0:M.ports)&&_.pm2Status.ports.length>0&&o.jsx("span",{className:"sub-port",children:_.pm2Status.ports.map($=>o.jsxs("a",{href:`http://localhost:${$}`,className:"building-popup-port-link",onClick:W=>{W.preventDefault(),W.stopPropagation(),I($,W.altKey)},title:`Open http://localhost:${$} (Alt+Click for modal)`,children:[":",$]},$))}),_.pm2Status&&o.jsxs("span",{className:"sub-metrics",children:[(R=_.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",yW(_.pm2Status.memory||0)]}),((z=_.pm2Status)==null?void 0:z.uptime)&&o.jsx("span",{className:"sub-uptime",children:vW(_.pm2Status.uptime)})]},_.id)})}),o.jsxs("div",{className:"building-popup-actions boss-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>T("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:()=>T("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:()=>T("restart_all"),disabled:N.length===0,title:c("terminal:building.restartAllSubs"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:building.restartAll")]}),E&&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")})]})}),kW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenDatabasePanel:r}){var D;const{t:i}=dt(["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=Yx(e.id),w=((D=e.database)==null?void 0:D.connections)??[],C=x.useRef(null),N=x.useRef(null),k=x.useCallback(E=>{E.preventDefault();const I=b.current?b.current.x:0,O=b.current?b.current.y:0;m.current={mouseX:E.clientX,mouseY:E.clientY,popupX:I,popupY:O},h(!0),C.current=_=>{if(!m.current)return;const M=_.clientX-m.current.mouseX,R=_.clientY-m.current.mouseY;d({x:m.current.popupX+M,y:m.current.popupY+R})},N.current=()=>{h(!1),m.current=null,C.current&&document.removeEventListener("mousemove",C.current),N.current&&document.removeEventListener("mouseup",N.current)},document.addEventListener("mousemove",C.current),document.addEventListener("mouseup",N.current)},[]);x.useEffect(()=>()=>{C.current&&document.removeEventListener("mousemove",C.current),N.current&&document.removeEventListener("mouseup",N.current)},[]);const j=E=>{U.testDatabaseConnection(e.id,E)},S=E=>y.connectionStatus.get(E),T=x.useMemo(()=>{let O=n.x+20,_=n.y-80;return typeof window<"u"&&!c&&(n.x+20+320>window.innerWidth&&(O=n.x-320-20),n.y-80<0?_=10:n.y-80+300>window.innerHeight&&(_=window.innerHeight-300-10)),{position:"fixed",left:O+((c==null?void 0:c.x)||0),top:_+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[n.x,n.y,c,f]);return o.jsxs("div",{className:"building-action-popup database-building-popup",style:T,onClick:E=>E.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:w.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),w.length>0?o.jsx("div",{className:"database-connection-list",children:w.map(E=>{var O;const I=S(E.id);return o.jsxs("div",{className:"database-connection-item",children:[o.jsx("span",{className:"conn-engine",children:((O=vL[E.engine])==null?void 0:O.icon)??"🗄️"}),o.jsx("span",{className:"conn-name",children:E.name}),o.jsx("span",{className:"conn-host",children:E.engine==="sqlite"?E.filepath||E.database||":memory:":`${E.host}:${E.port}`}),I&&o.jsx("span",{className:`conn-status ${I.connected?"connected":"disconnected"}`,children:I.connected?"●":"○"}),o.jsx("button",{className:"conn-test-btn",onClick:()=>j(E.id),title:i("terminal:building.testConnection"),children:"↻"})]},E.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:w.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:()=>w.forEach(E=>j(E.id)),disabled:w.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 SW({visible:t=!0,position:e="top-right"}){const[n,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),[w,C]=x.useState(!1),[N,k]=x.useState("fps"),[j,S]=x.useState(null),[T,D]=x.useState(null),[E,I]=x.useState(null),[O,_]=x.useState(typeof window<"u"?window.innerWidth:1024),[M,R]=x.useState(null);x.useEffect(()=>{const Z=()=>_(window.innerWidth);return window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]);const z=Kp(),$=x.useMemo(()=>{const Z=z.filter(me=>me.memoryUsageMB!==void 0&&me.memoryUsageMB>0);return{totalMB:Z.reduce((me,ee)=>me+(ee.memoryUsageMB||0),0),agentCount:Z.length,agents:Z.map(me=>({name:me.name,memoryMB:me.memoryUsageMB||0,status:me.status})).sort((me,ee)=>ee.memoryMB-me.memoryMB)}},[z]),W=x.useRef([]),L=x.useRef(null);if(x.useEffect(()=>{W.current=d},[d]),x.useEffect(()=>{L.current=h},[h]),x.useEffect(()=>{if(!t)return;const Z=async()=>{try{const me=await Bt(Rt("/api/perf"));if(me.ok){const ee=await me.json();D(ee)}}catch{}};Z();const ce=setInterval(Z,w?3e3:1e4);return()=>clearInterval(ce)},[t,w]),x.useEffect(()=>{if(!t)return;const Z=su.getUsage();Z&&M===null&&R(Z.usedMB);const ce=setInterval(()=>{var it,he;Nf.update();const me=Nf.getStats();s(me.current),r(Be=>[...Be,me.current].slice(-60));const ee=su.getUsage();ee&&c(ee);const re=window.__tideScene;if(re){const Be=(it=re.getMemoryDiagnostics)==null?void 0:it.call(re);Be!=null&&Be.threeJs&&m(Be.threeJs);const ie=re.renderer;if((he=ie==null?void 0:ie.info)!=null&&he.memory){const de=ie.info.memory.textures||0,He=Math.round(de*1);I({count:de,estimatedMB:He})}}const We=document.getElementsByTagName("*"),ze=document.getElementsByTagName("canvas"),Pe=document.getElementsByTagName("img"),ge=document.getElementsByTagName("video");let Te=0;for(let Be=0;Be<Math.min(We.length,500);Be++){const ie=We[Be];ie.onclick&&Te++,ie.onmousedown&&Te++,ie.onkeydown&&Te++}Te+=10,S({nodeCount:We.length,listenerCount:Te,canvasCount:ze.length,imageCount:Pe.length,videoCount:ge.length}),ee&&f(Be=>{const ie=L.current,de={timestamp:Date.now(),heapMB:ee.usedMB,geometries:(ie==null?void 0:ie.geometries)??0,textures:(ie==null?void 0:ie.textures)??0};return[...Be,de].slice(-120)});const qe=W.current;if(qe.length>=10){const Be=qe[0],ie=qe[qe.length-1],de=(ie.timestamp-Be.timestamp)/1e3/60;de>.1&&y((ie.heapMB-Be.heapMB)/de)}},1e3);return()=>{clearInterval(ce)}},[t,M]),!t)return null;const F=Z=>{const ce=Math.floor(Z/3600),me=Math.floor(Z%3600/60),ee=Z%60;return ce>0?`${ce}h ${me}m`:me>0?`${me}m ${ee}s`:`${ee}s`},H=Z=>Z>=55?"#4aff9e":Z>=30?"#ffcc00":"#ff4a4a",V=(Z,ce)=>{const me=Z/ce;return me<.5?"#4aff9e":me<.8?"#ffcc00":"#ff4a4a"},G=Z=>Z===null?"#888":Z<1?"#4aff9e":Z<5?"#ffcc00":"#ff4a4a",B=Nf.getStats(),ne=O<=768?80:10,q={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:ne,left:10},"bottom-right":{bottom:ne,right:10}},xe=M&&i?i.usedMB-M:0,Ae=Z=>({padding:"2px 8px",fontSize:"9px",border:"none",background:N===Z?"rgba(74, 158, 255, 0.4)":"rgba(255, 255, 255, 0.1)",color:N===Z?"#4a9eff":"#888",borderRadius:"3px",cursor:"pointer"});return o.jsxs("div",{style:{position:"fixed",...q[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:w?"260px":"120px",maxWidth:"calc(100vw - 20px)",maxHeight:w?"calc(100vh - 100px)":"auto",overflowY:w?"auto":"visible",transition:"all 0.2s ease"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:()=>C(!w),children:[o.jsx("span",{style:{color:H(n),fontWeight:"bold",fontSize:"14px"},children:n}),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:V(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:G(b),fontSize:"10px",marginLeft:"4px"},children:[b>0?"+":"",b.toFixed(1),"/m"]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:"#ff9e4a",fontWeight:"bold"},children:T.process.rssMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"SRV"})]}),o.jsx("span",{style:{color:"#444",marginLeft:"auto",fontSize:"10px"},children:w?"▼":"▶"})]}),w&&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:Ae("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:Ae("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:Ae("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:Ae("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:Ae("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:Ae("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:H(B.current)},children:B.current}),o.jsx("span",{style:{color:"#888"},children:"Min:"}),o.jsx("span",{style:{color:H(B.min)},children:B.min}),o.jsx("span",{style:{color:"#888"},children:"Max:"}),o.jsx("span",{style:{color:H(B.max)},children:B.max}),o.jsx("span",{style:{color:"#888"},children:"Avg:"}),o.jsx("span",{style:{color:H(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((Z,ce)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,Z/60*100)}%`,background:H(Z),opacity:.8}},ce))})]})]}),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:V(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:xe>50?"#ff4a4a":xe>20?"#ffcc00":"#4aff9e"},children:[xe>0?"+":"",xe," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Rate:"}),o.jsx("span",{style:{color:G(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:V(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((Z,ce)=>{const me=Math.min(...d.map(ze=>ze.heapMB)),re=Math.max(...d.map(ze=>ze.heapMB))-me||1,We=(Z.heapMB-me)/re*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,We)}%`,background:Z.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${Z.heapMB}MB`},ce)})})]}),$.agentCount>0&&o.jsxs("div",{style:{marginTop:"8px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:["Agent Memory (",$.agentCount,"):"]}),o.jsxs("div",{style:{fontSize:"10px"},children:[o.jsxs("div",{style:{color:"#4aff9e",fontWeight:"bold",marginBottom:"2px"},children:["Total: ",$.totalMB,"MB"]}),o.jsx("div",{style:{maxHeight:"50px",overflowY:"auto"},children:$.agents.slice(0,4).map((Z,ce)=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:Z.status==="working"?"#4aff9e":"#666",maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis"},children:Z.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[Z.memoryMB,"MB"]})]},ce))})]})]}),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:["~",(E==null?void 0:E.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsxs("span",{style:{color:"#9e4aff"},children:["DOM (",(j==null?void 0:j.nodeCount.toLocaleString())??0," nodes)"]}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(((j==null?void 0:j.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+((E==null?void 0:E.estimatedMB)??0)+Math.round(((j==null?void 0:j.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((Z,ce)=>{const me=Math.max(...d.map(ee=>ee.textures))||1;return o.jsx("div",{style:{width:"3px",height:`${Z.textures/me*100}%`,background:"#ff9e4a",opacity:.8},title:`${Z.textures} textures`},ce)})})]}),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:j?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:j.nodeCount>5e3?"#ff4a4a":j.nodeCount>2e3?"#ffcc00":"#4aff9e"},children:j.nodeCount.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Canvases:"}),o.jsx("span",{style:{color:"#4a9eff"},children:j.canvasCount}),o.jsx("span",{style:{color:"#888"},children:"Images:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:j.imageCount}),o.jsx("span",{style:{color:"#888"},children:"Videos:"}),o.jsx("span",{style:{color:"#9e4aff"},children:j.videoCount})]}),E&&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:E.count}),o.jsx("span",{style:{color:"#888"},children:"Est. VRAM:"}),o.jsxs("span",{style:{color:E.estimatedMB>100?"#ff4a4a":"#4aff9e"},children:["~",E.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:["~",(E==null?void 0:E.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(j.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)+((E==null?void 0:E.estimatedMB)??0)+Math.round(j.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:T?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:F(T.uptime)}),o.jsx("span",{style:{color:"#888"},children:"Heap Used:"}),o.jsxs("span",{style:{color:T.process.heapUsedMB>500?"#ff4a4a":"#4aff9e"},children:[T.process.heapUsedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Heap Total:"}),o.jsxs("span",{children:[T.process.heapTotalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"RSS:"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[T.process.rssMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"External:"}),o.jsxs("span",{children:[T.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:T.system.loadAvg[0]>T.system.cpuCount?"#ff4a4a":"#4aff9e"},children:T.system.loadAvg.join(" ")}),o.jsx("span",{style:{color:"#888"},children:"CPUs:"}),o.jsx("span",{children:T.system.cpuCount}),o.jsx("span",{style:{color:"#888"},children:"Sys Memory:"}),o.jsxs("span",{children:[T.system.totalMemMB-T.system.freeMemMB," / ",T.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:T.websocket.clients}),o.jsx("span",{style:{color:"#888"},children:"Sent:"}),o.jsx("span",{children:T.websocket.messagesSent.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Received:"}),o.jsx("span",{children:T.websocket.messagesReceived.toLocaleString()})]})]}),T.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 (",T.agents.working,"w / ",T.agents.idle,"i / ",T.agents.total,"t):"]}),o.jsx("div",{style:{maxHeight:"80px",overflowY:"auto",fontSize:"10px"},children:T.agents.processes.map(Z=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:Z.status==="working"?"#4aff9e":Z.status==="idle"?"#888":"#ff4a4a",maxWidth:"100px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[Z.memoryMB!=null?`${Z.memoryMB}MB`:"—",Z.pid?` (${Z.pid})`:""]})]},Z.id))})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading server metrics..."})}),N==="http"&&o.jsx("div",{children:T?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:T.http.reqPerSec}),o.jsx("span",{style:{color:"#888"},children:"Avg Latency:"}),o.jsxs("span",{style:{color:T.http.avgLatencyMs>100?"#ff4a4a":T.http.avgLatencyMs>50?"#ffcc00":"#4aff9e"},children:[T.http.avgLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Max Latency:"}),o.jsxs("span",{style:{color:T.http.maxLatencyMs>500?"#ff4a4a":T.http.maxLatencyMs>200?"#ffcc00":"#4aff9e"},children:[T.http.maxLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Recent Reqs:"}),o.jsx("span",{children:T.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,T.http.avgLatencyMs/500*100)}%`,background:T.http.avgLatencyMs>100?"#ff4a4a":T.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:[T.process.cpuUser," ms"]}),o.jsx("span",{style:{color:"#888"},children:"CPU (system):"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:[T.process.cpuSystem," ms"]}),o.jsx("span",{style:{color:"#888"},children:"WS Clients:"}),o.jsx("span",{style:{color:"#4aff9e"},children:T.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:Z=>{Z.stopPropagation();const ce=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&ce.push("","--- Memory ---",`Heap Used: ${i.usedMB} MB`,`Heap Total: ${i.totalMB} MB`,`Heap Limit: ${i.limitMB} MB`,`Baseline: ${M??"N/A"} MB`,`Growth: ${xe>0?"+":""}${xe} MB`,`Growth Rate: ${b!==null?`${b.toFixed(2)} MB/min`:"N/A"}`),h&&ce.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),$.agentCount>0&&(ce.push("","--- Agent Memory ---",`Total: ${$.totalMB} MB`,`Agents: ${$.agentCount}`),$.agents.slice(0,5).forEach(ee=>{ce.push(` ${ee.name}: ${ee.memoryMB} MB (${ee.status})`)})),j&&ce.push("","--- DOM ---",`DOM Nodes: ${j.nodeCount.toLocaleString()}`,`Canvases: ${j.canvasCount}`,`Images: ${j.imageCount}`,`Videos: ${j.videoCount}`),E&&ce.push("","--- Estimated Memory ---",`GPU Textures: ${E.count}`,`Est. VRAM: ~${E.estimatedMB} MB`,`Est. DOM: ~${Math.round(((j==null?void 0:j.nodeCount)??0)*.5/1024)} MB`,`Est. Total: ~${((i==null?void 0:i.usedMB)??0)+E.estimatedMB+Math.round(((j==null?void 0:j.nodeCount)??0)*.5/1024)} MB`),T&&(ce.push("","--- Server ---",`Uptime: ${F(T.uptime)}`,`Heap: ${T.process.heapUsedMB}/${T.process.heapTotalMB} MB`,`RSS: ${T.process.rssMB} MB`,`Load Avg: ${T.system.loadAvg.join(" ")}`,`System Memory: ${T.system.totalMemMB-T.system.freeMemMB}/${T.system.totalMemMB} MB`,"","--- WebSocket ---",`Clients: ${T.websocket.clients}`,`Sent: ${T.websocket.messagesSent}`,`Received: ${T.websocket.messagesReceived}`,"","--- HTTP ---",`Req/sec: ${T.http.reqPerSec}`,`Avg Latency: ${T.http.avgLatencyMs} ms`,`Max Latency: ${T.http.maxLatencyMs} ms`),T.agents.processes.length>0&&(ce.push("","--- Agent Processes ---",`Total: ${T.agents.total} (${T.agents.working} working, ${T.agents.idle} idle)`),T.agents.processes.forEach(ee=>{ce.push(` ${ee.name}: ${ee.memoryMB!=null?`${ee.memoryMB}MB`:"N/A"} (${ee.status})${ee.pid?` PID:${ee.pid}`:""}`)})));const me=ce.join(`
152
- `);navigator.clipboard.writeText(me).then(()=>{const ee=Z.currentTarget,re=ee.textContent;ee.textContent="Copied!",setTimeout(()=>{ee.textContent=re},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:Z=>{Z.stopPropagation(),su.report();const ce=window.__tideScene;ce!=null&&ce.logMemoryDiagnostics&&ce.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:Z=>{Z.stopPropagation(),Xb.clear(),Nf.reset(),su.reset(),r([]),f([]);const ce=su.getUsage();ce&&R(ce.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 CW(){const t=o1(),e=x.useCallback(n=>{U.setViewMode(n)},[]);return[t,e]}const AW=["3d","2d","dashboard"],jW=x.memo(function({className:e=""}){const{t:n}=dt(["common"]),[s,a]=CW(),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}}),AW.map(f=>o.jsxs("button",{className:`view-mode-toggle__btn ${s===f?"view-mode-toggle__btn--active":""}`,onClick:()=>d(f),title:n(`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:n(`common:viewMode.labels.${f}`)})]},f))]})});function JT({className:t}){const{t:e}=dt(["terminal"]),[n,s]=x.useState(!1),[a,r]=x.useState(null),i=My(),c=x.useCallback(async y=>{if(y.trim()){console.log("[VoiceAssistant] Transcribed:",y),s(!0),r(null);try{const C=await(await Bt(Rt("/api/voice-assistant/process"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:y})})).json();if(C.success&&C.response)console.log("[VoiceAssistant] Response:",C.response),i.speak(C.response);else{const N=C.error||e("terminal:voiceAssistant.failedToProcess");console.error("[VoiceAssistant] Error:",N),r(N),i.speak(N)}}catch(w){console.error("[VoiceAssistant] Request failed:",w);const C=e("terminal:voiceAssistant.unavailable");r(C),i.speak(C)}finally{s(!1)}}},[i]),d=UT({language:"Spanish",model:"medium",onTranscription:c}),f=d.recording||d.transcribing||n||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"):n?e("terminal:voiceAssistant.processing"):i.speaking?e("terminal:voiceAssistant.speaking"):e("terminal:voiceAssistant.title"),m=()=>{const y=["voice-assistant-btn",t].filter(Boolean);return d.recording&&y.push("recording"),(d.transcribing||n)&&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||n||d.toggleRecording()};return o.jsxs("button",{className:m(),onClick:b,title:d.supported?h():e("terminal:voiceAssistant.notSupported"),disabled:!d.supported||d.transcribing||n,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 NW=x.memo(function({isOpen:e,onToggle:n,onShowTerminal:s,onOpenSidebar:a,onOpenToolbox:r,onOpenCommander:i,onOpenSupervisor:c,onOpenControls:d,onOpenSkills:f,onOpenSnapshots:h,onTakeSnapshot:m,canTakeSnapshot:b,mobileView:y}){const{t:w}=dt(["terminal","common"]),C=Vr(),N=k=>{k(),n()};return o.jsxs(o.Fragment,{children:[C.experimentalVoiceAssistant&&o.jsx(JT,{className:"mobile-voice-assistant"}),y!=="terminal"&&o.jsx("button",{className:`mobile-fab-toggle ${e?"open":""}`,onClick:n,onTouchStart:k=>k.stopPropagation(),title:w(e?"terminal:mobileFab.closeMenu":"terminal:mobileFab.openMenu"),children:e?"✕":"☰"}),y==="3d"&&o.jsxs("div",{className:`mobile-fab-menu ${e?"open":""}`,children:[o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(s),onTouchEnd:k=>{k.preventDefault(),N(s)},title:w("terminal:mobileFab.showTerminal"),children:"💬"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(a),onTouchEnd:k=>{k.preventDefault(),N(a)},title:w("terminal:header.openSidebar"),children:"📋"}),b&&o.jsx("button",{className:"mobile-fab-option mobile-fab-option--highlight",onClick:()=>N(m),onTouchEnd:k=>{k.preventDefault(),N(m)},title:w("terminal:mobileFab.takeSnapshot"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(r),onTouchEnd:k=>{k.preventDefault(),N(r)},title:w("common:floatingButtons.settingsAndTools"),children:"⚙️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(i),onTouchEnd:k=>{k.preventDefault(),N(i)},title:w("common:floatingButtons.commanderView"),children:"📊"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(c),onTouchEnd:k=>{k.preventDefault(),N(c)},title:w("common:floatingButtons.supervisorOverview"),children:"🎖️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(d),onTouchEnd:k=>{k.preventDefault(),N(d)},title:w("common:floatingButtons.controls"),children:"⌨️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(f),onTouchEnd:k=>{k.preventDefault(),N(f)},title:w("common:floatingButtons.manageSkills"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(h),onTouchEnd:k=>{k.preventDefault(),N(h)},title:w("common:floatingButtons.viewSnapshots"),children:"📸"})]})]})}),TW=x.memo(function({onOpenToolbox:e,onOpenCommander:n,onOpenSupervisor:s,onOpenControls:a,onOpenSkills:r,onOpenSnapshots:i,isGeneratingReport:c,pip:d}){const{t:f}=dt(["common","terminal"]),h=Vr();return o.jsxs(o.Fragment,{children:[h.experimentalVoiceAssistant&&o.jsx(JT,{}),o.jsx(os,{content:f("common:floatingButtons.settingsAndTools"),position:"left",children:o.jsx("button",{className:"floating-settings-btn",onClick:e,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(os,{content:f("common:floatingButtons.commanderView"),position:"left",children:o.jsx("button",{className:"commander-toggle-btn",onClick:n,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(os,{content:f("common:floatingButtons.viewSnapshots"),position:"left",children:o.jsx("button",{className:"snapshots-toggle-btn",onClick:i,children:"📸"})}),o.jsx(os,{content:f(c?"terminal:supervisor.generating":"common:floatingButtons.supervisorOverview"),position:"left",children:o.jsxs("button",{className:`supervisor-toggle-btn ${c?"generating":""}`,onClick:s,children:["🎖️",c&&o.jsx("span",{className:"supervisor-generating-indicator"})]})}),o.jsx(os,{content:f("common:floatingButtons.controls"),position:"left",children:o.jsx("button",{className:"shortcuts-toggle-btn",onClick:a,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(os,{content:f("common:floatingButtons.manageSkills"),position:"left",children:o.jsx("button",{className:"skills-toggle-btn",onClick:r,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(os,{content:d.isSupported?d.isOpen?f("common:floatingButtons.closePip"):f("common:floatingButtons.openPip"):f("common:floatingButtons.pipNotSupported"),position:"left",disabled:!d.isSupported,children:o.jsx("button",{className:`pip-toggle-btn ${d.isOpen?"active":""}`,onClick:()=>d.isSupported&&d.toggle({width:320,height:400}),disabled:!d.isSupported,children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),o.jsx("rect",{x:"12",y:"9",width:"8",height:"6",rx:"1"})]})})})]})}),_W=Ce.lazy(()=>vt(()=>import("./SpawnModal-ByhvPfN7.js"),__vite__mapDeps([17,3,1,4])).then(t=>({default:t.SpawnModal}))),EW=Ce.lazy(()=>vt(()=>import("./BossSpawnModal-dSXYldID.js"),__vite__mapDeps([18,3,1,4])).then(t=>({default:t.BossSpawnModal}))),MW=Ce.lazy(()=>vt(()=>import("./SubordinateAssignmentModal-5Re0nGK9.js"),__vite__mapDeps([19,3,1,4])).then(t=>({default:t.SubordinateAssignmentModal}))),DW=Ce.lazy(()=>vt(()=>import("./index-DfBVuA_K.js"),__vite__mapDeps([20,3,1,4,21])).then(t=>({default:t.Toolbox}))),RW=Ce.lazy(()=>vt(()=>import("./index-DtDea-zV.js"),__vite__mapDeps([22,3,1,4])).then(t=>({default:t.BuildingConfigModal}))),OW=Ce.lazy(()=>vt(()=>import("./index-DTO0LlmC.js"),__vite__mapDeps([23,24,3,1,4])).then(t=>({default:t.CommanderView}))),LW=Ce.lazy(()=>vt(()=>import("./SupervisorPanel-DtNzjH1r.js"),__vite__mapDeps([25,3,1,4])).then(t=>({default:t.SupervisorPanel}))),IW=Ce.lazy(()=>vt(()=>import("./index-Bl5TthnX.js").then(t=>t.y),[]).then(t=>({default:t.FileExplorerPanel}))),PW=Ce.lazy(()=>vt(()=>import("./index-BakRazz4.js"),__vite__mapDeps([26,3,1,4])).then(t=>({default:t.Spotlight}))),BW=Ce.lazy(()=>vt(()=>import("./ControlsModal-C_W0XTlE.js"),__vite__mapDeps([27,3,1,4])).then(t=>({default:t.ControlsModal}))),FW=Ce.lazy(()=>vt(()=>import("./SkillsPanel-Btfm8DLY.js"),__vite__mapDeps([28,3,1,4])).then(t=>({default:t.SkillsPanel}))),zW=Ce.lazy(()=>vt(()=>Promise.resolve().then(()=>k2),void 0).then(t=>({default:t.AgentEditModal}))),$W=Ce.lazy(()=>vt(()=>import("./SnapshotManager-BgCuvtUx.js"),__vite__mapDeps([29,3,1,4])).then(t=>({default:t.SnapshotManager}))),UW=Ce.lazy(()=>vt(()=>import("./RestoreArchivedAreaModal-DHH8QKkx.js"),__vite__mapDeps([30,3,1,4])).then(t=>({default:t.RestoreArchivedAreaModal}))),HW=Ce.lazy(()=>vt(()=>import("./IntegrationsPanel-CJviFK3q.js"),__vite__mapDeps([31,3,1,4])).then(t=>({default:t.IntegrationsPanel}))),WW=Ce.lazy(()=>vt(()=>import("./MonitoringModal-DRZrxL7t.js"),__vite__mapDeps([32,3,1,4])).then(t=>({default:t.MonitoringModal}))),qW=Ce.lazy(()=>vt(()=>import("./WorkflowEditorPanel-CCauefUO.js"),__vite__mapDeps([33,3,1,4])).then(t=>({default:t.WorkflowEditorPanel}))),VW=Ce.lazy(()=>vt(()=>import("./TriggerManagerPanel-DUXzcjBS.js"),__vite__mapDeps([34,3,1,4])).then(t=>({default:t.TriggerManagerPanel})));function YW({spawnModal:t,bossSpawnModal:e,subordinateModal:n,toolboxModal:s,commanderModal:a,deleteConfirmModal:r,supervisorModal:i,spotlightModal:c,controlsModal:d,skillsModal:f,integrationsModal:h,monitoringModal:m,workflowEditorModal:b,triggerManagerModal:y,buildingModal:w,agentEditModal:C,snapshotsModal:N,restoreArchivedModal:k,explorerModal:j,contextMenu:S,spawnPosition:T,spawnAreaId:D,explorerFolderPath:E,contextMenuActions:I,buildingInitialPosition:O,sceneConfig:_,onConfigChange:M,onToolChange:R,onOpenAreaExplorer:z,onDeleteSelectedAgents:$,pendingBuildingDelete:W,onCancelBuildingDelete:L,onConfirmBuildingDelete:F,showBackNavModal:H,onCloseBackNavModal:V,onLeave:G,onOpenPM2LogsModal:B,onOpenBossLogsModal:K,onOpenDatabasePanel:ne,onSyncScene:q}){const xe=Rs(),Ae=Array.from(xe.snapshots.values()),Z=xe.snapshotsLoading;xe.currentSnapshot,x.useEffect(()=>{N.isOpen&&U.fetchSnapshots()},[N.isOpen]);const ce=W==="selected",me=W&&W!=="selected"?xe.buildings.get(W):null,ee=xe.selectedBuildingIds.size;return o.jsxs(x.Suspense,{fallback:null,children:[o.jsx(DW,{config:_,onConfigChange:M,onToolChange:R,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:re=>w.open(re||null),onOpenAreaExplorer:z,onOpenIntegrationsModal:re=>h.open(re),onOpenMonitoringModal:()=>m.open(),onOpenWorkflowEditor:()=>b.open(),onOpenTriggerManager:()=>y.open()}),o.jsx(RW,{isOpen:w.isOpen,onClose:w.close,buildingId:w.data,initialPosition:O||void 0}),o.jsx(_W,{isOpen:t.isOpen,onClose:t.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T,spawnAreaId:D}),o.jsx(EW,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T}),o.jsx(MW,{isOpen:n.isOpen,bossId:n.data||"",onClose:n.close}),C.isOpen&&C.data&&(()=>{const re=xe.agents.get(C.data);return re?o.jsx(zW,{agent:re,isOpen:C.isOpen,onClose:C.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:re=>{re.key==="Escape"&&r.close(),re.key==="Enter"&&$()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:re=>re.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 ",xe.selectedAgentIds.size," selected agent",xe.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:$,autoFocus:!0,children:"Remove"})]})]})}),(me||ce)&&o.jsx("div",{className:"modal-overlay visible",onClick:L,onKeyDown:re=>{re.key==="Escape"&&L(),re.key==="Enter"&&F()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:re=>re.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",ce&&ee>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[ce?o.jsxs("p",{children:["Delete ",ee," selected building",ee>1?"s":"","?"]}):o.jsxs("p",{children:["Delete ",o.jsx("strong",{children:me==null?void 0:me.name}),"?"]}),o.jsxs("p",{className:"confirm-modal-note",children:["This will permanently remove the building",ce&&ee>1?"s":""," and ",ce&&ee>1?"their":"its"," configuration."]})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:L,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:F,autoFocus:!0,children:"Delete"})]})]})}),H&&o.jsx("div",{className:"modal-overlay navigation-confirm-overlay visible",onClick:V,onKeyDown:re=>{re.key==="Escape"&&V()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:re=>re.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:V,autoFocus:!0,children:"Stay"}),o.jsx("button",{className:"btn btn-danger",onClick:G,children:"Leave"})]})]})}),o.jsx(x.Profiler,{id:"CommanderView",onRender:yu,children:o.jsx(OW,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(LW,{isOpen:i.isOpen,onClose:i.close}),o.jsx(IW,{isOpen:j.isOpen||E!==null||xe.explorerAreaId!==null,areaId:j.id||xe.explorerAreaId||null,folderPath:E,onChangeArea:re=>j.open(re),onClose:()=>{j.close(),U.closeFileExplorer()}}),o.jsx(PW,{isOpen:c.isOpen,onClose:c.close,onOpenSpawnModal:()=>t.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenSupervisor:()=>i.open(),onOpenFileExplorer:re=>j.open(re),onOpenPM2LogsModal:B,onOpenBossLogsModal:K,onOpenDatabasePanel:ne,onOpenMonitoringModal:()=>m.open()}),o.jsx(BW,{isOpen:d.isOpen,onClose:d.close}),o.jsx(FW,{isOpen:f.isOpen,onClose:f.close}),o.jsx(HW,{isOpen:h.isOpen,onClose:h.close,initialTab:h.data}),o.jsx(WW,{isOpen:m.isOpen,onClose:m.close}),o.jsx(qW,{isOpen:b.isOpen,onClose:b.close}),o.jsx(VW,{isOpen:y.isOpen,onClose:y.close}),o.jsx(UW,{isOpen:k.isOpen,restorePosition:k.data??null,onClose:k.close,onRestored:q}),N.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:N.close,children:o.jsx("div",{className:"modal snapshot-manager-modal",onClick:re=>re.stopPropagation(),children:o.jsx($W,{snapshots:Ae,isLoading:Z,onViewSnapshot:async re=>{await U.loadSnapshot(re),xe.selectedAgentIds.clear(),U.setTerminalOpen(!0),N.close()},onDeleteSnapshot:async re=>{await U.deleteSnapshot(re),await U.fetchSnapshots()},onRestoreSnapshot:async re=>{await U.restoreFiles(re)},onExportSnapshot:async re=>{await U.loadSnapshot(re),N.close()},onClose:N.close})})}),o.jsx(Do,{isOpen:S.isOpen,position:S.screenPosition,worldPosition:S.worldPosition,actions:I,onClose:S.close})]})}function GW({pip:t,title:e="Tide Commander",children:n}){return x.useEffect(()=>{t.pipWindow&&e&&(t.pipWindow.document.title=e)},[t.pipWindow,e]),!t.isOpen||!t.pipContainer?null:ac.createPortal(n,t.pipContainer)}function Oy(t){switch(t){case"working":return"⚡";case"waiting":return"⏳";case"waiting_permission":return"🔐";case"error":return"❌";case"offline":return"💤";case"orphaned":return"👻";case"idle":default:return"●"}}function Ly(t){switch(t){case"working":return"#4aff9e";case"waiting":return"#ff9e4a";case"waiting_permission":return"#ff4a9e";case"error":return"#ff4a4a";case"offline":return"#666";case"orphaned":return"#9e4aff";case"idle":default:return"#888"}}function Iy(t){const e=_o[t.class];return(e==null?void 0:e.icon)||"🤖"}function Rb({agent:t,onClick:e}){const n=Ly(t.status),s=Oy(t.status),a=Iy(t);return o.jsxs("div",{className:`pip-agent-card pip-status-${t.status}`,onClick:()=>e(t.id),title:"Click to view conversation",children:[o.jsxs("div",{className:"pip-agent-header",children:[o.jsx("span",{className:"pip-agent-icon",children:a}),o.jsx("span",{className:"pip-agent-name",children:t.name}),o.jsx("span",{className:"pip-agent-status",style:{color:n},children:s})]}),t.taskLabel&&o.jsxs("div",{className:"pip-agent-task",children:["📋 ",t.taskLabel]}),!t.taskLabel&&t.status==="working"&&t.currentTask&&o.jsx("div",{className:"pip-agent-task",children:t.currentTask.length>60?t.currentTask.slice(0,60)+"...":t.currentTask}),t.currentTool&&o.jsxs("div",{className:"pip-agent-tool",children:[o.jsx("span",{className:"pip-tool-label",children:"Tool:"})," ",t.currentTool]}),o.jsxs("div",{className:"pip-agent-context",children:[o.jsx("div",{className:"pip-context-bar",children:o.jsx("div",{className:"pip-context-fill",style:{width:`${Math.min(Math.round(t.contextUsed/t.contextLimit*100),100)}%`,backgroundColor:t.contextUsed/t.contextLimit*100>80?"#ff4a4a":t.contextUsed/t.contextLimit*100>50?"#ff9e4a":"#4aff9e"}})}),o.jsxs("span",{className:"pip-context-percent",children:[Math.round(t.contextUsed/t.contextLimit*100),"%"]})]})]})}function xu(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}const XA={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},JA={systemPrompt:"System Prompt",systemTools:"System Tools",messages:"Messages",freeSpace:"Free Space",autocompactBuffer:"Autocompact Buffer"};function KW({agent:t,onBack:e}){const n=Iy(t),s=Ly(t.status),a=t.contextStats,r=Math.round(t.contextUsed/t.contextLimit*100),i=t.contextUsed/t.contextLimit*100>80?"#ff4a4a":t.contextUsed/t.contextLimit*100>50?"#ff9e4a":"#4aff9e",c=["systemPrompt","systemTools","messages","autocompactBuffer","freeSpace"];return o.jsxs("div",{className:"pip-container pip-stats-container",children:[o.jsxs("div",{className:"pip-header pip-header-conversation",children:[o.jsx("button",{className:"pip-back-btn",onClick:e,title:"Back to conversation",children:"←"}),o.jsx("span",{className:"pip-agent-icon",children:n}),o.jsx("span",{className:"pip-title",children:t.name}),o.jsx("span",{className:"pip-agent-status-small",style:{color:s},children:Oy(t.status)})]}),o.jsx("div",{className:"pip-stats-content",children:a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"pip-model-info",children:[o.jsxs("div",{className:"pip-model-info-item",children:[o.jsx("div",{className:"pip-model-info-label",children:"Model"}),o.jsx("div",{className:"pip-model-info-value",children:a.model})]}),o.jsxs("div",{className:"pip-model-info-item",children:[o.jsx("div",{className:"pip-model-info-label",children:"Window"}),o.jsx("div",{className:"pip-model-info-value",children:xu(a.contextWindow)})]})]}),o.jsxs("div",{className:"pip-stats-section",children:[o.jsxs("div",{className:"pip-usage-header",children:[o.jsx("span",{className:"pip-usage-label",children:"Context Usage"}),o.jsxs("span",{className:"pip-usage-value",style:{color:i},children:[xu(a.totalTokens)," / ",xu(a.contextWindow)," (",a.usedPercent,"%)"]})]}),o.jsx("div",{className:"pip-stacked-bar",children:c.map(d=>{const f=a.categories[d];return!f||f.percent<=0?null:o.jsx("div",{className:"pip-stacked-bar-segment",style:{width:`${f.percent}%`,backgroundColor:XA[d]},title:`${JA[d]}: ${xu(f.tokens)}`},d)})})]}),o.jsxs("div",{className:"pip-stats-section",children:[o.jsx("h3",{className:"pip-stats-title",children:"Token Breakdown"}),o.jsx("div",{className:"pip-category-list",children:c.map(d=>{const f=a.categories[d];if(!f)return null;const h=d==="freeSpace";return o.jsxs("div",{className:`pip-category-item ${h?"free-space":""}`,children:[o.jsx("div",{className:"pip-category-color",style:{backgroundColor:XA[d]}}),o.jsxs("div",{className:"pip-category-info",children:[o.jsx("div",{className:"pip-category-name",children:JA[d]}),o.jsxs("div",{className:"pip-category-tokens",children:[xu(f.tokens)," (",f.percent.toFixed(1),"%)"]})]})]},d)})})]}),o.jsxs("div",{className:"pip-stats-updated",children:["Updated: ",new Date(a.lastUpdated).toLocaleTimeString()]})]}):o.jsxs("div",{className:"pip-stats-section",children:[o.jsx("h3",{className:"pip-stats-title",children:"Context Usage"}),o.jsxs("div",{className:"pip-stats-bar-container",children:[o.jsx("div",{className:"pip-stats-bar",children:o.jsx("div",{className:"pip-stats-bar-fill",style:{width:`${Math.min(r,100)}%`,backgroundColor:i}})}),o.jsxs("span",{className:"pip-stats-percent",style:{color:i},children:[r,"%"]})]}),o.jsx("div",{className:"pip-stats-info",children:o.jsx("p",{className:"pip-stats-info-text",children:"Context usage represents how much of the conversation window is filled. Detailed breakdown not available yet."})})]})})]})}function QW({agentId:t,onBack:e}){const n=Kj(t),s=Qj(t),a=r1(),r=i1(),i=Ux(),c=x.useRef(null),d=x.useRef(null),[f,h]=x.useState(""),[m,b]=x.useState(!1),[y]=x.useState("simple"),w=!!(n!=null&&n.sessionId),C=Wj({selectedAgentId:t,hasSessionId:w,reconnectCount:a,historyRefreshTrigger:r,lastPrompts:i,outputScrollRef:c}),N=_T({outputs:s,viewMode:y}),k=x.useMemo(()=>{const{history:$}=C,W=new Map;for(const F of $)F.type==="tool_result"&&F.toolUseId&&W.set(F.toolUseId,F.content);return(F=>F.map(H=>{if(H.type==="tool_use"&&H.toolName==="Bash"&&H.toolUseId){const V=W.get(H.toolUseId);let G;try{G=(H.toolInput||(H.content?JSON.parse(H.content):{})).command}catch{}return{...H,_bashOutput:V,_bashCommand:G}}return H}))($.filter(F=>F.type==="user"||F.type==="assistant"||F.type==="tool_use"))},[C.history]),[j,S]=x.useState({top:!1,bottom:!0}),T=x.useCallback(()=>{if(!c.current)return;const{scrollTop:$,scrollHeight:W,clientHeight:L}=c.current;S({top:$>20,bottom:$<W-L-20})},[]);x.useEffect(()=>{c.current&&(c.current.scrollTop=c.current.scrollHeight,T())},[s.length,k.length,T]);const D=x.useCallback(()=>{c.current&&c.current.scrollBy({top:-200,behavior:"smooth"})},[]),E=x.useCallback(()=>{c.current&&c.current.scrollBy({top:200,behavior:"smooth"})},[]),I=x.useCallback(()=>{const $=f.trim();!$||!n||(U.sendCommand(t,$),h(""),setTimeout(()=>{var W;return(W=d.current)==null?void 0:W.focus()},50))},[f,t,n]),O=x.useCallback($=>{h($.target.value)},[]),_=x.useCallback($=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),I())},[I]);x.useEffect(()=>{const $=setTimeout(()=>{var W;return(W=d.current)==null?void 0:W.focus()},100);return()=>clearTimeout($)},[t]);const M=x.useCallback(($,W)=>{const L=sh($,n==null?void 0:n.cwd),F=L.line?{...W||{},targetLine:L.line}:W;U.setFileViewerPath(L.path,F,n==null?void 0:n.cwd)},[n==null?void 0:n.cwd]);if(!n)return o.jsx("div",{className:"pip-container",children:o.jsxs("div",{className:"pip-header pip-header-conversation",children:[o.jsx("button",{className:"pip-back-btn",onClick:e,title:"Back to agents list",children:"←"}),o.jsx("span",{className:"pip-title",children:"Agent not found"})]})});const R=Iy(n),z=Ly(n.status);return m?o.jsx(KW,{agent:n,onBack:()=>b(!1)}):o.jsxs("div",{className:"pip-container pip-conversation-container",children:[o.jsxs("div",{className:"pip-header pip-header-conversation",children:[o.jsx("button",{className:"pip-back-btn",onClick:e,title:"Back to agents list",children:"←"}),o.jsx("span",{className:"pip-agent-icon",children:R}),o.jsx("span",{className:"pip-title",children:n.name}),o.jsx("span",{className:"pip-agent-status-small",style:{color:z},children:Oy(n.status)})]}),o.jsx("div",{className:"pip-context-section",children:o.jsx(y1,{contextInfo:Xp(n),onClick:()=>b(!0)})}),o.jsxs("div",{className:"pip-conversation-wrapper",children:[o.jsxs("div",{className:"pip-conversation guake-output",ref:c,onScroll:T,children:[!C.loadingHistory&&C.hasMore&&o.jsx("div",{className:"guake-load-more pip-load-more",children:C.loadingMore?o.jsx("span",{children:"Loading older messages..."}):o.jsxs("button",{onClick:C.loadMoreHistory,children:["Load more (",C.totalCount-C.history.length," older)"]})}),C.loadingHistory&&o.jsx("div",{className:"pip-loading-indicator",children:o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{children:"."}),o.jsx("span",{children:"."}),o.jsx("span",{children:"."})]})}),k.map(($,W)=>o.jsx(QT,{message:$,agentId:t,simpleView:!0,onFileClick:M},`h-${W}`)),N.map(($,W)=>o.jsx(Dy,{output:$,agentId:t,onFileClick:M},`o-${W}`)),!C.loadingHistory&&k.length===0&&N.length===0&&n.status!=="working"&&o.jsx("div",{className:"pip-empty",children:o.jsx("p",{children:"No conversation yet"})})]}),o.jsxs("div",{className:"pip-scroll-controls",children:[j.top&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-up",onClick:D,title:"Scroll up",children:"↑"}),j.bottom&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-down",onClick:E,title:"Scroll down",children:"↓"})]})]}),n.currentTool&&o.jsx("div",{className:"pip-current-tool",children:o.jsxs("span",{className:"pip-tool-indicator",children:["Using: ",n.currentTool]})}),o.jsxs("div",{className:"pip-input-area",children:[o.jsx("input",{ref:d,type:"text",className:"pip-input",placeholder:`Message ${n.name}...`,value:f,onChange:O,onKeyDown:_,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1}),o.jsx("button",{className:"pip-send-btn",onClick:I,disabled:!f.trim(),title:"Send message",children:"➤"})]})]})}function XW({onSelectAgent:t}){const e=Kp(),n=e.filter(c=>c.status==="working"),s=e.filter(c=>c.status==="waiting"||c.status==="waiting_permission"),a=e.filter(c=>c.status!=="working"&&c.status!=="waiting"&&c.status!=="waiting_permission"),r=e.length,i=n.length+s.length;return o.jsxs("div",{className:"pip-container",children:[o.jsxs("div",{className:"pip-header",children:[o.jsx("span",{className:"pip-title",children:"Tide Commander"}),o.jsxs("span",{className:"pip-stats",children:[i,"/",r," active"]})]}),o.jsxs("div",{className:"pip-agents-list",children:[n.length>0&&o.jsxs("div",{className:"pip-section",children:[o.jsxs("div",{className:"pip-section-title",children:["Working (",n.length,")"]}),n.map(c=>o.jsx(Rb,{agent:c,onClick:t},c.id))]}),s.length>0&&o.jsxs("div",{className:"pip-section",children:[o.jsxs("div",{className:"pip-section-title",children:["Waiting (",s.length,")"]}),s.map(c=>o.jsx(Rb,{agent:c,onClick:t},c.id))]}),a.length>0&&o.jsxs("div",{className:"pip-section",children:[o.jsxs("div",{className:"pip-section-title",children:["Idle (",a.length,")"]}),a.map(c=>o.jsx(Rb,{agent:c,onClick:t},c.id))]}),e.length===0&&o.jsx("div",{className:"pip-empty",children:o.jsx("p",{children:"No agents spawned yet"})})]})]})}function JW(){const[t,e]=x.useState(null),n=a=>{e(a)},s=()=>{e(null)};return t?o.jsx(QW,{agentId:t,onBack:s}):o.jsx(XW,{onSelectAgent:n})}function ZW(t){const e=t.trim();if(!e)return{ok:!0,normalizedUrl:""};let n;try{n=new URL(e)}catch{return{ok:!1,normalizedUrl:"",error:"Invalid URL format. Use http://host:port"}}return n.protocol!=="http:"&&n.protocol!=="https:"?{ok:!1,normalizedUrl:"",error:"Unsupported protocol. Use http or https"}:{ok:!0,normalizedUrl:e}}async function eq(t,e=5e3,n=fetch){if(!t)return{ok:!0};const a=`${t.replace(/\/$/,"")}/api/health`,r=new AbortController,i=setTimeout(()=>r.abort(),e);try{const c=await n(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 tq=4e3;function nq(){const t=Jj(),[e,n]=x.useState(!1),[s,a]=x.useState(!1),[r,i]=x.useState(!0),[c,d]=x.useState(()=>Rx()),[f,h]=x.useState(!1),[m,b]=x.useState(null),[y,w]=x.useState(null),C=x.useRef(!0),N=x.useCallback((D=7e3)=>U.getState().isConnected?Promise.resolve(!0):new Promise(E=>{let I=!1;const O=R=>{I||(I=!0,clearTimeout(M),_(),E(R))},_=U.subscribe(()=>{U.getState().isConnected&&O(!0)}),M=setTimeout(()=>O(!1),D)}),[]);x.useEffect(()=>{const D=setTimeout(()=>i(!1),3e3);return()=>clearTimeout(D)},[]),x.useEffect(()=>()=>{C.current=!1},[]),x.useEffect(()=>VD(D=>{d(D)}),[]);const k=x.useCallback(()=>{navigator.clipboard.writeText("bunx tide-commander").then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(()=>{})},[]),j=x.useCallback(async()=>{if(f)return;const D=Date.now(),E=()=>tq-(Date.now()-D);b(null),w("Validating URL");const I=c.trim()||"http://localhost:6200",O=ZW(I);if(!O.ok){w(null),b(O.error||"Invalid backend URL");return}h(!0),w("Checking host reachability");const _=E();if(_<=0){h(!1),w(null),b("Connection timeout after 4 seconds");return}const M=await eq(O.normalizedUrl,_);if(!M.ok){if(!C.current)return;h(!1),w(null),E()<=0?b("Connection timeout after 4 seconds"):b(M.error||"Failed to reach host");return}qD(O.normalizedUrl),w("Connecting to server"),zR();const R=E();if(R<=0){h(!1),w(null),b("Connection timeout after 4 seconds");return}const z=await N(R);if(C.current){if(!z){h(!1),w(null),E()<=0?b("Connection timeout after 4 seconds"):b("Could not establish WebSocket connection. Verify host and auth token, then retry");return}h(!1),w("Connected"),b(null)}},[c,f,N]),S=x.useCallback(D=>{D.key==="Enter"&&!f&&j()},[j,f]),T=x.useCallback(()=>{n(!0)},[]);return t||e||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:k,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:c,disabled:f,onChange:D=>{const E=D.target.value;d(E),m&&b(null)},onKeyDown:S})}),o.jsx("span",{className:"config-hint",children:"Leave empty for auto-detect"}),y&&!m&&o.jsx("div",{className:"not-connected-status","aria-live":"polite",children:y}),m&&o.jsx("div",{className:"not-connected-error","aria-live":"assertive",children:m})]}),o.jsxs("div",{className:"not-connected-actions",children:[o.jsx("button",{className:"not-connected-btn not-connected-btn-retry",onClick:()=>{j()},disabled:f,children:f?"Connecting...":"↻ Connect"}),o.jsx("button",{className:"not-connected-btn not-connected-btn-explore",onClick:T,children:"Explore"})]})]})})}const ZA="tide-onboarding-dismissed";function sq({onCreateAgent:t}){const{t:e}=dt("common"),n=Jj(),s=Gj(),[a,r]=x.useState(()=>sessionStorage.getItem(ZA)==="1"),i=n&&!a&&s===0,c=x.useCallback(()=>{r(!0),sessionStorage.setItem(ZA,"1")},[]),d=x.useCallback(()=>{c(),t()},[c,t]),f=x.useCallback(h=>{h.key==="Escape"&&c()},[c]);return i?o.jsx(pr,{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 ZT(){return{"Content-Type":"application/json","X-Auth-Token":Ii()}}async function aq(t){const e=await fetch(`${Ea()}/api/areas/${t}/organize`,{method:"POST",headers:ZT()});if(!e.ok)throw new Error(`Failed to organize area: ${e.statusText}`);const n=await e.json();return{organized:Array.isArray(n.organized)?n.organized:[],buildings:Array.isArray(n.buildings)?n.buildings:[]}}async function rq(){const t=await fetch(`${Ea()}/api/areas/organize-all`,{method:"POST",headers:ZT()});if(!t.ok)throw new Error(`Failed to organize all areas: ${t.statusText}`);const e=await t.json();return Array.isArray(e.organized)?{organized:e.organized,buildings:Array.isArray(e.buildings)?e.buildings:[]}:(Array.isArray(e.results)?e.results:[]).reduce((n,s)=>(n.organized.push(...s.organized),n.buildings.push(...s.buildings),n),{organized:[],buildings:[]})}function e_(t,e){var s,a;const n=U.getState();for(const r of t.organized){const i=n.agents.get(r.agentId);if(i){const c={...i,position:r.position};U.updateAgent(c),(s=e.current)==null||s.updateAgent(c,!0)}}for(const r of t.buildings){const i=n.buildings.get(r.buildingId);i&&(U.updateBuilding(r.buildingId,{position:r.position}),(a=e.current)==null||a.updateBuilding({...i,position:r.position}))}}function iq(t,e,n,s,a,r){const i=[];if(e.type==="agent"&&e.id){const d=n.get(e.id);if(d)return i.push({id:"select-agent",label:`Select ${d.name}`,icon:"👆",onClick:()=>{var f;U.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:()=>{U.selectAgent(e.id),U.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;U.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:()=>{U.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}}))}}),i.push({id:"divider-area-layer",label:"",divider:!0,onClick:()=>{}}),i.push({id:"bring-to-front",label:"Bring to Front",icon:"⬆️",onClick:()=>{var f;U.bringAreaToFront(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),i.push({id:"send-to-back",label:"Send to Back",icon:"⬇️",onClick:()=>{var f;U.sendAreaToBack(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),d.assignedAgentIds.length>0&&i.push({id:"organize-area",label:"Organize Area",icon:"✨",onClick:()=>{aq(e.id).then(f=>{e_(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;U.archiveArea(e.id,y=>U.stopAgent(y)),(m=r.sceneRef.current)==null||m.syncAreas(),(b=r.sceneRef.current)==null||b.syncAgents(Array.from(U.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;U.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:()=>{U.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};U.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:()=>{U.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(t),r.openSpawnModal()}}),i.push({id:"spawn-boss",label:"Spawn Boss Here",icon:"👑",onClick:()=>{r.setSpawnPosition(t),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(t)}}),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 oq=Ce.lazy(()=>vt(()=>import("./index-CPBP46l5.js"),__vite__mapDeps([35,3,1,4,36])).then(t=>({default:t.DatabasePanel}))),lq=Ce.lazy(()=>vt(()=>import("./PM2LogsModal-BLzKH4ql.js"),__vite__mapDeps([37,38,3,1,4])).then(t=>({default:t.PM2LogsModal}))),cq=Ce.lazy(()=>vt(()=>import("./DockerLogsModal-CUweGxhz.js"),__vite__mapDeps([39,38,3,1,4])).then(t=>({default:t.DockerLogsModal}))),uq=Ce.lazy(()=>vt(()=>import("./BossLogsModal-C9c6b6JM.js"),__vite__mapDeps([40,38,3,1,4])).then(t=>({default:t.BossLogsModal}))),dq=Ce.lazy(()=>vt(()=>import("./Scene2DCanvas-Gu0Pplgl.js"),__vite__mapDeps([41,3,1,4,42])).then(t=>({default:t.Scene2DCanvas}))),fq=Ce.lazy(()=>vt(()=>import("./index-BG-fI4o6.js"),__vite__mapDeps([43,3,1,4,44])).then(t=>({default:t.DashboardView}))),pq=Ce.lazy(()=>vt(()=>import("./IframeModal-3rIUuKKu.js"),__vite__mapDeps([45,3,1,4,46])).then(t=>({default:t.IframeModal}))),hq=Ce.lazy(()=>vt(()=>import("./SaveSnapshotModal-BTvvgNqk.js"),__vite__mapDeps([47,3,1,4])).then(t=>({default:t.SaveSnapshotModal})));function mq(){const{t}=dt(["common","notifications"]),e=x.useRef(null),n=x.useRef(null),s=cs(),a=cs(),r=cs(),i=cs(),c=cs(),d=cs(),f=cs(),h=cs(),m=cs(),b=cs(),y=cs(),w=cs(),C=cs(),N=cs(),k=cs(),j=cs(),S=cs(),T=cs(),D=cs(),E=YD(),I=JO(),O=GD(),_=rR(),[M,R]=x.useState(null),z=KR(),[$,W]=x.useState(!1),[L,F]=x.useState(null),[H,V]=x.useState(null),[G,B]=x.useState(null),[K,ne]=x.useState(null),[q,xe]=x.useState(null),[Ae,Z]=x.useState(null),[ce,me]=x.useState(null),[ee,re]=x.useState(null),[We,ze]=x.useState(null),[Pe,ge]=x.useState(null),Te=x.useCallback(Ne=>{ge(Ne),Ne&&localStorage.setItem("tide-commander-last-database-building",Ne)},[]),qe=x.useCallback(()=>Te(null),[Te]),{handleMouseDown:it,handleClick:he}=Ta(qe),Be=x.useCallback(()=>ze(null),[]),{handleMouseDown:ie,handleClick:de}=Ta(Be),He=x.useRef(Ae);He.current=Ae;const et=x.useCallback(Ne=>{Z(Ne)},[]),ct=x.useCallback(()=>He.current,[]),fe=x.useRef(null),[X,se]=x.useState($j),[Se,J]=x.useState(0),[pe,Re]=x.useState(!1),[$e,ye]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[Ie,te]=x.useState(!1),[be,we]=x.useState(!1),Fe=t1(),Ke=o1(),st=Wx(),ft=qx(),wt=e1(),{showToast:rt}=u1(),{showAgentNotification:gt}=AL(),{showBackNavModal:ht,setShowBackNavModal:Gt,handleLeave:tn}=pO();iO({showToast:rt,showAgentNotification:gt});const[je,Oe]=x.useState(!1);x.useEffect(()=>{const Ne=Je=>{var ot;((ot=Je.detail)==null?void 0:ot.mode)==="3d"&&Oe(!0)};return window.addEventListener("tide:viewmode-switch-pressed",Ne),()=>{window.removeEventListener("tide:viewmode-switch-pressed",Ne)}},[]),x.useEffect(()=>{Ke==="3d"&&Oe(!0)},[Ke]);const Ye=rO({canvasRef:e,selectionBoxRef:n,viewMode:Ke,sceneMountKey:Se,showToast:rt,showAgentNotification:gt,toolboxModal:i,contextMenu:O,setHoveredAgentPopup:xe,setBuildingPopup:et,getBuildingPopup:ct,openBuildingModal:Ne=>k.open(Ne),openPM2LogsModal:Ne=>me(Ne),openBossLogsModal:Ne=>re(Ne),openDatabasePanel:Ne=>Te(Ne),onSceneLoadingChange:Oe}),Ze=Gj(),Ot=ur(),Ft=Hx(),Lt=$x(),Vt=VO(),ln=qO(),bt=WO(),at=Vr(),xt=GO(),$t=cL(),En=uL(),nn=x.useMemo(()=>Array.from(Lt),[Lt]),Un=x.useRef(!1);Mj("AppContent"),oO(Ye),lO(Ye),cO(Ye),gO(),uO(Ye,ln),dO(Ye,at.powerSaving),x.useEffect(()=>{var Ne;document.title=((Ne=at.tabTitle)==null?void 0:Ne.trim())||"Tide Commander"},[at.tabTitle]),x.useEffect(()=>{var Dn,Fs;if(Un.current||typeof window>"u")return;const Ne=new URLSearchParams(window.location.search),Je=(Dn=Ne.get("agentId"))==null?void 0:Dn.trim(),Ct=(Fs=Ne.get("agentName"))==null?void 0:Fs.trim();if(!Je&&!Ct||Ze===0)return;const ot=U.getState().agents,jn=Ne.get("openTerminal"),Mt=jn?["1","true","yes"].includes(jn.toLowerCase()):!0;let At=Je?ot.get(Je):void 0;if(!At&&Ct){const Qr=Ct.toLowerCase();At=Array.from(ot.values()).find(pa=>pa.name.toLowerCase()===Qr)}if(!At){console.warn("[DeepLink] No matching agent found for query params",{rawAgentId:Je,rawAgentName:Ct}),Un.current=!0;return}U.selectAgent(At.id),Mt&&U.setTerminalOpen(!0),Ne.delete("agentId"),Ne.delete("agentName"),Ne.delete("openTerminal");const kn=Ne.toString(),ms=`${window.location.pathname}${kn?`?${kn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,ms),Un.current=!0},[Ze]),fO({sceneRef:Ye,spawnModal:s,commanderModal:c,explorerModal:E,spotlightModal:h,deleteConfirmModal:d,onRequestBuildingDelete:()=>ne("selected"),onOpenDatabasePanel:Te,onCloseDatabasePanel:qe,databasePanelOpen:Pe!==null}),Xt("spawn-modal",s.isOpen,s.close),Xt("boss-spawn-modal",a.isOpen,a.close),Xt("subordinate-modal",r.isOpen,r.close),Xt("toolbox-modal",i.isOpen,i.close),Xt("commander-modal",c.isOpen,c.close),Xt("delete-confirm-modal",d.isOpen,d.close),Xt("supervisor-modal",f.isOpen,f.close),Xt("spotlight-modal",h.isOpen,h.close),Xt("controls-modal",m.isOpen,m.close),Xt("skills-modal",b.isOpen,b.close),Xt("integrations-modal",y.isOpen,y.close),Xt("monitoring-modal",w.isOpen,w.close),Xt("workflow-editor-modal",C.isOpen,C.close),Xt("trigger-manager-modal",N.isOpen,N.close),Xt("building-modal",k.isOpen,k.close),Xt("agent-edit-modal",j.isOpen,j.close),Xt("snapshots-modal",S.isOpen,S.close),Xt("save-snapshot-modal",T.isOpen,T.close),Xt("explorer-modal",E.isOpen||I!==null,()=>{E.close(),U.closeFileExplorer()}),Xt("context-menu",O.isOpen,O.close),Xt("mobile-sidebar",pe,()=>Re(!1)),Xt("mobile-fab-menu",be,()=>we(!1)),Xt("file-viewer",st!==null,()=>U.clearFileViewerPath()),Xt("context-modal",ft!==null,()=>U.closeContextModal()),Xt("terminal",wt,()=>U.setTerminalOpen(!1)),Xt("pm2-logs-modal",ce!==null,()=>me(null)),Xt("boss-logs-modal",ee!==null,()=>re(null)),Xt("database-panel",Pe!==null,qe),Xt("terminal-modal",We!==null,Be);const Os=x.useRef(wt),ps=x.useRef(b),ks=x.useRef(m);ps.current=b,ks.current=m,x.useEffect(()=>{Os.current&&!wt&&(ps.current.close(),ks.current.close()),Os.current=wt},[wt]),x.useEffect(()=>{},[]),x.useEffect(()=>{if(Fe!=="3d"||Ke!=="3d")return;const Ne=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(Ne)},[Fe,Ke]);const Qn=x.useCallback(Ne=>{var Je,Ct,ot,jn,Mt,At,kn,ms,Dn,Fs;se(Ne),sO(Ne),(Je=Ye.current)==null||Je.setCharacterScale(Ne.characterScale),(Ct=Ye.current)==null||Ct.setScale3D(Ne.scale3d),(ot=Ye.current)==null||ot.setGridVisible(Ne.gridVisible),(jn=Ye.current)==null||jn.setTimeMode(Ne.timeMode),(Mt=Ye.current)==null||Mt.setTerrainConfig(Ne.terrain),(At=Ye.current)==null||At.setFloorStyle(Ne.terrain.floorStyle),(kn=Ye.current)==null||kn.setAgentModelStyle(Ne.modelStyle),(ms=Ye.current)==null||ms.setIdleAnimation(Ne.animations.idleAnimation),(Dn=Ye.current)==null||Dn.setWorkingAnimation(Ne.animations.workingAnimation),(Fs=Ye.current)==null||Fs.setFpsLimit(Ne.fpsLimit)},[Ye]),Ss=x.useCallback(Ne=>{var Je;if((Je=Ye.current)==null||Je.setDrawingTool(Ne),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(Ne),Ne==="rectangle"||Ne==="circle"){const Ct=t(Ne==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");rt("info",Ct,t("notifications:drawing.clickAndDrag"),3e3)}},[Ye,rt]),Fn=x.useCallback(Ne=>{var Je;(Je=Ye.current)==null||Je.focusAgent(Ne)},[Ye]),Ls=x.useCallback(Ne=>{U.killAgent(Ne)},[]),Is=x.useCallback(Ne=>{var Je;(Je=Ye.current)==null||Je.callSubordinates(Ne)},[Ye]),wn=x.useCallback(Ne=>{E.open(Ne)},[E]),Po=x.useCallback(()=>{k.open(null)},[k]),Bo=x.useCallback(()=>{var Ne;(Ne=Ye.current)==null||Ne.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),rt("info",t("notifications:drawing.rectangleTool"),t("notifications:drawing.clickAndDrag"),3e3)},[Ye,rt]),Ps=x.useCallback(Ne=>{R(Ne)},[]),Ua=x.useCallback(()=>{R(null)},[]),Bi=x.useCallback(()=>{const Ne=Array.from(U.getState().selectedAgentIds);Ne.forEach(Je=>{var Ct;U.removeAgentFromServer(Je),(Ct=Ye.current)==null||Ct.removeAgent(Je)}),d.close(),rt("info",t("notifications:toast.agentsRemoved"),t("notifications:toast.agentsRemovedMsg",{count:Ne.length}))},[rt,d,Ye,t]),Fi=x.useCallback(()=>{var Ne,Je;if(K==="selected"){const Ct=Vt.size;U.deleteSelectedBuildings(),(Ne=Ye.current)==null||Ne.syncBuildings(),rt("info",t("notifications:toast.buildingsDeleted"),t("notifications:toast.buildingsDeletedMsg",{count:Ct}))}else if(K){const Ct=Ft.get(K);U.deleteBuilding(K),(Je=Ye.current)==null||Je.syncBuildings(),rt("info",t("notifications:toast.buildingDeleted"),t("notifications:toast.buildingDeletedMsg",{name:(Ct==null?void 0:Ct.name)||"Building"}))}ne(null)},[K,Ft,Vt.size,rt,Ye,t]),Bs=x.useMemo(()=>iq(O.worldPosition,O.target,U.getState().agents,Ot,Ft,{showToast:rt,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:Ne=>E.open(Ne),openBuildingModal:Ne=>k.open(Ne),openAgentEditModal:Ne=>j.open(Ne),requestBuildingDelete:Ne=>ne(Ne),setSpawnPosition:F,openRestoreArchivedModal:Ne=>D.open(Ne),sceneRef:Ye}),[O.worldPosition,O.target,Ot,Ft,s,a,k,i,c,E,j,D,rt,Ye]);x.useEffect(()=>{!s.isOpen&&!a.isOpen&&(F(null),B(null))},[s.isOpen,a.isOpen]),x.useEffect(()=>{const Ne=Mt=>{const At=Mt.detail;B((At==null?void 0:At.areaId)||null),F((At==null?void 0:At.position)||null),s.open()},Je=Mt=>{var ms,Dn;const At=Mt.detail;if(!(At!=null&&At.buildingId))return;const kn=U.getState().buildings.get(At.buildingId);kn&&(kn.type==="server"&&((ms=kn.pm2)!=null&&ms.enabled)?me(At.buildingId):kn.type==="boss"?re(At.buildingId):kn.type==="database"?Te(At.buildingId):kn.type==="folder"&&kn.folderPath?U.openFileExplorer(kn.folderPath):kn.type==="terminal"&&((Dn=kn.terminalStatus)!=null&&Dn.url)?ze(At.buildingId):k.open(At.buildingId))},Ct=Mt=>{const At=Mt.detail;At!=null&&At.buildingId&&k.open(At.buildingId)},ot=Mt=>{const At=Mt.detail;V((At==null?void 0:At.position)||null),k.open(null)},jn=Mt=>{const At=Mt.detail;At!=null&&At.buildingId?ze(At.buildingId):At!=null&&At.url&&R(At.url)};return window.addEventListener("tide:open-spawn-modal",Ne),window.addEventListener("tide:building-action",Je),window.addEventListener("tide:building-edit",Ct),window.addEventListener("tide:building-create",ot),window.addEventListener("tide:open-iframe-modal",jn),()=>{window.removeEventListener("tide:open-spawn-modal",Ne),window.removeEventListener("tide:building-action",Je),window.removeEventListener("tide:building-edit",Ct),window.removeEventListener("tide:building-create",ot),window.removeEventListener("tide:open-iframe-modal",jn)}},[s,k]);const lc=bt==="rectangle"||bt==="circle",Ma=x.useCallback(()=>{var Ne;(Ne=Ye.current)==null||Ne.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ye]),Ts=x.useCallback(()=>we(Ne=>!Ne),[]),hs=x.useCallback(()=>U.setMobileView("terminal"),[]),Mn=x.useCallback(()=>Re(!0),[]),zi=nn.length===1&&U.getOutputs(nn[0]).length>0;return o.jsxs("div",{className:`app ${wt?"terminal-open":""} ${lc?"drawing-mode":""} ${$e?"sidebar-collapsed":""} mobile-view-${Fe} view-mode-${Ke}`,children:[o.jsx(nq,{}),o.jsx(sq,{onCreateAgent:s.open}),o.jsx(SW,{visible:at.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(jW,{className:"app-view-mode-toggle"}),o.jsx(QR,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:$,title:"Auto-organize all agents in their areas",onClick:()=>{W(!0),rq().then(Ne=>{e_(Ne,Ye),rt("success","Organized",`Arranged ${Ne.organized.length} agent${Ne.organized.length!==1?"s":""}`)}).catch(Ne=>{console.error("organize all error:",Ne),rt("error","Organize Failed",Ne.message||"Failed to organize")}).finally(()=>W(!1))},children:[$?"⏳":"✨"," Organize"]})]}),o.jsxs("main",{className:"main-content",children:[o.jsxs("div",{className:"battlefield-container",children:[z&&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:Ke==="dashboard"?o.jsx(fq,{onSelectAgent:Ne=>U.selectAgent(Ne),onFocusAgent:Ne=>{U.setViewMode("3d"),Fn(Ne)},onKillAgent:Ls,onSelectBuilding:Ne=>U.selectBuilding(Ne),onOpenTerminal:Ne=>{U.selectAgent(Ne),U.setTerminalOpen(!0)},onFocusZone:Ne=>{U.setViewMode("3d");const Je=U.getState().areas.get(Ne);Je&&Je.assignedAgentIds.length>0&&Fn(Je.assignedAgentIds[0])}}):Ke==="2d"?o.jsx(dq,{onAgentClick:(Ne,Je)=>{Je?U.addToSelection(Ne):U.selectAgent(Ne)},onAgentDoubleClick:Ne=>{if(window.innerWidth<=768){U.openTerminalOnMobile(Ne);return}U.selectAgent(Ne),U.setTerminalOpen(!0)},onBuildingClick:(Ne,Je)=>{U.selectBuilding(Ne);const Ct=U.getState().buildings.get(Ne);(Ct==null?void 0:Ct.type)==="folder"&&Ct.folderPath?U.openFileExplorer(Ct.folderPath):((Ct==null?void 0:Ct.type)==="server"||(Ct==null?void 0:Ct.type)==="boss"||(Ct==null?void 0:Ct.type)==="database")&&(fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>{et({buildingId:Ne,screenPos:Je,fromClick:!0}),fe.current=null},150))},onBuildingDoubleClick:Ne=>{var Ct;fe.current&&(clearTimeout(fe.current),fe.current=null),et(null);const Je=U.getState().buildings.get(Ne);(Je==null?void 0:Je.type)==="server"&&((Ct=Je.pm2)!=null&&Ct.enabled)?me(Ne):(Je==null?void 0:Je.type)==="boss"?re(Ne):(Je==null?void 0:Je.type)==="database"?Te(Ne):(Je==null?void 0:Je.type)==="folder"&&Je.folderPath?U.openFileExplorer(Je.folderPath):k.open(Ne)},onGroundClick:()=>{U.selectAgent(null),U.selectBuilding(null)},onAreaDoubleClick:Ne=>{U.selectArea(Ne),i.open()},onContextMenu:(Ne,Je,Ct)=>{const ot=Ct?{type:Ct.type,id:Ct.id}:{type:"ground"};O.open(Ne,Je,ot)},onMoveCommand:(Ne,Je)=>{const ot=Ne.length,jn=[];if(ot===1)jn.push({x:Je.x,y:0,z:Je.z});else if(ot<=6){const Mt=1.2*Math.max(1,ot/3);for(let At=0;At<ot;At++){const kn=At/ot*Math.PI*2-Math.PI/2;jn.push({x:Je.x+Math.cos(kn)*Mt,y:0,z:Je.z+Math.sin(kn)*Mt})}}else{const Mt=Math.ceil(Math.sqrt(ot)),At=Math.ceil(ot/Mt),kn=(Mt-1)*1.2/2,ms=(At-1)*1.2/2;for(let Dn=0;Dn<ot;Dn++){const Fs=Dn%Mt,Qr=Math.floor(Dn/Mt);jn.push({x:Je.x+Fs*1.2-kn,y:0,z:Je.z+Qr*1.2-ms})}}Ne.forEach((Mt,At)=>{U.moveAgent(Mt,jn[At])})},onBuildingDragMove:(Ne,Je)=>{var ot;const Ct=U.getState().buildings.get(Ne);Ct&&(U.getState().buildings.set(Ne,{...Ct,position:{x:Je.x,z:Je.z}}),(ot=window.__tideScene2D)==null||ot.syncBuildings())},onBuildingDragEnd:(Ne,Je)=>{U.updateBuildingPosition(Ne,Je)},scale2d:X.scale2d,showTaskLabels:X.show2DTaskLabels,showGrid:X.gridVisible,fpsLimit:X.fpsLimit}):o.jsxs(Ce.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:n,id:"selection-box"})]},Se)}),je&&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(NW,{isOpen:be,onToggle:Ts,onShowTerminal:hs,onOpenSidebar:Mn,onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:b.open,onOpenSnapshots:S.open,onTakeSnapshot:T.open,canTakeSnapshot:zi,mobileView:Fe}),pe&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>Re(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${$e?"is-collapsed":""} ${Ie?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)Re(!pe);else{const Je=!$e;ye(Je),localStorage.setItem("tide-commander-sidebar-collapsed",String(Je))}},title:$e?"Open sidebar":"Close sidebar",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:Ie?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:$e?"15 18 9 12 15 6":"9 18 15 12 9 6"})})}),o.jsxs("aside",{className:`sidebar ${pe?"sidebar-open":""} ${$e?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>Re(!1),title:"Close sidebar",children:"✕"}),nn.length>0?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:yu,children:o.jsx(_S,{onFocusAgent:Fn,onKillAgent:Ls,onCallSubordinates:Is,onOpenAreaExplorer:wn})})}),o.jsx("div",{className:"sidebar-section tool-history-section",children:o.jsx(x.Profiler,{id:"ToolHistory",onRender:yu,children:o.jsx(T4,{agentIds:nn})})})]}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:yu,children:o.jsx(_S,{onFocusAgent:Fn,onKillAgent:Ls,onCallSubordinates:Is,onOpenAreaExplorer:wn})})})]}),o.jsx(x.Profiler,{id:"GuakeOutputPanel",onRender:yu,children:o.jsx(nW,{onSaveSnapshot:T.open})})]}),o.jsx(TW,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:b.open,onOpenSnapshots:S.open,isGeneratingReport:xt,pip:_}),o.jsx(pW,{activeTool:bt,onExit:Ma}),q&&(()=>{const Ne=U.getState().agents.get(q.agentId);return Ne?o.jsx(gW,{agent:Ne,screenPos:q.screenPos,onClose:()=>xe(null)}):null})(),Ae&&(()=>{const Ne=Ft.get(Ae.buildingId);if(!Ne)return null;const Je=()=>et(null);return Ne.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(wW,{building:Ne,screenPos:Ae.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ae.buildingId)},onOpenLogsModal:()=>{Je(),re(Ae.buildingId)},onOpenUrlInModal:Ps})]}):Ne.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(kW,{building:Ne,screenPos:Ae.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ae.buildingId)},onOpenDatabasePanel:()=>{Je(),Te(Ae.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(xW,{building:Ne,screenPos:Ae.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ae.buildingId)},onOpenLogsModal:()=>{me(Ae.buildingId)},onOpenUrlInModal:Ps})]})})(),ce&&(()=>{var Je;const Ne=Ft.get(ce);return Ne?(Je=Ne.docker)!=null&&Je.enabled?o.jsx(cq,{building:Ne,isOpen:!0,onClose:()=>me(null)}):o.jsx(lq,{building:Ne,isOpen:!0,onClose:()=>me(null)}):null})(),ee&&(()=>{const Ne=Ft.get(ee);return Ne?o.jsx(uq,{building:Ne,isOpen:!0,onClose:()=>re(null)}):null})(),Pe&&(()=>{const Ne=Ft.get(Pe);return Ne?o.jsx("div",{className:"modal-overlay visible",onMouseDown:it,onClick:he,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(oq,{building:Ne,onClose:qe})})}):null})(),We&&(()=>{var Je;const Ne=Ft.get(We);return!Ne||!((Je=Ne.terminalStatus)!=null&&Je.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:ie,onClick:de,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 - ",Ne.name]}),o.jsx("button",{className:"terminal-modal-close",onClick:Be,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(Ax,{terminalUrl:Ne.terminalStatus.url,visible:!0})]})})})(),o.jsx(GW,{pip:_,title:"Tide Commander - Agents",children:o.jsx(JW,{})}),o.jsx(pq,{url:M||"",title:M?`Preview - ${M}`:"",isOpen:!!M,onClose:Ua}),T.isOpen&&nn.length===1&&(()=>{const Ne=nn[0],Je=U.getState().agents.get(Ne);if(!Je)return null;const Ct=U.getOutputs(Ne);return o.jsx(hq,{isOpen:T.isOpen,onClose:T.close,agent:Je,outputCount:Ct.length,onSave:async ot=>{try{const jn=Ct.map(Mt=>({type:"message",content:Mt.text,timestamp:new Date(Mt.timestamp).toISOString()}));await U.createSnapshot(ot.agentId,Je.name,ot.title,ot.description,jn,[]),T.close(),rt("success",t("notifications:toast.snapshotSaved"),t("notifications:toast.snapshotSavedMsg"))}catch(jn){const Mt=jn instanceof Error?jn.message:t("notifications:toast.snapshotFailedMsg");rt("error",t("notifications:toast.snapshotFailed"),Mt)}},isSaving:$t,error:En||void 0})})(),o.jsx(fW,{onFocusAgent:Fn,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:Po,onNewAreaClick:Bo}),o.jsx(YW,{spawnModal:s,bossSpawnModal:a,subordinateModal:r,toolboxModal:i,commanderModal:c,deleteConfirmModal:d,supervisorModal:f,spotlightModal:h,controlsModal:m,skillsModal:b,integrationsModal:y,monitoringModal:w,workflowEditorModal:C,triggerManagerModal:N,buildingModal:k,buildingInitialPosition:H,agentEditModal:j,snapshotsModal:S,restoreArchivedModal:D,explorerModal:E,contextMenu:O,spawnPosition:L,spawnAreaId:G,explorerFolderPath:I,contextMenuActions:Bs,sceneConfig:X,onConfigChange:Qn,onToolChange:Ss,onOpenAreaExplorer:wn,onDeleteSelectedAgents:Bi,pendingBuildingDelete:K,onCancelBuildingDelete:()=>ne(null),onConfirmBuildingDelete:Fi,showBackNavModal:ht,onCloseBackNavModal:()=>Gt(!1),onLeave:tn,onOpenPM2LogsModal:Ne=>me(Ne),onOpenBossLogsModal:Ne=>re(Ne),onOpenDatabasePanel:Ne=>Te(Ne),onSyncScene:()=>{var Ne,Je;(Ne=Ye.current)==null||Ne.syncAreas(),(Je=Ye.current)==null||Je.syncAgents(Array.from(U.getState().agents.values()))}})]})}function gq(){return o.jsx(xL,{children:o.jsx(CL,{children:o.jsx(mq,{})})})}class bq extends x.Component{constructor(n){super(n);Xe(this,"handleReload",()=>{window.location.reload()});Xe(this,"handleDismiss",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[Tide] React Error:",n,s),this.setState({errorInfo:s})}render(){if(this.state.hasError){const{error:n,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:"💥"}),On.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:[n==null?void 0:n.name,": ",n==null?void 0:n.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:On.t("errors:crash.stackTrace")}),o.jsx("pre",{style:{color:"#ccc",fontSize:"12px",lineHeight:"1.5",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:n==null?void 0:n.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:On.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:On.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:On.t("common:buttons.tryToContinue")})]}),o.jsx("div",{style:{marginTop:"24px",color:"#666",fontSize:"12px"},children:On.t("errors:crash.checkConsole")})]})})}return this.props.children}}C6();document.addEventListener("wheel",t=>{if(Math.abs(t.deltaX)>Math.abs(t.deltaY)&&Math.abs(t.deltaX)>0){const e=t.target;if(e.tagName==="CANVAS"){t.preventDefault();return}let n=e;for(;n&&n!==document.documentElement;){if(n.scrollWidth>n.clientWidth)return;n=n.parentElement}t.preventDefault()}},{passive:!1});const t_=document.getElementById("app");if(!t_)throw new Error("Could not find #app container");const xq=SM.createRoot(t_);xq.render(o.jsx(Ce.StrictMode,{children:o.jsx(x.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(bq,{children:o.jsx(gq,{})})})}));console.log("[Tide] Tide Commander initialized");export{Df as $,jL as A,l1 as B,WD as C,vL as D,Ex as E,sV as F,Tx as G,ed as H,Hx as I,ur as J,$x as K,ZO as L,dr as M,Lq as N,NL as O,Fa as P,iV as Q,NH as R,pt as S,fs as T,Xq as U,Bt as V,g1 as W,rV as X,w2 as Y,Mu as Z,Rf as _,Yx as a,AN as a$,Wr as a0,Qp as a1,Qq as a2,Kj as a3,yp as a4,Cq as a5,yL as a6,qb as a7,Vq as a8,Ii as a9,i5 as aA,I6 as aB,P6 as aC,$6 as aD,Fq as aE,Qj as aF,$q as aG,Uq as aH,Mx as aI,Dx as aJ,np as aK,oV as aL,vt as aM,jN as aN,aV as aO,NN as aP,TN as aQ,Lu as aR,Fr as aS,zr as aT,H6 as aU,W6 as aV,u1 as aW,Ab as aX,q6 as aY,Do as aZ,ph as a_,Sq as aa,Hq as ab,_y as ac,ia as ad,Pu as ae,Up as af,Ea as ag,pr as ah,Rx as ai,VD as aj,On as ak,zR as al,qD as am,Yq as an,Gq as ao,Kq as ap,qq as aq,r1 as ar,rS as as,Oq as at,Xj as au,Xt as av,$H as aw,TT as ax,sh as ay,HD as az,iL as b,da as b0,DN as b1,u5 as b2,Ry as b3,mx as b4,y4 as b5,n1 as b6,Tq as b7,Iq as b8,_q as b9,Pq as ba,Bq as bb,Rq as bc,Mq as bd,zq as be,Kp as bf,IL as bg,b2 as bh,y2 as bi,Jq as bj,_o as bk,Ju as bl,TL as bm,Zq as bn,nV as bo,eV as bp,Dq as bq,Eq as br,tV as bs,$R as bt,UR as bu,su as bv,Ox as bw,Wq as c,oL as d,Ay as e,Rs as f,TH as g,Ta as h,Kl as i,o as j,yS as k,Na as l,Tn as m,jq as n,Aq as o,Nf as p,Fx as q,x as r,U as s,Nq as t,dt as u,Yb as v,Rt as w,YR as x,GR as y,Ce as z};
151
+ `):[],[y]),C=x.useMemo(()=>w.map(S=>Kl(S||" ")),[w]),N=x.useMemo(()=>b?f&&!y?"No log lines match the current filter.":null:"Waiting for logs...",[b,f,y]),k=DN({count:C.length,getScrollElement:()=>i.current,estimateSize:()=>20,overscan:12,measureElement:S=>S.getBoundingClientRect().height}),j=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:j.map(S=>o.jsx("div",{ref:k.measureElement,className:"guake-bottom-pm2-log-line","data-index":S.index,style:{transform:`translateY(${S.start}px)`},dangerouslySetInnerHTML:{__html:C[S.index]}},S.key))})})});x.memo(function({src:e,title:n}){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:n,allow:"clipboard-read; clipboard-write",loading:"lazy",tabIndex:-1,onLoad:()=>{r(!0),d(),f()}})]})});const nW=x.memo(function({onSaveSnapshot:e}={}){var xd,Ko,ti,yd,mc;const{t:n}=dt(["terminal","common"]),s=ed(),a=$x(),r=e1(),i=Ux(),c=r1(),d=i1(),f=t1(),h=Wx(),m=qx(),b=lL(),y=!!b,w=x.useMemo(()=>b?{id:b.agentId,name:b.agentName,class:b.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:b.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:b.createdAt,lastActivity:b.createdAt}:null,[b]),C=Array.from(a),k=C.length===1?C[0]:null,S=(Kj(k)||null)??(y?w:null),T=k??(y?(b==null?void 0:b.agentId)??null:null),D=!!(S!=null&&S.sessionId)&&!y,E=ur(),I=Hx(),O=x.useMemo(()=>{if(!T)return null;const Q=new Set,ue=[];for(const Ee of E.values())Ee.archived||Ee.directories.length===0||Ee.assignedAgentIds.includes(T)&&(Q.add(Ee.id),ue.push(Ee));const le=s.get(T);if(le)for(const Ee of E.values())Ee.archived||Ee.directories.length===0||Q.has(Ee.id)||Z5({x:le.position.x,z:le.position.z},Ee)&&(Q.add(Ee.id),ue.push(Ee));return ue.length===0?null:ue.flatMap(Ee=>Ee.directories.filter(nt=>nt&&nt.trim().length>0).map(nt=>({areaId:Ee.id,areaName:Ee.name,dir:nt})))},[T,E,s]),_=x.useMemo(()=>{var le;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Ee of I.values())Ee.type==="terminal"&&U.isPositionInArea(Ee.position,Q)&&ue.push({id:Ee.id,name:Ee.name,hasUrl:!!((le=Ee.terminalStatus)!=null&&le.url)});return ue},[T,I,E]),M=x.useMemo(()=>{var le;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Ee of I.values())Ee.type==="server"&&((le=Ee.pm2)!=null&&le.enabled)&&U.isPositionInArea(Ee.position,Q)&&ue.push({id:Ee.id,name:Ee.name});return ue},[T,I,E]),R=x.useMemo(()=>{if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const le of I.values())le.type==="database"&&le.database&&U.isPositionInArea(le.position,Q)&&ue.push({id:le.id,name:le.name});return ue},[T,I,E]),{branches:z,fetchRemote:$,fetchingDirs:W}=WH(O),{terminalHeight:L,terminalRef:F,handleResizeStart:H}=MH(),{mobileOverviewHeight:V,handleResizeMouseDown:G,handleResizeTouchStart:B}=OH(),K=EH(),[ne,q]=x.useState(()=>{const Q=Mx(pt.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,Q))}),xe=x.useRef(null),Ae=x.useCallback((Q,ue)=>{Q.preventDefault(),xe.current={startX:Q.clientX,startW:ne},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",U.setTerminalResizing(!0);let le=ne;const Ee=ut=>{if(!xe.current)return;const Nt=ut.clientX-xe.current.startX,_t=ue==="left"?-Nt:Nt;le=Math.max(280,Math.min(700,xe.current.startW+_t)),q(le)},nt=()=>{xe.current=null,document.body.style.cursor="",document.body.style.userSelect="",U.setTerminalResizing(!1),document.removeEventListener("mousemove",Ee),document.removeEventListener("mouseup",nt),Dx(pt.SIDE_PANEL_WIDTH,le)};document.addEventListener("mousemove",Ee),document.addEventListener("mouseup",nt)},[ne]),Z=Qj(T),ce=x.useMemo(()=>y&&b?b.outputs.map(Q=>({text:Q.text||"",timestamp:Q.timestamp,isStreaming:!1,isUserPrompt:!1})):Z,[y,b,Z]),me=x.useRef(null),ee=x.useRef(null),re=x.useRef(null),We=x.useRef(null),[ze,Pe]=x.useState(()=>{const Q=Fa(pt.VIEW_MODE);return Q==="simple"||Q==="chat"||Q==="advanced"?Q:Fa(pt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[ge,Te]=x.useState(()=>Ni(pt.TERMINAL_FULLSCREEN,!1)),[qe,it]=x.useState(null),[he,Be]=x.useState(null),[ie,de]=x.useState(null),[He,et]=x.useState(null),[ct,fe]=x.useState(!1);Xt("guake-image-modal",qe!==null,()=>it(null)),Xt("guake-bash-modal",he!==null,()=>Be(null)),Xt("guake-response-modal",He!==null,()=>et(null)),Xt("guake-context-confirm",ie!==null,()=>de(null)),Xt("guake-agent-info",ct,()=>fe(!1));const[X,se]=x.useState(!1),[Se,J]=x.useState(()=>vs.isEnabled()),[pe,Re]=x.useState(()=>Ni(pt.GIT_PANEL_OPEN,!1)),$e=x.useCallback(Q=>{Re(Q),Ti(pt.GIT_PANEL_OPEN,Q)},[]),[ye,Ie]=x.useState(()=>Ni(pt.BUILDINGS_PANEL_OPEN,!1)),te=x.useCallback(Q=>{Ie(Q),Ti(pt.BUILDINGS_PANEL_OPEN,Q)},[]),[be,we]=x.useState(()=>Ni(pt.WORKFLOW_PANEL_OPEN,!1)),Fe=x.useCallback(Q=>{we(Q),Ti(pt.WORKFLOW_PANEL_OPEN,Q)},[]),[Ke,st]=x.useState(!1);x.useEffect(()=>{if(!T){st(!1);return}let Q=!1;return(async()=>{try{const ue=await Bt(Rt("/api/workflows/definitions"));if(Q||!ue.ok)return;const Ee=(await ue.json()).some(nt=>nt.states.some(ut=>{var Nt,_t;return((Nt=ut.action)==null?void 0:Nt.type)==="agent_task"&&((_t=ut.action)==null?void 0:_t.agentId)===T}));Q||st(Ee)}catch{Q||st(!1)}})(),()=>{Q=!0}},[T]);const ft=hL(),wt=x.useCallback(Q=>U.setOverviewPanelOpen(Q),[]),[rt,gt]=x.useState([]),[ht,Gt]=x.useState({}),[tn,je]=x.useState(()=>Vj()),[Oe,Ye]=x.useState(()=>{try{return localStorage.getItem("tide:bottom-split-direction")==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[Ze,Ot]=x.useState(()=>{try{const Q=localStorage.getItem("tide:bottom-terminal-height");return Q?Math.max(120,Math.min(600,Number(Q))):250}catch{return 250}}),Ft=x.useRef(null),[Lt,Vt]=x.useState([1]),ln=x.useRef(null),bt=x.useRef(null),[at,xt]=x.useState(null),[$t,En]=x.useState(null),nn=x.useMemo(()=>rt.filter(Q=>Q.areaId===$t),[rt,$t]),Un=x.useMemo(()=>new Set(nn.map(Q=>Q.buildingId)),[nn]),Os=x.useRef(new Map);x.useEffect(()=>{try{const Q=localStorage.getItem("tide:bottom-panels-v2");if(Q){const ue=JSON.parse(Q);Os.current=new Map(ue.map(([le,Ee])=>[le,Ee.map(nt=>({id:nt.id??Xf(),type:nt.type,buildingId:nt.buildingId}))]))}else{const ue=localStorage.getItem("tide:bottom-terminals");if(ue){const le=JSON.parse(ue);for(const[Ee,nt]of le)Os.current.set(Ee,[{id:Xf(),type:"terminal",buildingId:nt}])}}}catch{}},[]);const ps=x.useCallback(Q=>{if(!T)return;const ue=U.getAreaForAgent(T);if(ue)try{Q.length>0?Os.current.set(ue.id,Q.map(Ee=>({id:Ee.id,type:Ee.type,buildingId:Ee.buildingId}))):Os.current.delete(ue.id);const le=Array.from(Os.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(le))}catch{}},[T]),ks=x.useCallback(()=>{if(!T)return null;const Q=U.getAreaForAgent(T);return(Q==null?void 0:Q.id)??null},[T]),Qn=x.useCallback((Q,ue)=>{const le=ks();Gt({}),gt(Ee=>{for(const _t of Ee)_t.areaId===le&&_t.type==="pm2-logs"&&U.stopLogStreaming(_t.buildingId);const nt=Ee.filter(_t=>_t.areaId!==le),ut={id:Xf(),type:ue,buildingId:Q,areaId:le??void 0},Nt=[...nt,ut];return ps([ut]),Nt})},[ps,ks]),Ss=x.useCallback((Q,ue,le)=>{const Ee=ks();Ye(le);try{localStorage.setItem("tide:bottom-split-direction",le)}catch{}gt(nt=>{const ut=nt.filter(sn=>sn.areaId===Ee);if(ut.length>=4||ut.some(sn=>sn.buildingId===Q))return nt;const Nt={id:Xf(),type:ue,buildingId:Q,areaId:Ee??void 0},_t=[...nt,Nt];return ps(ut.concat(Nt)),_t})},[ps,ks]),Fn=x.useCallback(Q=>{Gt(ue=>{if(!(Q in ue))return ue;const le={...ue};return delete le[Q],le}),gt(ue=>{const le=ue.find(ut=>ut.id===Q);(le==null?void 0:le.type)==="pm2-logs"&&U.stopLogStreaming(le.buildingId);const Ee=ue.filter(ut=>ut.id!==Q),nt=le==null?void 0:le.areaId;return nt&&ps(Ee.filter(ut=>ut.areaId===nt)),Ee})},[ps]);x.useCallback(()=>{Gt({}),gt(Q=>{for(const ue of Q)ue.type==="pm2-logs"&&U.stopLogStreaming(ue.buildingId);return ps([]),[]})},[ps]),x.useEffect(()=>{if(!T){En(null);return}const Q=U.getAreaForAgent(T);if(!Q){En(null);return}En(Q.id),gt(ue=>{if(ue.filter(ut=>ut.areaId===Q.id).length>0)return ue;const Ee=Os.current.get(Q.id);if(!Ee||Ee.length===0)return ue;const nt=Ee.map(ut=>({id:ut.id,type:ut.type,buildingId:ut.buildingId,areaId:Q.id}));return[...ue,...nt]})},[T]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&Qn(le.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",Q),()=>window.removeEventListener("tide:open-bottom-terminal",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&Qn(le.buildingId,"pm2-logs")};return window.addEventListener("tide:open-bottom-pm2-logs",Q),()=>window.removeEventListener("tide:open-bottom-pm2-logs",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&Qn(le.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",Q),()=>window.removeEventListener("tide:open-bottom-database",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const le=ue.detail;le!=null&&le.buildingId&&(le!=null&&le.type)&&(le!=null&&le.direction)&&(nn.length===0?Qn(le.buildingId,le.type):Ss(le.buildingId,le.type,le.direction))};return window.addEventListener("tide:split-bottom-panel",Q),()=>window.removeEventListener("tide:split-bottom-panel",Q)},[nn.length,Qn,Ss]),x.useEffect(()=>{Vt(Q=>Q.length===nn.length?Q:nn.length<=1?[1]:(nn.length>Q.length,Array(nn.length).fill(1)))},[nn.length]);const Ls=x.useCallback((Q,ue)=>{var sn;Q.preventDefault();const le=Oe==="horizontal";ln.current={index:ue,startPos:le?Q.clientX:Q.clientY,startRatios:[...Lt]},document.body.style.cursor=le?"col-resize":"row-resize",document.body.style.userSelect="none";const Ee=(sn=bt.current)==null?void 0:sn.querySelectorAll("iframe");Ee==null||Ee.forEach(gn=>gn.style.pointerEvents="none");const nt=bt.current,ut=nt?le?nt.offsetWidth:nt.offsetHeight:1,Nt=gn=>{const qn=ln.current;if(!qn||!nt)return;const Qo=(le?gn.clientX:gn.clientY)-qn.startPos,Ki=qn.startRatios.reduce((bc,vd)=>bc+vd,0),gc=Qo/ut*Ki,Xo=[...qn.startRatios],Jo=.1*Ki;Xo[ue]=Math.max(Jo,qn.startRatios[ue]+gc),Xo[ue+1]=Math.max(Jo,qn.startRatios[ue+1]-gc),Vt(Xo)},_t=()=>{ln.current=null,document.body.style.cursor="",document.body.style.userSelect="",Ee==null||Ee.forEach(gn=>gn.style.pointerEvents=""),document.removeEventListener("mousemove",Nt),document.removeEventListener("mouseup",_t)};document.addEventListener("mousemove",Nt),document.addEventListener("mouseup",_t)},[Oe,Lt]),Is=x.useRef(new Set);x.useEffect(()=>{const Q=new Set(rt.filter(ue=>ue.type==="pm2-logs").map(ue=>ue.buildingId));for(const ue of Q)Is.current.has(ue)||U.startLogStreaming(ue,200);Is.current=Q},[rt]);const wn=x.useRef(new Set);x.useEffect(()=>{var le;const Q=rt.filter(Ee=>Ee.type==="terminal");for(const Ee of Q){const nt=I.get(Ee.buildingId);!!((le=nt==null?void 0:nt.terminalStatus)!=null&&le.url)?wn.current.add(Ee.buildingId):wn.current.has(Ee.buildingId)&&(wn.current.delete(Ee.buildingId),Fn(Ee.id))}const ue=new Set(Q.map(Ee=>Ee.buildingId));for(const Ee of wn.current)ue.has(Ee)||wn.current.delete(Ee)},[rt,I,Fn]);const Po=x.useCallback(Q=>{Q.preventDefault(),Ft.current={startY:Q.clientY,startH:Ze};let ue=Ze;const le=nt=>{if(!Ft.current)return;const ut=Ft.current.startY-nt.clientY;ue=Math.max(120,Math.min(600,Ft.current.startH+ut)),Ot(ue)},Ee=()=>{Ft.current=null,document.removeEventListener("mousemove",le),document.removeEventListener("mouseup",Ee);try{localStorage.setItem("tide:bottom-terminal-height",String(ue))}catch{}};document.addEventListener("mousemove",le),document.addEventListener("mouseup",Ee)},[Ze]),[Bo,Ps]=x.useState(!1),[Ua,Bi]=x.useState(null),Fi=x.useRef(null),Bs=x.useRef(null),[lc,Ma]=x.useState(!1),[Ts,hs]=x.useState(!1),[Mn,zi]=x.useState(!1),[Ne,Je]=x.useState(!1),Ct=x.useRef(0),ot=r&&S!==null,jn=x.useRef([]),Mt=x.useRef(-1),At=x.useRef(!1),kn=x.useRef(!1),ms=x.useRef(!1),Dn=x.useRef(null),[Fs,Qr]=x.useState(!1),[pa,mh]=x.useState(!1),ha=x.useCallback(()=>{const Q=jn.current,ue=Mt.current;Qr(ue>0),mh(ue>=0&&ue<Q.length-1)},[]),$i=x.useCallback(Q=>{const ue=jn.current;if(ue.length===0)return;let le=Mt.current+Q;for(;le>=0&&le<ue.length;){const Ee=ue[le];if(s.has(Ee)){At.current=!0,Mt.current=le,ha(),U.selectAgent(Ee);return}le+=Q}},[s,ha]),gr=x.useCallback(()=>{$i(-1)},[$i]),Ui=x.useCallback(()=>{$i(1)},[$i]),cc=x.useCallback((Q,ue)=>{if(typeof window>"u")return;const le=window.history.state,nt={...typeof le=="object"&&le!==null?le:{},__guakeAgentNav:{agentId:Q}};ue==="replace"?window.history.replaceState(nt,"",window.location.href):window.history.pushState(nt,"",window.location.href)},[]),Fo=x.useCallback(()=>{Te(Q=>{const ue=!Q;return Ti(pt.TERMINAL_FULLSCREEN,ue),ue})},[]),It=Wj({selectedAgentId:T,hasSessionId:D,reconnectCount:c,historyRefreshTrigger:d,lastPrompts:i,outputScrollRef:me}),Hn=LH({agents:s,selectedAgentId:T,isOpen:ot,overviewPanelOpen:ft,loadingHistory:It.fetchingHistory,hasModalOpen:!!(qe||he||He||h||m),outputRef:me});x.useEffect(()=>{const Q=F.current;if(!Q||!ot)return;const ue=Ee=>{Ee.button===3?(Ee.preventDefault(),Ee.stopPropagation(),gr()):Ee.button===4&&(Ee.preventDefault(),Ee.stopPropagation(),Ui())},le=Ee=>{(Ee.button===3||Ee.button===4)&&Ee.preventDefault()};return Q.addEventListener("mouseup",ue),Q.addEventListener("mousedown",le),()=>{Q.removeEventListener("mouseup",ue),Q.removeEventListener("mousedown",le)}},[ot,gr,Ui]);const uc=x.useCallback(Q=>{U.setLastSelectionViaDirectClick(!0),U.selectAgent(Q)},[]),Xr=typeof window<"u"&&window.innerWidth<=768&&ft&&ot,Jr=tR({gestureRef:me,agentListRef:ee,enabled:Xr,onSelect:uc}),ts=$H({selectedAgentId:k}),zo=KO(),cd=x.useMemo(()=>y||!T?[]:Array.from(zo.values()).filter(Q=>Q.agentId===T&&Q.status==="pending"),[y,T,zo]),Ha=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),zs=nL(!y&&Ha?T:null),Hi=x.useMemo(()=>Array.from(zs.values()).filter(Q=>Q.status==="working"),[zs]),br=x.useMemo(()=>Array.from(zs.values()).filter(Q=>Q.status==="completed"||Q.status==="failed").map(Q=>Q.agentId),[zs]),[ma,$o]=x.useState(!0),Uo=sL(y?null:T),ud=pL(y?null:T);x.useEffect(()=>{X&&!Se&&(J(!0),vs.setEnabled(!0))},[X,Se]),x.useEffect(()=>{ot||fe(!1)},[ot]),x.useEffect(()=>{if(!T||!Ha||y||br.length===0)return;const Q=window.setTimeout(()=>{br.forEach(ue=>{U.clearAgentTaskProgress(T,ue)})},300);return()=>window.clearTimeout(Q)},[T,Ha,y,br]),x.useEffect(()=>{const Q=S==null?void 0:S.status;if(Fi.current==="working"&&Q==="idle"){Bs.current&&clearTimeout(Bs.current);const le=T?i.get(T):void 0;Bi(le!=null&&le.timestamp?Date.now()-le.timestamp:null),Ps(!0),Bs.current=setTimeout(()=>{Ps(!1),Bi(null),Bs.current=null},4e3)}else Q==="working"&&(Bs.current&&(clearTimeout(Bs.current),Bs.current=null),Ps(!1),Bi(null));return Fi.current=Q||null,()=>{Bs.current&&clearTimeout(Bs.current)}},[S==null?void 0:S.status]);const Wi=x.useMemo(()=>{const{history:Q}=It,ue=new Map;for(const Ee of Q)Ee.type==="tool_result"&&Ee.toolUseId&&ue.set(Ee.toolUseId,Ee.content);return(Ee=>Ee.map(nt=>{if(nt.type==="tool_use"&&nt.toolName==="Bash"&&nt.toolUseId){const ut=ue.get(nt.toolUseId);let Nt;try{Nt=(nt.toolInput||(nt.content?JSON.parse(nt.content):{})).command}catch{}return{...nt,_bashOutput:ut,_bashCommand:Nt}}return nt}))(Q)},[It.history,ze]),qi=_T({outputs:ce,viewMode:ze}),Wa=x.useMemo(()=>{const Q=[],ue=new Set,le=new Set;let Ee=null,nt=0;for(const ut of Wi){if(ut.type==="assistant"){const gn=ut.uuid?`uuid:${ut.uuid}:${Qf(ut.content)}`:`sig:${ut.timestamp}:${Qf(ut.content)}`;if(ue.has(gn))continue;ue.add(gn),Q.push(ut);continue}if(ut.type!=="user"){Q.push(ut);continue}const Nt=Eb(ut.content),_t=ut.uuid?`uuid:${ut.uuid}:${Nt}`:null;if(_t&&le.has(_t))continue;const sn=ut.timestamp?new Date(ut.timestamp).getTime():0;Ee===Nt&&Math.abs(sn-nt)<=VA||(Q.push(ut),_t&&le.add(_t),Ee=Nt,nt=sn)}return Q},[Wi]),Wn=x.useMemo(()=>{const Q=new Map,ue=new Set,le=new Map;for(const Nt of Wa){const _t=Nt.timestamp?new Date(Nt.timestamp).getTime():0;if(Nt.type==="user"){const qn=Eb(Nt.content),Va=Q.get(qn)??0;_t>Va&&Q.set(qn,_t);continue}if(Nt.type!=="assistant")continue;Nt.uuid&&ue.add(Nt.uuid);const sn=Qf(Nt.content),gn=le.get(sn)??0;_t>gn&&le.set(sn,_t)}const Ee=[];let nt=null,ut=0;for(const Nt of qi){if(!Nt.isUserPrompt){if(!Nt.isStreaming&&!J5(Nt.text)){if(Nt.uuid&&ue.has(Nt.uuid))continue;const qn=Qf(Nt.text),Va=Nt.timestamp||0,Qo=le.get(qn);if(Qo&&Math.abs(Va-Qo)<=K5)continue}Ee.push(Nt);continue}const _t=Eb(Nt.text),sn=Nt.timestamp||0,gn=Q.get(_t);gn&&sn>=gn&&sn-gn<=G5||nt===_t&&Math.abs(sn-ut)<=VA||(Ee.push(Nt),nt=_t,ut=sn)}return Ee},[qi,Wa]),xr=x.useMemo(()=>[...Wa,...Wn],[Wa,Wn]),Ln=BH({selectedAgentId:T,isOpen:ot,allItems:xr,viewMode:ze,hasMoreHistory:It.hasMore,loadAllHistory:It.loadAllHistory,loadingMore:It.loadingMore}),Vi=Wa.length+Wn.length,dd=UH({totalMessages:Vi,isOpen:ot,hasModalOpen:!!(qe||he||He||h),scrollContainerRef:me,selectedAgentId:T,inputRef:re,textareaRef:We,useTextarea:ts.useTextarea});x.useEffect(()=>{if(!(!(he!=null&&he.isLive)||!he.command)){for(const Q of Wn)if(Q._bashCommand===he.command&&Q._bashOutput){Be({command:he.command,output:Q._bashOutput,isLive:!1});return}}},[he,Wn]);const Ho=x.useCallback((Q,ue)=>{it({url:Q,name:ue})},[]),Wo=x.useCallback((Q,ue)=>{const le=sh(Q,S==null?void 0:S.cwd),Ee=le.line?{...ue||{},targetLine:le.line}:ue;U.setFileViewerPath(le.path,Ee,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),Zr=x.useCallback((Q,ue)=>{Be({command:Q,output:ue,isLive:ue==="Running..."})},[]),qo=x.useCallback(Q=>{et(Q)},[]),fd=x.useCallback(()=>{fe(Q=>!Q)},[]),[gh,Vo]=x.useState(!0),[pd,ei]=x.useState(0),[dc,fc]=x.useState(!1),Yi=x.useRef(!1),pc=x.useRef(!1),Yo=x.useRef(!1),hd=x.useCallback(()=>{Yo.current||(Yi.current=!0,Vo(!1))},[]),bh=x.useCallback(()=>hs(!1),[]),xh=x.useCallback(()=>{Yi.current=!1,Vo(!0)},[]),yh=x.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(fc(!0),ei(Q5),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{U.setMobileView("3d"),fc(!1),ei(0)},X5))},[]),vh=x.useCallback(Q=>{dc||ei(Q)},[dc]);x.useEffect(()=>{Vo(!0),ei(0),fc(!1),Yi.current=!1,pc.current=!0,Yo.current=!0;const Q=setTimeout(()=>{Yo.current=!1},3e3);return()=>clearTimeout(Q)},[T]),x.useEffect(()=>{if(!T){jn.current=[],Mt.current=-1,ha(),ms.current=!1,Dn.current=null;return}const Q=jn.current;if(At.current){At.current=!1,ha();return}const ue=Mt.current;if(ue>=0&&Q[ue]===T){ha();return}const le=ue<Q.length-1?Q.slice(0,ue+1):Q.slice();le.push(T),le.length>100&&le.shift(),jn.current=le,Mt.current=le.length-1,ha()},[T,ha]),x.useEffect(()=>{if(!(!ot||!T)){if(!ms.current){cc(T,"replace"),ms.current=!0,Dn.current=T;return}if(kn.current){kn.current=!1,Dn.current=T;return}Dn.current!==T&&(cc(T,"push"),Dn.current=T)}},[ot,T,cc]),x.useEffect(()=>{if(!ot)return;const Q=ue=>{var ut,Nt;const le=(Nt=(ut=ue.state)==null?void 0:ut.__guakeAgentNav)==null?void 0:Nt.agentId;if(!le||typeof le!="string"||!s.has(le)||le===k)return;kn.current=!0,At.current=!0;const Ee=jn.current,nt=Ee.lastIndexOf(le);nt>=0?Mt.current=nt:(Ee.push(le),Mt.current=Ee.length-1),ha(),U.selectAgent(le)};return window.addEventListener("popstate",Q),()=>window.removeEventListener("popstate",Q)},[ot,s,k,ha]),x.useEffect(()=>{if(!pc.current||!T||Mn||It.fetchingHistory)return;let Q=0,ue=0;return Q=requestAnimationFrame(()=>{ue=requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=me.current.scrollHeight),pc.current=!1})}),()=>{cancelAnimationFrame(Q),cancelAnimationFrame(ue)}},[T,Mn,It.fetchingHistory,It.historyLoadVersion]);const Go=x.useRef(It.handleScroll);Go.current=It.handleScroll;const wh=x.useCallback(()=>{if(!me.current||K.keyboardScrollLockRef.current)return;const{scrollTop:Q,scrollHeight:ue,clientHeight:le}=me.current,Ee=ue-Q-le<150;Yo.current||(Yi.current=!Ee,Ee&&Vo(!0)),Go.current(K.keyboardScrollLockRef)},[me,K.keyboardScrollLockRef]),kh=Z.length>0&&((Ko=(xd=Z[Z.length-1])==null?void 0:xd.text)==null?void 0:Ko.length)||0;x.useEffect(()=>{K.keyboardScrollLockRef.current||Yi.current||requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=me.current.scrollHeight)})},[Z.length,kh,K.keyboardScrollLockRef,me]);const md=x.useRef(null);x.useLayoutEffect(()=>{const Q=md.current;Q!==null&&Q!==k?(Ma(!1),k&&It.hasCachedHistory(k)||zi(!0),U.getState().currentSnapshot&&U.setCurrentSnapshot(null)):k||Ma(!1),md.current=k},[k]),x.useEffect(()=>{if(!Mn||It.fetchingHistory)return;const Q=requestAnimationFrame(()=>{me.current&&(me.current.scrollTop=me.current.scrollHeight),zi(!1)});return()=>cancelAnimationFrame(Q)},[Mn,It.fetchingHistory,It.historyLoadVersion]);const qa=x.useRef(!1);x.useEffect(()=>{ot&&k&&U.clearUnseenForAgent(k)},[ot,k]),x.useEffect(()=>{qa.current=!0,hs(!0)},[T,c]),x.useEffect(()=>{It.fetchingHistory&&(qa.current=!0,hs(!0))},[It.fetchingHistory]),x.useEffect(()=>{if(!Ts||!ot||It.fetchingHistory)return;const Q=me.current;if(!Q)return;let ue=null;const le=performance.now();let Ee=0,nt=-1;const ut=()=>{const{scrollTop:_t,scrollHeight:sn,clientHeight:gn}=Q;return sn-_t-gn<=2},Nt=()=>{const _t=performance.now(),sn=Q.scrollHeight,gn=Math.abs(sn-nt)<=1,qn=ut();if(gn&&qn?Ee+=1:Ee=0,nt=sn,Ee>=3){hs(!1),ue=null;return}if(_t-le>8e3){hs(!1),ue=null;return}ue=requestAnimationFrame(Nt)};return ue=requestAnimationFrame(Nt),()=>{ue!==null&&cancelAnimationFrame(ue)}},[Ts,ot,It.fetchingHistory,It.historyLoadVersion]);const gd=x.useRef(!1);x.useEffect(()=>{gd.current&&!Ts&&qa.current&&(qa.current=!1,Ma(!0)),gd.current=Ts},[Ts]),x.useEffect(()=>{if(!ot||!qa.current||Ts||It.fetchingHistory)return;const Q=requestAnimationFrame(()=>{qa.current&&(qa.current=!1,Ma(!0))});return()=>cancelAnimationFrame(Q)},[It.historyLoadVersion,ot,Ts,It.fetchingHistory]),x.useEffect(()=>{const Q=ue=>{if(ue.key==="`"&&!ue.ctrlKey&&!ue.altKey&&S){const le=ue.target;le.tagName!=="INPUT"&&le.tagName!=="TEXTAREA"&&(ue.preventDefault(),U.toggleTerminal())}};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[S]),x.useEffect(()=>{if(!ot)return;const Q=ue=>{ue.altKey&&(ue.key!=="ArrowLeft"&&ue.key!=="ArrowRight"||(ue.key==="ArrowLeft"&&Fs?(ue.preventDefault(),gr()):ue.key==="ArrowRight"&&pa&&(ue.preventDefault(),Ui())))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[ot,Fs,pa,gr,Ui]),x.useEffect(()=>{const Q=ue=>{ue.key==="Escape"&&(h?(ue.stopImmediatePropagation(),U.clearFileViewerPath()):m?(ue.stopImmediatePropagation(),U.closeContextModal()):He?(ue.stopImmediatePropagation(),et(null)):he?(ue.stopImmediatePropagation(),Be(null)):qe?(ue.stopImmediatePropagation(),it(null)):Ln.searchMode&&(ue.stopImmediatePropagation(),Ln.closeSearch()))};return document.addEventListener("keydown",Q,!0),()=>document.removeEventListener("keydown",Q,!0)},[qe,he,He,Ln,h,m]);const bd=x.useRef(ot),Gi=x.useRef(!1);x.useEffect(()=>{bd.current=ot},[ot]),x.useEffect(()=>{if(window.innerWidth<=768)return;const ue=nt=>{var sn;if(!(nt instanceof Element))return!1;const ut=(sn=F.current)==null?void 0:sn.contains(nt),Nt=nt.closest(".agent-bar"),_t=!!nt.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");return!!ut||!!Nt||_t},le=nt=>{if(!bd.current){Gi.current=!1;return}if(XD("terminal")){Gi.current=!1;return}Gi.current=!ue(nt.target)},Ee=nt=>{Gi.current&&(ue(nt.target)||U.setTerminalOpen(!1),Gi.current=!1)};return document.addEventListener("mousedown",le,!0),document.addEventListener("mouseup",Ee,!0),()=>{document.removeEventListener("mousedown",le,!0),document.removeEventListener("mouseup",Ee,!0)}},[]),x.useEffect(()=>{const Q=()=>{document.hidden&&K.cleanup()};return document.addEventListener("visibilitychange",Q),()=>document.removeEventListener("visibilitychange",Q)},[K]),x.useEffect(()=>()=>K.cleanup(),[T,K]);const hc=typeof window<"u"&&window.innerWidth<=768;if(!S)return hc&&f==="terminal"&&a.size===0?o.jsx("div",{ref:F,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${L}%`},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:n("terminal:empty.tapAgent")}),o.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:n("terminal:empty.switchTo3D")})]})})})}):hc&&f==="terminal"&&a.size>0?o.jsx("div",{ref:F,className:`guake-terminal open ${ge?"fullscreen":""}`,style:{"--terminal-height":`${L}%`},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:[n("terminal:empty.loadingTerminal"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]})})})}):null;if(!T)return null;const Sh=Q=>{Q.preventDefault(),Q.stopPropagation(),Ct.current++,Q.dataTransfer.types.includes("Files")&&Je(!0)},Ch=Q=>{Q.preventDefault(),Q.stopPropagation()},Ah=Q=>{Q.preventDefault(),Q.stopPropagation(),Ct.current--,Ct.current===0&&Je(!1)},jh=async Q=>{Q.preventDefault(),Q.stopPropagation(),Ct.current=0,Je(!1);const ue=Q.dataTransfer.files;if(ue.length)for(const le of ue){const Ee=await ts.uploadFile(le);Ee&&ts.setAttachedFiles(nt=>[...nt,Ee])}};return o.jsxs("div",{ref:F,className:`guake-terminal ${ot?"open":"collapsed"} ${ge&&ot?"fullscreen":""} ${X&&ot?"with-debug-panel":""} ${pe&&ot?"with-git-panel":""} ${ye&&ot?"with-buildings-panel":""} ${be&&ot?"with-workflow-panel":""} ${ft&&ot?"with-overview-panel":""} ${Ne?"drag-over":""} ${pd>0?"mobile-swipe-close-active":""} ${dc?"mobile-swipe-close-closing":""}`,style:{"--terminal-height":`${L}%`,"--mobile-swipe-close-offset":`${pd}px`,"--guake-side-panel-width":`${ne}px`,...V>0?{"--guake-mobile-overview-height":`${V}px`}:{}},onDragEnter:Sh,onDragOver:Ch,onDragLeave:Ah,onDrop:jh,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:n("terminal:input.dropToAttach")})]}),!y&&X&&ot&&T&&o.jsx(o5,{agentId:T,onClose:()=>se(!1)}),!y&&pe&&ot&&T&&o.jsx(b5,{agentId:T,agents:s,onClose:()=>$e(!1),branchInfoMap:z,fetchRemote:$,fetchingDirs:W}),!y&&ye&&ot&&T&&o.jsx(D5,{agentId:T,onClose:()=>te(!1)}),!y&&be&&ot&&T&&o.jsx(L5,{agentId:T,onClose:()=>Fe(!1)}),!y&&(X||pe||ye||be)&&ot&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:Q=>Ae(Q,"right")}),!y&&ft&&ot&&T&&o.jsx(_5,{activeAgentId:T,onClose:()=>wt(!1),onSelectAgent:Q=>{U.setLastSelectionViaDirectClick(!0),U.selectAgent(Q)},agentListRef:ee,twoFingerState:Jr}),!y&&ft&&ot&&T&&o.jsx("div",{className:"guake-side-panel-resize left",onMouseDown:Q=>Ae(Q,"left")}),!y&&ft&&ot&&T&&o.jsx("div",{className:"aop-resize-handle",onMouseDown:G,onTouchStart:B}),o.jsxs("div",{className:"guake-content",children:[o.jsx(A6,{selectedAgent:S,selectedAgentId:T,sortedAgents:Hn.sortedAgents,swipeOffset:Hn.swipeOffset,viewMode:ze,setViewMode:Pe,searchMode:Ln.searchMode,toggleSearch:Ln.toggleSearch,closeSearch:Ln.closeSearch,debugPanelOpen:X,setDebugPanelOpen:se,debuggerEnabled:Se,setDebuggerEnabled:J,gitPanelOpen:pe,setGitPanelOpen:$e,buildingsPanelOpen:ye,setBuildingsPanelOpen:te,workflowPanelOpen:be,setWorkflowPanelOpen:Fe,hasWorkflow:Ke,overviewPanelOpen:ft,setOverviewPanelOpen:wt,agentInfoOpen:ct,onToggleAgentInfo:fd,isFullscreen:ge,onToggleFullscreen:Fo,onNavigateBack:gr,onNavigateForward:Ui,canNavigateBack:Fs,canNavigateForward:pa,outputsLength:Wa.length+Wn.length,setContextConfirm:de,headerRef:Hn.headerRef,onSaveSnapshot:y?void 0:e,isSnapshotView:y}),Ln.searchMode&&o.jsx(j6,{searchInputRef:Ln.searchInputRef,searchQuery:Ln.searchQuery,setSearchQuery:Ln.setSearchQuery,closeSearch:Ln.closeSearch,matchCount:Ln.matchIndices.length,currentMatch:Ln.currentMatch,navigateNext:Ln.navigateNext,navigatePrev:Ln.navigatePrev,loadingFullHistory:Ln.loadingFullHistory}),o.jsxs("div",{className:`guake-swipe-container ${Hn.swipeAnimationClass}`,style:Hn.swipeOffset!==0?{transform:`translateX(${Hn.swipeOffset*40}%)`}:void 0,children:[Hn.sortedAgents.length>1&&Hn.swipeOffset!==0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`swipe-indicator left ${Hn.swipeOffset>.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-icon",children:"←"}),o.jsx("span",{className:"indicator-name",children:(ti=Hn.nextAgent)==null?void 0:ti.name})]}),o.jsxs("div",{className:`swipe-indicator right ${Hn.swipeOffset<-.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-name",children:(yd=Hn.prevAgent)==null?void 0:yd.name}),o.jsx("span",{className:"indicator-icon",children:"→"})]})]}),Hn.sortedAgents.length>1&&Hn.sortedAgents.length<=8&&Hn.swipeOffset!==0&&o.jsx("div",{className:`swipe-dots ${Math.abs(Hn.swipeOffset)>.1?"visible":""}`,children:Hn.sortedAgents.map((Q,ue)=>o.jsx("div",{className:`swipe-dot ${ue===Hn.currentAgentIndex?"active":""}`},Q.id))}),o.jsx("div",{className:"guake-output",ref:me,onScroll:wh,children:o.jsxs("div",{className:`guake-history-content ${lc?"fade-in":""}`,children:[Mn&&o.jsxs("div",{className:"guake-empty loading",children:[n("terminal:empty.loadingConversation"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]}),!Mn&&It.loadingHistory&&It.history.length===0&&Z.length===0&&o.jsxs("div",{className:"guake-empty loading",children:[n("terminal:empty.loadingConversation"),o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})]}),!Mn&&!It.loadingHistory&&It.history.length===0&&ce.length===0&&S.status!=="working"&&o.jsx("div",{className:"guake-empty",children:n("terminal:empty.noOutput")}),!Mn&&It.hasMore&&!Ln.searchMode&&o.jsx("div",{className:"guake-load-more",children:It.loadingMore?o.jsx("span",{children:n("terminal:empty.loadingOlder")}):o.jsx("button",{onClick:It.loadMoreHistory,children:n("terminal:empty.loadMore",{count:It.totalCount-It.history.length})})}),!Mn&&o.jsx(i5,{historyMessages:Wa,liveOutputs:Wn,agentId:T,execTasks:Uo,subagents:ud,viewMode:ze,searchHighlight:Ln.highlightQuery,searchActiveIndex:Ln.scrollToIndex,selectedMessageIndex:dd.selectedIndex,isMessageSelected:dd.isSelected,onImageClick:Ho,onFileClick:Wo,onBashClick:Zr,onViewMarkdown:qo,scrollContainerRef:me,onScrollTopReached:It.loadMoreHistory,isLoadingMore:It.loadingMore,hasMore:It.hasMore,shouldAutoScroll:gh,onUserScroll:hd,pinToBottom:Ts,onPinCancel:bh,isLoadingHistory:It.fetchingHistory},T),!Mn&&Ha&&Hi.length>0&&o.jsxs("div",{className:`agent-progress-container ${ma?"collapsed":"expanded"}`,children:[o.jsxs("div",{className:"agent-progress-container-header",onClick:()=>$o(Q=>!Q),role:"button",tabIndex:0,onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),$o(ue=>!ue))},children:[o.jsx("span",{className:"progress-crown",children:"👑"}),o.jsx("span",{children:n("terminal:empty.subordinateProgress")}),o.jsx("span",{className:"progress-count",children:n("terminal:empty.activeCount",{count:Hi.length})}),o.jsx("span",{className:"agent-progress-container-toggle",children:ma?"▶":"▼"})]}),!ma&&Hi.map(Q=>o.jsx($5,{progress:Q,defaultExpanded:Q.status==="working",onAgentClick:ue=>{U.selectAgent(ue),U.setTerminalOpen(!0)},onDismiss:ue=>{T&&U.clearAgentTaskProgress(T,ue)},onFileClick:Wo,onBashClick:Zr},Q.agentId))]})]})})]}),o.jsx(O6,{selectedAgent:S,selectedAgentId:T,isOpen:ot,command:ts.command,setCommand:ts.setCommand,forceTextarea:ts.forceTextarea,setForceTextarea:ts.setForceTextarea,useTextarea:ts.useTextarea,attachedFiles:ts.attachedFiles,setAttachedFiles:ts.setAttachedFiles,removeAttachedFile:ts.removeAttachedFile,uploadFile:ts.uploadFile,pastedTexts:ts.pastedTexts,expandPastedTexts:ts.expandPastedTexts,incrementPastedCount:ts.incrementPastedCount,setPastedTexts:ts.setPastedTexts,resetPastedCount:ts.resetPastedCount,handleInputFocus:K.handleInputFocus,handleInputBlur:K.handleInputBlur,pendingPermissions:cd,showCompletion:Bo,completionElapsed:Ua,onImageClick:Ho,inputRef:re,textareaRef:We,isSnapshotView:y,onClearHistory:It.clearHistory,onSendCommand:xh,canSwipeClose:hc&&f==="terminal"&&!Mn&&!Ln.searchMode&&!It.fetchingHistory,onSwipeCloseOffsetChange:vh,onSwipeClose:yh}),o.jsxs("div",{className:"guake-agent-status-bar",children:[!y&&(S==null?void 0:S.isDetached)&&o.jsx(os,{content:o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",n("terminal:empty.reattachingSessionTitle")]}),o.jsxs("div",{className:"tide-tooltip__text",children:[n("terminal:empty.reattachingSessionDesc"),o.jsx("br",{}),o.jsx("br",{}),o.jsxs("strong",{children:[n("common:labels.status"),":"]})," ",n("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:o.jsxs("span",{className:"guake-detached-badge",title:n("terminal:empty.reattachingBadge"),children:[o.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",n("terminal:empty.reattaching")]})}),(S==null?void 0:S.cwd)&&o.jsxs("span",{className:"guake-agent-cwd",title:S.cwd,children:["📁 ",S.cwd.split("/").filter(Boolean).slice(-2).join("/")||S.cwd]}),O&&O.map(({areaId:Q,areaName:ue,dir:le})=>{const Ee=z.get(le),nt=W.has(le);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${ue}: ${le}${Ee?` (${Ee.branch}${Ee.ahead?` ↑${Ee.ahead}`:""}${Ee.behind?` ↓${Ee.behind}`:""})`:""}`,onClick:()=>U.openFileExplorerForAreaFolder(Q,le),children:["📂 ",le.split("/").filter(Boolean).pop()||le,Ee&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",Ee.branch]}),Ee.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${Ee.ahead} ahead`,children:["↑",Ee.ahead]}),Ee.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${Ee.behind} behind`,children:["↓",Ee.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${nt?"fetching":""}`,title:"Git fetch",onClick:ut=>{ut.stopPropagation(),$(le)},children:nt?"⏳":"⇣"})]})]},`${Q}:${le}`)}),!y&&S&&(()=>{const Q=S.contextStats,ue=!!Q,le=Q?Q.totalTokens:S.contextUsed||0,Ee=Q?Q.contextWindow:S.contextLimit||2e5,nt=Q?Q.usedPercent:Math.round(le/Ee*100),ut=Math.max(0,Math.min(100,nt)),Nt=Math.max(0,100-ut),_t=ut>=80?"#ff4a4a":ut>=60?"#ff9e4a":ut>=40?"#ffd700":"#4aff9e",sn=(le/1e3).toFixed(1),gn=(Ee/1e3).toFixed(1);return o.jsxs("span",{className:"guake-agent-context",onClick:()=>U.setContextModalAgentId(T),title:n(ue?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[o.jsx("span",{className:"context-icon",children:"📊"}),o.jsxs("span",{className:"context-label",children:[n("terminal:agentInfo.context"),":"]}),o.jsx("span",{className:"context-bar-mini",children:o.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,ut)}%`,backgroundColor:_t}})}),o.jsxs("span",{className:"context-tokens",style:{color:_t},children:[sn,"k/",gn,"k"]}),o.jsxs("span",{className:"context-free",children:["(",n("terminal:context.percentFree",{percent:Nt}),")"]}),!ue&&o.jsx("span",{className:"context-warning",title:n("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),o.jsxs("span",{className:"guake-status-right",children:[_.length>0&&o.jsx("span",{className:"guake-status-terminals",children:_.map(Q=>{const ue=Un.has(Q.id);return o.jsx("button",{className:`guake-status-terminal-btn ${ue?"active":""} ${Q.hasUrl?"":"offline"}`,title:`${ue?"Hide":"Show"} terminal: ${Q.name}${Q.hasUrl?"":" (starting...)"}`,onClick:()=>{if(ue){const le=rt.find(Ee=>Ee.buildingId===Q.id);le&&Fn(le.id)}else Q.hasUrl||U.sendBuildingCommand(Q.id,"start"),Qn(Q.id,"terminal")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Un.has(Q.id)||xt({position:{x:le.clientX,y:le.clientY},buildingId:Q.id,type:"terminal"})},children:"💻"},Q.id)})}),M.length>0&&o.jsx("span",{className:"guake-status-terminals",children:M.map(Q=>{const ue=Un.has(Q.id);return o.jsx("button",{className:`guake-status-terminal-btn ${ue?"active":""}`,title:`${ue?"Hide":"Show"} logs: ${Q.name}`,onClick:()=>{if(ue){const le=rt.find(Ee=>Ee.buildingId===Q.id);le&&Fn(le.id)}else Qn(Q.id,"pm2-logs")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Un.has(Q.id)||xt({position:{x:le.clientX,y:le.clientY},buildingId:Q.id,type:"pm2-logs"})},children:"📜"},Q.id)})}),R.length>0&&o.jsx("span",{className:"guake-status-terminals",children:R.map(Q=>{const ue=Un.has(Q.id);return o.jsx("button",{className:`guake-status-terminal-btn ${ue?"active":""}`,title:`${ue?"Hide":"Show"} database: ${Q.name}`,onClick:()=>{if(ue){const le=rt.find(Ee=>Ee.buildingId===Q.id);le&&Fn(le.id)}else Qn(Q.id,"database")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Un.has(Q.id)||xt({position:{x:le.clientX,y:le.clientY},buildingId:Q.id,type:"database"})},children:"🗄️"},Q.id)})}),o.jsx(H5,{})]})]}),(()=>{const Q=[];return at&&(Q.push({id:"open",label:"Open",icon:"⬇",onClick:()=>Qn(at.buildingId,at.type)}),nn.length>0&&(Q.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Ss(at.buildingId,at.type,"horizontal")}),Q.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Ss(at.buildingId,at.type,"vertical")}))),o.jsx(pr,{children:o.jsx(Do,{isOpen:at!==null,position:(at==null?void 0:at.position)||{x:0,y:0},worldPosition:{x:0,z:0},actions:Q,onClose:()=>xt(null)})})})(),nn.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:Po}),o.jsx("div",{ref:bt,className:`guake-bottom-panels-container ${Oe}`,style:{height:Ze},onWheel:Q=>Q.stopPropagation(),children:nn.map((Q,ue)=>{const le=I.get(Q.buildingId);if(!le)return null;const Ee=Lt[ue]??1,nt=(()=>{var ut;if(Q.type==="terminal")return(ut=le.terminalStatus)!=null&&ut.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>Fn(Q.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(Ax,{terminalUrl:le.terminalStatus.url,visible:!0})]},Q.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name," (starting...)"]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>Fn(Q.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..."})})]},Q.id);if(Q.type==="pm2-logs"){const Nt=ht[Q.id]||"";return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",le.name]}),o.jsxs("div",{className:"guake-bottom-terminal-controls",children:[o.jsx("input",{type:"text",className:"guake-bottom-terminal-filter",value:Nt,onChange:_t=>{const sn=_t.target.value;Gt(gn=>{if(!sn.trim()){if(!(Q.id in gn))return gn;const qn={...gn};return delete qn[Q.id],qn}return{...gn,[Q.id]:sn}})},placeholder:"Filter logs","aria-label":`Filter logs for ${le.name}`,spellCheck:!1}),o.jsx("select",{className:"guake-bottom-terminal-retention",value:tn===null?"unlimited":String(tn),onChange:_t=>{const sn=_t.target.value==="unlimited"?null:Number(_t.target.value);je(sn),_O(sn)},"aria-label":`Max log retention for ${le.name}`,children:TO.map(_t=>o.jsx("option",{value:_t===null?"unlimited":String(_t),children:_t===null?"Unlimited":`${_t.toLocaleString()} lines`},_t===null?"unlimited":_t))}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>U.clearStreamingLogs(Q.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:()=>U.sendBuildingCommand(Q.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:()=>Fn(Q.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(tW,{buildingId:Q.buildingId,filterText:Nt,maxRetention:tn})]},Q.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Ee},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>Fn(Q.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(_H,{building:le})]},Q.id)})();return ue>0?o.jsxs(Ce.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${Oe}`,onMouseDown:ut=>Ls(ut,ue-1)}),nt]},Q.id):nt})})]}),rt.filter(Q=>Q.areaId!==$t&&Q.type==="terminal").map(Q=>{var le;const ue=I.get(Q.buildingId);return(le=ue==null?void 0:ue.terminalStatus)!=null&&le.url?o.jsx(Ax,{terminalUrl:ue.terminalStatus.url,visible:!1},Q.id):null})]}),ot&&!ge&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:H,title:n("common:rightPanel.dragToResize")}),!(ot&&ge)&&o.jsxs("div",{className:"guake-handle",onClick:()=>{ot&&U.toggleTerminal()},onDoubleClick:()=>{ot||U.toggleTerminal()},style:{top:ot?`min(${L}%, calc(100vh - 72px))`:"0"},children:[o.jsx("span",{className:"guake-handle-icon",children:ot?"▲":"▼"}),o.jsx("span",{className:"guake-handle-text",children:S.name})]}),qe&&o.jsx(I6,{url:qe.url,name:qe.name,onClose:()=>it(null)}),he&&o.jsx(P6,{state:he,onClose:()=>Be(null)}),ie&&o.jsx(B6,{action:ie,selectedAgentId:T,subordinateCount:((mc=S==null?void 0:S.subordinateIds)==null?void 0:mc.length)||0,onClose:()=>de(null),onClearHistory:It.clearHistory}),o.jsx(F6,{}),o.jsx(z6,{}),o.jsx(U6,{agent:S,isOpen:ct,onClose:()=>fe(!1)}),!y&&o.jsx($6,{agent:S,content:He,onClose:()=>et(null)})]})});function sW(t){return t.trim().replace(/^v/i,"")}function YA(t){const n=sW(t).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!n)return null;const s=n[1].split(".").map(r=>Number.parseInt(r,10));if(s.some(Number.isNaN))return null;const a=n[2]?n[2].split("."):[];return{core:s,prerelease:a}}function aW(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;const n=Math.max(t.length,e.length);for(let s=0;s<n;s+=1){const a=t[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 rW(t,e){const n=YA(t),s=YA(e);if(!n||!s)return null;const a=Math.max(n.core.length,s.core.length);for(let r=0;r<a;r+=1){const i=n.core[r]??0,c=s.core[r]??0;if(i>c)return 1;if(i<c)return-1}return aW(n.prerelease,s.prerelease)}function iW(t,e){const n=rW(t,e);return n===null?"unknown":n<0?"behind":n>0?"ahead":"equal"}async function oW(t,e={}){const{timeoutMs:n=5e3,fetchImpl:s=fetch}=e;try{const a=new AbortController,r=setTimeout(()=>a.abort(),n),i=Date.now(),c=await s(`https://registry.npmjs.org/${encodeURIComponent(t)}/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 lW(t,e,n={}){const s=await oW(t,n);return s?{currentVersion:e,latestVersion:s,relation:iW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const cW="tide-commander",Mb="1.38.0";function uW(){const[t,e]=x.useState({currentVersion:Mb,latestVersion:null,relation:"unknown",isChecking:!1}),n=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await lW(cW,Mb);e({currentVersion:Mb,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return x.useEffect(()=>{n()},[n]),{...t,refresh:n}}const dW=x.memo(function({agent:e,currentIndex:n,agentIndex:s,isTouchInput:a,isTouchDragEnabled:r,isSelected:i,hasUnseenOutput:c,isDragging:d,isDragOver:f,customClasses:h,onDragStart:m,onDragEnd:b,onDragOver:y,onDragEnter:w,onDragLeave:C,onDrop:N,onAgentClick:k,onAgentDoubleClick:j,onTouchStart:S,onTouchMove:T,onTouchEnd:D,onTouchCancel:E,onHoverEnter:I,onHoverLeave:O,onItemRef:_}){const M=x.useMemo(()=>fr(e.class,h),[e.class,h]),R=!a||r,z=x.useCallback($=>{_(e.id,$)},[e.id,_]);return o.jsxs("div",{ref:z,className:`agent-bar-item ${i?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${d?"dragging":""} ${f?"drag-over":""} ${r?"touch-drag-enabled":""}`,draggable:R,onDragStart:$=>m($,e),onDragEnd:b,onDragOver:$=>y($,s),onDragEnter:$=>w($,s),onDragLeave:C,onDrop:$=>N($,s),onTouchStart:$=>S($,e.id),onTouchMove:T,onTouchEnd:D,onTouchCancel:E,onClick:$=>k(e,$),onDoubleClick:()=>j(e),onMouseEnter:()=>I(e),onMouseLeave:O,title:a?`${e.name} (${n+1}) - Long press to reorder`:`${e.name} (${n+1}) - Drag to reorder within group`,children:[o.jsxs("div",{className:"agent-bar-avatar",children:[o.jsx("span",{className:"agent-bar-icon",children:M.icon}),o.jsx("span",{className:"agent-bar-status",style:{backgroundColor:_x(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:Tx(e.lastActivity)},title:Ex(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${n+1}`,children:["^",n+1]})]})}),fW=x.memo(function({onFocusAgent:e,onSpawnClick:n,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=dt(["common"]),c=ed(),d=ur(),f=$x(),h=HO(),m=Ux(),b=Vr(),y=dr(),w=l1(),[C]=Bj(),[N,k]=x.useState(!1);Mj("AgentBar");const j=x.useRef(null),S=x.useRef(null),T=x.useRef(null),D=x.useRef(new Map);x.useEffect(()=>{{k(!1);return}},[b.experimental2DView]),x.useEffect(()=>{const we=S.current;if(!we)return;const Fe=Ke=>{we.scrollWidth<=we.clientWidth||(Ke.preventDefault(),Math.abs(Ke.deltaX)>Math.abs(Ke.deltaY)?we.scrollLeft+=Ke.deltaX:we.scrollLeft+=Ke.deltaY)};return we.addEventListener("wheel",Fe,{passive:!1}),()=>we.removeEventListener("wheel",Fe)},[]);const[E,I]=x.useState(null),[O,_]=x.useState(new Map),[M,R]=x.useState(null),[z,$]=x.useState(null),W=x.useRef(0),[L,F]=x.useState(null),H=x.useRef(null),V=x.useRef(null),G=x.useRef(null),B=x.useRef(null),K=350,ne=8,q=x.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),xe=x.useMemo(()=>Array.from(c.values()).filter(we=>{if(U.isAgentInArchivedArea(we.id))return!1;if(C){const Fe=U.getAreaForAgent(we.id);if(!Fx((Fe==null?void 0:Fe.id)??null))return!1}return!0}).sort((we,Fe)=>(we.createdAt||0)-(Fe.createdAt||0)),[c,d,C]),{orderedAgents:Ae,moveAgent:Z}=hO(xe),ce=Ae,me=x.useMemo(()=>{const we=new Map;for(const Fe of ce)we.set(Fe.id,U.getAreaForAgent(Fe.id));return we},[ce,d]),ee=x.useMemo(()=>{const we=new Map;for(const Ke of ce){const st=me.get(Ke.id)||null,ft=(st==null?void 0:st.id)||null;we.has(ft)||we.set(ft,{area:st,agents:[]}),we.get(ft).agents.push(Ke)}const Fe=Array.from(we.values());return Fe.sort((Ke,st)=>{var ft,wt;return!Ke.area&&st.area?1:Ke.area&&!st.area?-1:!Ke.area&&!st.area?0:(((ft=Ke.area)==null?void 0:ft.name)||"").localeCompare(((wt=st.area)==null?void 0:wt.name)||"")}),Fe},[ce,me]),re=x.useRef(e);re.current=e;const We=x.useRef(M);We.current=M;const ze=x.useRef(ce);ze.current=ce;const Pe=x.useRef(me);Pe.current=me;const ge=x.useRef(Z);ge.current=Z,x.useEffect(()=>{const we=new Map(O);let Fe=!1;for(const Ke of ce){const st=O.get(Ke.id);Ke.currentTool?(!st||st.tool!==Ke.currentTool)&&(we.set(Ke.id,{tool:Ke.currentTool,key:Date.now()}),Fe=!0):st&&setTimeout(()=>{_(ft=>{const wt=new Map(ft);return wt.delete(Ke.id),wt})},1500)}Fe&&_(we)},[ce.map(we=>we.currentTool).join(",")]),x.useEffect(()=>{const we=h;if(!we)return;const Fe=D.current.get(we),Ke=S.current;Fe&&Ke&&requestAnimationFrame(()=>{const st=Fe.getBoundingClientRect(),ft=Ke.getBoundingClientRect(),rt=st.left-ft.left+Ke.scrollLeft+st.width/2,gt=Ke.clientWidth;Ke.scrollTo({left:rt-gt/2,behavior:"smooth"})})},[h]);const Te=x.useCallback((we,Fe)=>{if(G.current===we.id){G.current=null,Fe.preventDefault(),Fe.stopPropagation();return}U.setLastSelectionViaDirectClick(!0),Fe.shiftKey?U.addToSelection(we.id):U.selectAgent(we.id),U.setTerminalOpen(!0)},[]),qe=x.useCallback(we=>{var Fe;(Fe=re.current)==null||Fe.call(re,we.id),U.setTerminalOpen(!0)},[]),it=x.useCallback(()=>I(null),[]),he=x.useCallback((we,Fe)=>{Fe?D.current.set(we,Fe):D.current.delete(we)},[]),Be=x.useCallback((we,Fe)=>{R(Fe),F(Fe.id),we.dataTransfer.effectAllowed="move",we.dataTransfer.setData("text/plain",Fe.id),requestAnimationFrame(()=>{we.target.classList.add("dragging")})},[]),ie=x.useCallback(we=>{R(null),$(null),F(null),W.current=0,we.target.classList.remove("dragging")},[]),de=x.useCallback((we,Fe)=>{we.preventDefault();const Ke=We.current;if(Ke){const st=Pe.current.get(Ke.id),ft=ze.current[Fe],wt=ft?Pe.current.get(ft.id):null,rt=(st==null?void 0:st.id)??null,gt=(wt==null?void 0:wt.id)??null;we.dataTransfer.dropEffect=rt===gt?"move":"none"}else we.dataTransfer.dropEffect="move"},[]),He=x.useCallback((we,Fe)=>{we.preventDefault(),W.current++;const Ke=We.current;if(Ke){const st=Pe.current.get(Ke.id),ft=ze.current[Fe],wt=ft?Pe.current.get(ft.id):null,rt=(st==null?void 0:st.id)??null,gt=(wt==null?void 0:wt.id)??null;$(rt===gt?Fe:null)}else $(Fe)},[]),et=x.useCallback(we=>{W.current--,W.current===0&&$(null)},[]),ct=x.useCallback((we,Fe)=>{we.preventDefault();const Ke=We.current;if(!Ke)return;const st=ze.current,ft=Pe.current,wt=st.findIndex(rt=>rt.id===Ke.id);if(wt!==-1&&wt!==Fe){const rt=ft.get(Ke.id),gt=st[Fe],ht=gt?ft.get(gt.id):null,Gt=(rt==null?void 0:rt.id)??null,tn=(ht==null?void 0:ht.id)??null;Gt===tn&&ge.current(wt,Fe)}R(null),$(null),F(null),W.current=0},[]),fe=x.useCallback(()=>{H.current&&(clearTimeout(H.current),H.current=null)},[]),X=x.useCallback(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),se=x.useCallback((we,Fe)=>{if(!q||we.touches.length!==1)return;fe(),X(),F(null);const Ke=we.touches[0];V.current={agentId:Fe,x:Ke.clientX,y:Ke.clientY},H.current=setTimeout(()=>{F(Fe),G.current=Fe,H.current=null},K)},[fe,X,q]),Se=x.useCallback(we=>{if(!q||we.touches.length!==1)return;const Fe=V.current;if(!Fe||!H.current)return;const Ke=we.touches[0],st=Ke.clientX-Fe.x,ft=Ke.clientY-Fe.y;Math.sqrt(st*st+ft*ft)>ne&&(fe(),V.current=null)},[fe,q]),J=x.useCallback(()=>{fe(),V.current=null,We.current||F(null),X(),B.current=setTimeout(()=>{G.current=null,B.current=null},450)},[fe,X]);x.useEffect(()=>()=>{fe(),X()},[fe,X]);const pe=we=>{const Fe=`common:status.${we}`;return i(Fe,{defaultValue:i("common:status.unknown")})},{currentVersion:Re,latestVersion:$e,relation:ye,isChecking:Ie}=uW(),te=Re;let be=0;return o.jsxs("div",{className:"agent-bar",ref:j,children:[o.jsxs("div",{className:"agent-bar-scroll",ref:S,children:[o.jsxs("div",{className:"agent-bar-version",title:$e?`Tide Commander v${te} (npm: v${$e})`:`Tide Commander v${te}`,children:[o.jsxs("span",{children:["v",te]}),ye==="behind"&&$e?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${$e}`,children:["npm v",$e]}):ye==="ahead"&&$e?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${$e}`,children:["npm v",$e]}):null,ye==="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)"})}):ye==="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)"})}):ye==="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")}):Ie?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(os,{content:"Refresh 3D Scene (HMR changes pending)",position:"bottom",children:o.jsx("button",{className:"agent-bar-hmr-refresh",onClick:Uj,children:"↻"})})]}),o.jsxs("div",{className:"agent-bar-list",ref:T,children:[o.jsx(os,{content:i("common:agentBar.spawnNewAgent"),position:"bottom",children:o.jsxs("button",{className:"agent-bar-spawn-btn",onClick:n,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(os,{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(os,{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(os,{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")})]})}),ee.map(we=>{var st,ft,wt,rt,gt;const Fe=we.agents,Ke=!we.area;return o.jsxs("div",{className:`agent-bar-group ${Ke?"unassigned":""}`,style:{borderColor:((st=we.area)==null?void 0:st.color)||void 0,background:we.area?`${we.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:((ft=we.area)==null?void 0:ft.color)||"#888"},children:((wt=we.area)==null?void 0:wt.name)||i("common:agentBar.unassigned")})}),((rt=we.area)==null?void 0:rt.directories)&&we.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:we.area.directories.map((ht,Gt)=>o.jsxs("div",{className:"agent-bar-folder-item",onClick:tn=>{tn.stopPropagation(),U.openFileExplorer(ht)},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:ht}),o.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},Gt))}),Fe.map(ht=>{const Gt=be++,tn=ce.findIndex(je=>je.id===ht.id);return o.jsx(dW,{agent:ht,currentIndex:Gt,agentIndex:tn,isTouchInput:q,isTouchDragEnabled:L===ht.id,isSelected:f.has(ht.id),hasUnseenOutput:w.has(ht.id),isDragging:(M==null?void 0:M.id)===ht.id,isDragOver:z===tn,customClasses:y,onDragStart:Be,onDragEnd:ie,onDragOver:de,onDragEnter:He,onDragLeave:et,onDrop:ct,onAgentClick:Te,onAgentDoubleClick:qe,onTouchStart:se,onTouchMove:Se,onTouchEnd:J,onTouchCancel:J,onHoverEnter:I,onHoverLeave:it,onItemRef:he},ht.id)})]},((gt=we.area)==null?void 0:gt.id)||"unassigned")})]})]}),Array.from(O.entries()).map(([we,Fe])=>{const Ke=D.current.get(we);if(!Ke)return null;const st=Ke.getBoundingClientRect(),ft=fs[Fe.tool]||fs.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:Fe.tool,style:{position:"fixed",left:st.left+st.width/2,bottom:window.innerHeight-st.top+8},children:[o.jsx("span",{className:"agent-bar-tool-icon",children:ft}),o.jsx("span",{className:"agent-bar-tool-name",children:Fe.tool})]},`tool-${we}-${Fe.key}`)}),E&&(()=>{const we=U.getAreaForAgent(E.id),Fe=m.get(E.id),Ke=fr(E.class,y),st=U.getAgentSupervisorHistory(E.id),ft=st.length>0?st[st.length-1]:void 0,wt=Date.now()-(E.createdAt||Date.now()),rt=Math.floor(wt/6e4),gt=Math.floor(rt/60),ht=gt>0?`${gt}h ${rt%60}m`:`${rt}m`,Gt=Ze=>Ze>=1e6?`${(Ze/1e6).toFixed(1)}M`:Ze>=1e3?`${(Ze/1e3).toFixed(1)}K`:Ze.toString(),tn=E.contextLimit>0?Math.round(E.contextUsed/E.contextLimit*100):0,je=Ze=>{switch(Ze){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Oe=D.current.get(E.id),Ye={};if(Oe){const Ze=Oe.getBoundingClientRect();Ye.position="fixed",Ye.left=Ze.left+Ze.width/2,Ye.bottom=window.innerHeight-Ze.top+12}return o.jsxs("div",{className:"agent-bar-tooltip",style:Ye,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:Ke.icon}),o.jsxs("span",{className:"agent-bar-tooltip-name",children:[o.jsx("img",{src:E.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:E.provider,className:"agent-bar-provider-icon",title:E.provider==="codex"?"Codex Agent":"Claude Agent"}),E.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:_x(E.status)},children:pe(E.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:[E.class," — ",Ke.description]})]}),we&&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:we.color},children:we.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:E.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:ht})]}),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:[Gt(E.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:tn>80?"#ff4a4a":tn>60?"#ff9e4a":void 0},children:[Gt(E.contextUsed)," / ",Gt(E.contextLimit)," (",tn,"%)"]})]}),E.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:[fs[E.currentTool]||fs.default," ",E.currentTool]})]}),E.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:E.taskLabel})]}),E.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:[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:[i("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?"...":""]})]}),Fe&&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:[Fe.text.substring(0,300),Fe.text.length>300?"...":""]})]}),ft&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"agent-bar-tooltip-divider"}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.supervisor"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",style:{color:je(ft.analysis.progress)},children:ft.analysis.progress.replace("_"," ")})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.status"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:ft.analysis.statusDescription})]}),ft.analysis.recentWorkSummary&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.summary"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[ft.analysis.recentWorkSummary.substring(0,300),ft.analysis.recentWorkSummary.length>300?"...":""]})]}),ft.analysis.concerns&&ft.analysis.concerns.length>0&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.concerns"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:ft.analysis.concerns.join("; ")})]})]})]})]})})()]})});function pW({activeTool:t,onExit:e}){const{t:n}=dt(["notifications","terminal"]);if(!t||t==="select")return null;const s=n(t==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=t==="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:[n("terminal:drawingMode.drawingArea"),": ",s]}),o.jsxs("span",{className:"drawing-mode-hint",children:[n("terminal:drawingMode.clickAndDrag")," • ",n("terminal:drawingMode.pressEscape")]})]})]}),o.jsx("button",{className:"drawing-mode-exit",onClick:e,title:n("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const hW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Db=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),mW=t=>{switch(t){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},gW=x.memo(function({agent:e,screenPos:n,onClose:s}){const{t:a}=dt(["common"]),r=dr(),i=U.getAreaForAgent(e.id),c=U.getState().lastPrompts.get(e.id),d=fr(e.class,r),f=U.getAgentSupervisorHistory(e.id),h=f.length>0?f[f.length-1]:void 0,m=Date.now()-(e.createdAt||Date.now()),b=Math.floor(m/6e4),y=Math.floor(b/60),w=y>0?`${y}h ${b%60}m`:`${b}m`,C=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,N=x.useMemo(()=>{let S=n.x-150,T=n.y-320-10;return typeof window<"u"&&(S<10?S=10:S+300>window.innerWidth-10&&(S=window.innerWidth-300-10),T<10&&(T=n.y+10)),{position:"fixed",left:S,top:T,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[n.x,n.y]);return o.jsxs("div",{className:"agent-hover-popup",style:N,onMouseLeave:s,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:d.icon}),o.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:_x(e.status)},children:a(hW[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:w})]}),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:[Db(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:C>80?"#ff4a4a":C>60?"#ff9e4a":void 0},children:[Db(e.contextUsed)," / ",Db(e.contextLimit)," (",C,"%)"]})]}),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:[fs[e.currentTool]||fs.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?"...":""]})]}),h&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"agent-bar-tooltip-divider"}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.supervisor"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value",style:{color:mW(h.analysis.progress)},children:h.analysis.progress.replace("_"," ")})]}),o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.status"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:h.analysis.statusDescription})]}),h.analysis.recentWorkSummary&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.summary"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[h.analysis.recentWorkSummary.substring(0,300),h.analysis.recentWorkSummary.length>300?"...":""]})]}),h.analysis.concerns&&h.analysis.concerns.length>0&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.concerns"),":"]}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:h.analysis.concerns.join("; ")})]})]})]})]})});function GA(t){if(t===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,s)).toFixed(1))+" "+n[s]}function KA(t){const n=Date.now()-t,s=Math.floor(n/(1e3*60*60)),a=Math.floor(n%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const QA={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 bW(t){const e=[],n=/\x1B\[([0-9;]*)m/g;let s=0,a=null,r;for(;(r=n.exec(t))!==null;){if(r.index>s){const c=t.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:QA[c]&&(a=QA[c]);s=n.lastIndex}if(s<t.length){const i=t.slice(s);a?e.push(o.jsx("span",{style:{color:a},children:i},e.length)):e.push(i)}return e.length>0?e:[t]}const xW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var F,H,V,G,B,K,ne,q,xe,Ae,Z,ce,me,ee,re,We,ze,Pe,ge,Te;const{t:c}=dt(["terminal","common"]),[d,f]=x.useState(!1),[h,m]=x.useState(null),[b,y]=x.useState(!1),w=x.useRef(null),C=x.useRef(h);C.current=h;const{buildingLogs:N}=Rs(),k=U.getBuildingLogs(e.id),j=(F=e.pm2)==null?void 0:F.enabled,S=(H=e.docker)==null?void 0:H.enabled,T=x.useRef(null),D=x.useRef(null),E=x.useCallback(qe=>{qe.preventDefault();const it=C.current?C.current.x:0,he=C.current?C.current.y:0;w.current={mouseX:qe.clientX,mouseY:qe.clientY,popupX:it,popupY:he},y(!0),T.current=Be=>{if(!w.current)return;const ie=Be.clientX-w.current.mouseX,de=Be.clientY-w.current.mouseY;m({x:w.current.popupX+ie,y:w.current.popupY+de})},D.current=()=>{y(!1),w.current=null,T.current&&document.removeEventListener("mousemove",T.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",T.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{T.current&&document.removeEventListener("mousemove",T.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const I=qe=>{if(qe==="logs"){if((j||S)&&r){r();return}U.sendBuildingCommand(e.id,qe),f(!0)}else U.sendBuildingCommand(e.id,qe)},O=(qe,it)=>{if(qe){const he=`http://localhost:${qe}`;it&&i?i(he):window.open(he,"_blank")}},_=((V=e.pm2Status)==null?void 0:V.ports)||[],M=((B=(G=e.dockerStatus)==null?void 0:G.ports)==null?void 0:B.map(qe=>qe.host))||[],R=j?_:S?M:[],z=j?!!((K=e.pm2)!=null&&K.script):S?!!((ne=e.docker)!=null&&ne.image)||((q=e.docker)==null?void 0:q.mode)==="compose"||((xe=e.docker)==null?void 0:xe.mode)==="existing":!!((Ae=e.commands)!=null&&Ae.start),$=j?!!((Z=e.pm2)!=null&&Z.script):S?!0:!!((ce=e.commands)!=null&&ce.stop),W=j?!!((me=e.pm2)!=null&&me.script):S?!0:!!((ee=e.commands)!=null&&ee.restart),L=x.useMemo(()=>{const it=d?400:250;let he=n.x+20,Be=n.y-80;return typeof window<"u"&&!h&&(n.x+20+280>window.innerWidth&&(he=n.x-280-20),n.y-80<0?Be=10:n.y-80+it>window.innerHeight&&(Be=window.innerHeight-it-10)),{position:"fixed",left:he+((h==null?void 0:h.x)||0),top:Be+((h==null?void 0:h.y)||0),zIndex:1e3,cursor:b?"grabbing":void 0}},[n.x,n.y,d,h,b]);return o.jsxs("div",{className:"building-action-popup",style:L,onClick:qe=>qe.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header ${b?"dragging":""}`,onMouseDown:E,children:[o.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&o.jsx("span",{className:"building-popup-ports",children:R.map(qe=>o.jsxs("a",{href:`http://localhost:${qe}`,className:"building-popup-port-link",onClick:it=>{it.preventDefault(),it.stopPropagation(),O(qe,it.altKey)},onMouseDown:it=>it.stopPropagation(),title:`Open http://localhost:${qe} (Alt+Click for modal)`,children:[":",qe]},qe))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:qb[e.status]},children:e.status}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),j&&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:[((re=e.pm2Status.cpu)==null?void 0:re.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:GA(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:KA(e.pm2Status.uptime)})]})]}),S&&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:GA(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:KA(e.dockerStatus.startedAt)})]})]}),S&&((We=e.dockerStatus)==null?void 0:We.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((qe,it)=>o.jsxs("span",{className:"service-item",title:`${qe.name}: ${qe.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:qe.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:qe.name})]},it))}),(e.lastError||j&&((ze=e.pm2Status)==null?void 0:ze.status)==="errored"||S&&((Pe=e.dockerStatus)==null?void 0:Pe.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),j&&((ge=e.pm2Status)==null?void 0:ge.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),S&&((Te=e.dockerStatus)==null?void 0:Te.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:()=>I("start"),disabled:!z||e.status==="running"||e.status==="starting",title:c(z?"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:()=>I("stop"),disabled:!$||e.status==="stopped"||e.status==="stopping",title:c($?"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:()=>I("restart"),disabled:!W,title:c(W?"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:()=>I("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:qe=>O(R[0],qe.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(qe=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:it=>O(qe,it.altKey),title:`Open http://localhost:${qe} (Alt+Click for modal)`,children:[":",qe]},qe))]})]}),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:()=>U.clearBuildingLogs(e.id),children:c("terminal:logs.clear")})]}),o.jsx("div",{className:"logs-content",children:k.slice(-50).map((qe,it)=>o.jsx("pre",{children:bW(qe)},it))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function yW(t){if(t===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,s)).toFixed(1))+" "+n[s]}function vW(t){const n=Date.now()-t,s=Math.floor(n/(1e3*60*60)),a=Math.floor(n%(1e3*60*60)/(1e3*60));return s>0?`${s}h ${a}m`:`${a}m`}const wW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){const{t:c}=dt(["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:w}=Rs(),N=(e.subordinateBuildingIds||[]).map(_=>w.get(_)).filter(_=>_!==void 0),k=x.useRef(null),j=x.useRef(null),S=x.useCallback(_=>{_.preventDefault();const M=y.current?y.current.x:0,R=y.current?y.current.y:0;b.current={mouseX:_.clientX,mouseY:_.clientY,popupX:M,popupY:R},m(!0),k.current=z=>{if(!b.current)return;const $=z.clientX-b.current.mouseX,W=z.clientY-b.current.mouseY;f({x:b.current.popupX+$,y:b.current.popupY+W})},j.current=()=>{m(!1),b.current=null,k.current&&document.removeEventListener("mousemove",k.current),j.current&&document.removeEventListener("mouseup",j.current)},document.addEventListener("mousemove",k.current),document.addEventListener("mouseup",j.current)},[]);x.useEffect(()=>()=>{k.current&&document.removeEventListener("mousemove",k.current),j.current&&document.removeEventListener("mouseup",j.current)},[]);const T=_=>{U.sendBossBuildingCommand(e.id,_)},D=N.reduce((_,M)=>(_[M.status]=(_[M.status]||0)+1,_),{}),E=N.some(_=>{var M;return(M=_.pm2)==null?void 0:M.enabled}),I=(_,M)=>{const R=`http://localhost:${_}`;M&&i?i(R):window.open(R,"_blank")},O=x.useMemo(()=>{let R=n.x+20,z=n.y-80;return typeof window<"u"&&!d&&(n.x+20+340>window.innerWidth&&(R=n.x-340-20),n.y-80<0?z=10:n.y-80+350>window.innerHeight&&(z=window.innerHeight-350-10)),{position:"fixed",left:R+((d==null?void 0:d.x)||0),top:z+((d==null?void 0:d.y)||0),zIndex:1e3,cursor:h?"grabbing":void 0}},[n.x,n.y,d,h]);return o.jsxs("div",{className:"building-action-popup boss-building-popup",style:O,onClick:_=>_.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header boss-header ${h?"dragging":""}`,onMouseDown:S,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(([_,M])=>o.jsxs("span",{className:"status-badge",style:{backgroundColor:qb[_]||"#666"},children:[M," ",_]},_)),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(_=>{var M,R,z;return o.jsxs("div",{className:"subordinate-item",children:[o.jsx("span",{className:"sub-status-dot",style:{backgroundColor:qb[_.status]}}),o.jsx("span",{className:"sub-name",children:_.name}),((M=_.pm2Status)==null?void 0:M.ports)&&_.pm2Status.ports.length>0&&o.jsx("span",{className:"sub-port",children:_.pm2Status.ports.map($=>o.jsxs("a",{href:`http://localhost:${$}`,className:"building-popup-port-link",onClick:W=>{W.preventDefault(),W.stopPropagation(),I($,W.altKey)},title:`Open http://localhost:${$} (Alt+Click for modal)`,children:[":",$]},$))}),_.pm2Status&&o.jsxs("span",{className:"sub-metrics",children:[(R=_.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",yW(_.pm2Status.memory||0)]}),((z=_.pm2Status)==null?void 0:z.uptime)&&o.jsx("span",{className:"sub-uptime",children:vW(_.pm2Status.uptime)})]},_.id)})}),o.jsxs("div",{className:"building-popup-actions boss-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>T("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:()=>T("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:()=>T("restart_all"),disabled:N.length===0,title:c("terminal:building.restartAllSubs"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:building.restartAll")]}),E&&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")})]})}),kW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenDatabasePanel:r}){var D;const{t:i}=dt(["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=Yx(e.id),w=((D=e.database)==null?void 0:D.connections)??[],C=x.useRef(null),N=x.useRef(null),k=x.useCallback(E=>{E.preventDefault();const I=b.current?b.current.x:0,O=b.current?b.current.y:0;m.current={mouseX:E.clientX,mouseY:E.clientY,popupX:I,popupY:O},h(!0),C.current=_=>{if(!m.current)return;const M=_.clientX-m.current.mouseX,R=_.clientY-m.current.mouseY;d({x:m.current.popupX+M,y:m.current.popupY+R})},N.current=()=>{h(!1),m.current=null,C.current&&document.removeEventListener("mousemove",C.current),N.current&&document.removeEventListener("mouseup",N.current)},document.addEventListener("mousemove",C.current),document.addEventListener("mouseup",N.current)},[]);x.useEffect(()=>()=>{C.current&&document.removeEventListener("mousemove",C.current),N.current&&document.removeEventListener("mouseup",N.current)},[]);const j=E=>{U.testDatabaseConnection(e.id,E)},S=E=>y.connectionStatus.get(E),T=x.useMemo(()=>{let O=n.x+20,_=n.y-80;return typeof window<"u"&&!c&&(n.x+20+320>window.innerWidth&&(O=n.x-320-20),n.y-80<0?_=10:n.y-80+300>window.innerHeight&&(_=window.innerHeight-300-10)),{position:"fixed",left:O+((c==null?void 0:c.x)||0),top:_+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[n.x,n.y,c,f]);return o.jsxs("div",{className:"building-action-popup database-building-popup",style:T,onClick:E=>E.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:w.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),w.length>0?o.jsx("div",{className:"database-connection-list",children:w.map(E=>{var O;const I=S(E.id);return o.jsxs("div",{className:"database-connection-item",children:[o.jsx("span",{className:"conn-engine",children:((O=vL[E.engine])==null?void 0:O.icon)??"🗄️"}),o.jsx("span",{className:"conn-name",children:E.name}),o.jsx("span",{className:"conn-host",children:E.engine==="sqlite"?E.filepath||E.database||":memory:":`${E.host}:${E.port}`}),I&&o.jsx("span",{className:`conn-status ${I.connected?"connected":"disconnected"}`,children:I.connected?"●":"○"}),o.jsx("button",{className:"conn-test-btn",onClick:()=>j(E.id),title:i("terminal:building.testConnection"),children:"↻"})]},E.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:w.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:()=>w.forEach(E=>j(E.id)),disabled:w.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 SW({visible:t=!0,position:e="top-right"}){const[n,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),[w,C]=x.useState(!1),[N,k]=x.useState("fps"),[j,S]=x.useState(null),[T,D]=x.useState(null),[E,I]=x.useState(null),[O,_]=x.useState(typeof window<"u"?window.innerWidth:1024),[M,R]=x.useState(null);x.useEffect(()=>{const Z=()=>_(window.innerWidth);return window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]);const z=Kp(),$=x.useMemo(()=>{const Z=z.filter(me=>me.memoryUsageMB!==void 0&&me.memoryUsageMB>0);return{totalMB:Z.reduce((me,ee)=>me+(ee.memoryUsageMB||0),0),agentCount:Z.length,agents:Z.map(me=>({name:me.name,memoryMB:me.memoryUsageMB||0,status:me.status})).sort((me,ee)=>ee.memoryMB-me.memoryMB)}},[z]),W=x.useRef([]),L=x.useRef(null);if(x.useEffect(()=>{W.current=d},[d]),x.useEffect(()=>{L.current=h},[h]),x.useEffect(()=>{if(!t)return;const Z=async()=>{try{const me=await Bt(Rt("/api/perf"));if(me.ok){const ee=await me.json();D(ee)}}catch{}};Z();const ce=setInterval(Z,w?3e3:1e4);return()=>clearInterval(ce)},[t,w]),x.useEffect(()=>{if(!t)return;const Z=su.getUsage();Z&&M===null&&R(Z.usedMB);const ce=setInterval(()=>{var it,he;Nf.update();const me=Nf.getStats();s(me.current),r(Be=>[...Be,me.current].slice(-60));const ee=su.getUsage();ee&&c(ee);const re=window.__tideScene;if(re){const Be=(it=re.getMemoryDiagnostics)==null?void 0:it.call(re);Be!=null&&Be.threeJs&&m(Be.threeJs);const ie=re.renderer;if((he=ie==null?void 0:ie.info)!=null&&he.memory){const de=ie.info.memory.textures||0,He=Math.round(de*1);I({count:de,estimatedMB:He})}}const We=document.getElementsByTagName("*"),ze=document.getElementsByTagName("canvas"),Pe=document.getElementsByTagName("img"),ge=document.getElementsByTagName("video");let Te=0;for(let Be=0;Be<Math.min(We.length,500);Be++){const ie=We[Be];ie.onclick&&Te++,ie.onmousedown&&Te++,ie.onkeydown&&Te++}Te+=10,S({nodeCount:We.length,listenerCount:Te,canvasCount:ze.length,imageCount:Pe.length,videoCount:ge.length}),ee&&f(Be=>{const ie=L.current,de={timestamp:Date.now(),heapMB:ee.usedMB,geometries:(ie==null?void 0:ie.geometries)??0,textures:(ie==null?void 0:ie.textures)??0};return[...Be,de].slice(-120)});const qe=W.current;if(qe.length>=10){const Be=qe[0],ie=qe[qe.length-1],de=(ie.timestamp-Be.timestamp)/1e3/60;de>.1&&y((ie.heapMB-Be.heapMB)/de)}},1e3);return()=>{clearInterval(ce)}},[t,M]),!t)return null;const F=Z=>{const ce=Math.floor(Z/3600),me=Math.floor(Z%3600/60),ee=Z%60;return ce>0?`${ce}h ${me}m`:me>0?`${me}m ${ee}s`:`${ee}s`},H=Z=>Z>=55?"#4aff9e":Z>=30?"#ffcc00":"#ff4a4a",V=(Z,ce)=>{const me=Z/ce;return me<.5?"#4aff9e":me<.8?"#ffcc00":"#ff4a4a"},G=Z=>Z===null?"#888":Z<1?"#4aff9e":Z<5?"#ffcc00":"#ff4a4a",B=Nf.getStats(),ne=O<=768?80:10,q={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:ne,left:10},"bottom-right":{bottom:ne,right:10}},xe=M&&i?i.usedMB-M:0,Ae=Z=>({padding:"2px 8px",fontSize:"9px",border:"none",background:N===Z?"rgba(74, 158, 255, 0.4)":"rgba(255, 255, 255, 0.1)",color:N===Z?"#4a9eff":"#888",borderRadius:"3px",cursor:"pointer"});return o.jsxs("div",{style:{position:"fixed",...q[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:w?"260px":"120px",maxWidth:"calc(100vw - 20px)",maxHeight:w?"calc(100vh - 100px)":"auto",overflowY:w?"auto":"visible",transition:"all 0.2s ease"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:()=>C(!w),children:[o.jsx("span",{style:{color:H(n),fontWeight:"bold",fontSize:"14px"},children:n}),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:V(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:G(b),fontSize:"10px",marginLeft:"4px"},children:[b>0?"+":"",b.toFixed(1),"/m"]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:"#ff9e4a",fontWeight:"bold"},children:T.process.rssMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"SRV"})]}),o.jsx("span",{style:{color:"#444",marginLeft:"auto",fontSize:"10px"},children:w?"▼":"▶"})]}),w&&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:Ae("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:Ae("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:Ae("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:Ae("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:Ae("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:Ae("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:H(B.current)},children:B.current}),o.jsx("span",{style:{color:"#888"},children:"Min:"}),o.jsx("span",{style:{color:H(B.min)},children:B.min}),o.jsx("span",{style:{color:"#888"},children:"Max:"}),o.jsx("span",{style:{color:H(B.max)},children:B.max}),o.jsx("span",{style:{color:"#888"},children:"Avg:"}),o.jsx("span",{style:{color:H(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((Z,ce)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,Z/60*100)}%`,background:H(Z),opacity:.8}},ce))})]})]}),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:V(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:xe>50?"#ff4a4a":xe>20?"#ffcc00":"#4aff9e"},children:[xe>0?"+":"",xe," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Rate:"}),o.jsx("span",{style:{color:G(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:V(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((Z,ce)=>{const me=Math.min(...d.map(ze=>ze.heapMB)),re=Math.max(...d.map(ze=>ze.heapMB))-me||1,We=(Z.heapMB-me)/re*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,We)}%`,background:Z.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${Z.heapMB}MB`},ce)})})]}),$.agentCount>0&&o.jsxs("div",{style:{marginTop:"8px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:["Agent Memory (",$.agentCount,"):"]}),o.jsxs("div",{style:{fontSize:"10px"},children:[o.jsxs("div",{style:{color:"#4aff9e",fontWeight:"bold",marginBottom:"2px"},children:["Total: ",$.totalMB,"MB"]}),o.jsx("div",{style:{maxHeight:"50px",overflowY:"auto"},children:$.agents.slice(0,4).map((Z,ce)=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:Z.status==="working"?"#4aff9e":"#666",maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis"},children:Z.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[Z.memoryMB,"MB"]})]},ce))})]})]}),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:["~",(E==null?void 0:E.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsxs("span",{style:{color:"#9e4aff"},children:["DOM (",(j==null?void 0:j.nodeCount.toLocaleString())??0," nodes)"]}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(((j==null?void 0:j.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+((E==null?void 0:E.estimatedMB)??0)+Math.round(((j==null?void 0:j.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((Z,ce)=>{const me=Math.max(...d.map(ee=>ee.textures))||1;return o.jsx("div",{style:{width:"3px",height:`${Z.textures/me*100}%`,background:"#ff9e4a",opacity:.8},title:`${Z.textures} textures`},ce)})})]}),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:j?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:j.nodeCount>5e3?"#ff4a4a":j.nodeCount>2e3?"#ffcc00":"#4aff9e"},children:j.nodeCount.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Canvases:"}),o.jsx("span",{style:{color:"#4a9eff"},children:j.canvasCount}),o.jsx("span",{style:{color:"#888"},children:"Images:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:j.imageCount}),o.jsx("span",{style:{color:"#888"},children:"Videos:"}),o.jsx("span",{style:{color:"#9e4aff"},children:j.videoCount})]}),E&&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:E.count}),o.jsx("span",{style:{color:"#888"},children:"Est. VRAM:"}),o.jsxs("span",{style:{color:E.estimatedMB>100?"#ff4a4a":"#4aff9e"},children:["~",E.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:["~",(E==null?void 0:E.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(j.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)+((E==null?void 0:E.estimatedMB)??0)+Math.round(j.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:T?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:F(T.uptime)}),o.jsx("span",{style:{color:"#888"},children:"Heap Used:"}),o.jsxs("span",{style:{color:T.process.heapUsedMB>500?"#ff4a4a":"#4aff9e"},children:[T.process.heapUsedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Heap Total:"}),o.jsxs("span",{children:[T.process.heapTotalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"RSS:"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[T.process.rssMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"External:"}),o.jsxs("span",{children:[T.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:T.system.loadAvg[0]>T.system.cpuCount?"#ff4a4a":"#4aff9e"},children:T.system.loadAvg.join(" ")}),o.jsx("span",{style:{color:"#888"},children:"CPUs:"}),o.jsx("span",{children:T.system.cpuCount}),o.jsx("span",{style:{color:"#888"},children:"Sys Memory:"}),o.jsxs("span",{children:[T.system.totalMemMB-T.system.freeMemMB," / ",T.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:T.websocket.clients}),o.jsx("span",{style:{color:"#888"},children:"Sent:"}),o.jsx("span",{children:T.websocket.messagesSent.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Received:"}),o.jsx("span",{children:T.websocket.messagesReceived.toLocaleString()})]})]}),T.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 (",T.agents.working,"w / ",T.agents.idle,"i / ",T.agents.total,"t):"]}),o.jsx("div",{style:{maxHeight:"80px",overflowY:"auto",fontSize:"10px"},children:T.agents.processes.map(Z=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:Z.status==="working"?"#4aff9e":Z.status==="idle"?"#888":"#ff4a4a",maxWidth:"100px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[Z.memoryMB!=null?`${Z.memoryMB}MB`:"—",Z.pid?` (${Z.pid})`:""]})]},Z.id))})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading server metrics..."})}),N==="http"&&o.jsx("div",{children:T?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:T.http.reqPerSec}),o.jsx("span",{style:{color:"#888"},children:"Avg Latency:"}),o.jsxs("span",{style:{color:T.http.avgLatencyMs>100?"#ff4a4a":T.http.avgLatencyMs>50?"#ffcc00":"#4aff9e"},children:[T.http.avgLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Max Latency:"}),o.jsxs("span",{style:{color:T.http.maxLatencyMs>500?"#ff4a4a":T.http.maxLatencyMs>200?"#ffcc00":"#4aff9e"},children:[T.http.maxLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Recent Reqs:"}),o.jsx("span",{children:T.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,T.http.avgLatencyMs/500*100)}%`,background:T.http.avgLatencyMs>100?"#ff4a4a":T.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:[T.process.cpuUser," ms"]}),o.jsx("span",{style:{color:"#888"},children:"CPU (system):"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:[T.process.cpuSystem," ms"]}),o.jsx("span",{style:{color:"#888"},children:"WS Clients:"}),o.jsx("span",{style:{color:"#4aff9e"},children:T.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:Z=>{Z.stopPropagation();const ce=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&ce.push("","--- Memory ---",`Heap Used: ${i.usedMB} MB`,`Heap Total: ${i.totalMB} MB`,`Heap Limit: ${i.limitMB} MB`,`Baseline: ${M??"N/A"} MB`,`Growth: ${xe>0?"+":""}${xe} MB`,`Growth Rate: ${b!==null?`${b.toFixed(2)} MB/min`:"N/A"}`),h&&ce.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),$.agentCount>0&&(ce.push("","--- Agent Memory ---",`Total: ${$.totalMB} MB`,`Agents: ${$.agentCount}`),$.agents.slice(0,5).forEach(ee=>{ce.push(` ${ee.name}: ${ee.memoryMB} MB (${ee.status})`)})),j&&ce.push("","--- DOM ---",`DOM Nodes: ${j.nodeCount.toLocaleString()}`,`Canvases: ${j.canvasCount}`,`Images: ${j.imageCount}`,`Videos: ${j.videoCount}`),E&&ce.push("","--- Estimated Memory ---",`GPU Textures: ${E.count}`,`Est. VRAM: ~${E.estimatedMB} MB`,`Est. DOM: ~${Math.round(((j==null?void 0:j.nodeCount)??0)*.5/1024)} MB`,`Est. Total: ~${((i==null?void 0:i.usedMB)??0)+E.estimatedMB+Math.round(((j==null?void 0:j.nodeCount)??0)*.5/1024)} MB`),T&&(ce.push("","--- Server ---",`Uptime: ${F(T.uptime)}`,`Heap: ${T.process.heapUsedMB}/${T.process.heapTotalMB} MB`,`RSS: ${T.process.rssMB} MB`,`Load Avg: ${T.system.loadAvg.join(" ")}`,`System Memory: ${T.system.totalMemMB-T.system.freeMemMB}/${T.system.totalMemMB} MB`,"","--- WebSocket ---",`Clients: ${T.websocket.clients}`,`Sent: ${T.websocket.messagesSent}`,`Received: ${T.websocket.messagesReceived}`,"","--- HTTP ---",`Req/sec: ${T.http.reqPerSec}`,`Avg Latency: ${T.http.avgLatencyMs} ms`,`Max Latency: ${T.http.maxLatencyMs} ms`),T.agents.processes.length>0&&(ce.push("","--- Agent Processes ---",`Total: ${T.agents.total} (${T.agents.working} working, ${T.agents.idle} idle)`),T.agents.processes.forEach(ee=>{ce.push(` ${ee.name}: ${ee.memoryMB!=null?`${ee.memoryMB}MB`:"N/A"} (${ee.status})${ee.pid?` PID:${ee.pid}`:""}`)})));const me=ce.join(`
152
+ `);navigator.clipboard.writeText(me).then(()=>{const ee=Z.currentTarget,re=ee.textContent;ee.textContent="Copied!",setTimeout(()=>{ee.textContent=re},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:Z=>{Z.stopPropagation(),su.report();const ce=window.__tideScene;ce!=null&&ce.logMemoryDiagnostics&&ce.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:Z=>{Z.stopPropagation(),Xb.clear(),Nf.reset(),su.reset(),r([]),f([]);const ce=su.getUsage();ce&&R(ce.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 CW(){const t=o1(),e=x.useCallback(n=>{U.setViewMode(n)},[]);return[t,e]}const AW=["3d","2d","dashboard"],jW=x.memo(function({className:e=""}){const{t:n}=dt(["common"]),[s,a]=CW(),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}}),AW.map(f=>o.jsxs("button",{className:`view-mode-toggle__btn ${s===f?"view-mode-toggle__btn--active":""}`,onClick:()=>d(f),title:n(`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:n(`common:viewMode.labels.${f}`)})]},f))]})});function JT({className:t}){const{t:e}=dt(["terminal"]),[n,s]=x.useState(!1),[a,r]=x.useState(null),i=My(),c=x.useCallback(async y=>{if(y.trim()){console.log("[VoiceAssistant] Transcribed:",y),s(!0),r(null);try{const C=await(await Bt(Rt("/api/voice-assistant/process"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:y})})).json();if(C.success&&C.response)console.log("[VoiceAssistant] Response:",C.response),i.speak(C.response);else{const N=C.error||e("terminal:voiceAssistant.failedToProcess");console.error("[VoiceAssistant] Error:",N),r(N),i.speak(N)}}catch(w){console.error("[VoiceAssistant] Request failed:",w);const C=e("terminal:voiceAssistant.unavailable");r(C),i.speak(C)}finally{s(!1)}}},[i]),d=UT({language:"Spanish",model:"medium",onTranscription:c}),f=d.recording||d.transcribing||n||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"):n?e("terminal:voiceAssistant.processing"):i.speaking?e("terminal:voiceAssistant.speaking"):e("terminal:voiceAssistant.title"),m=()=>{const y=["voice-assistant-btn",t].filter(Boolean);return d.recording&&y.push("recording"),(d.transcribing||n)&&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||n||d.toggleRecording()};return o.jsxs("button",{className:m(),onClick:b,title:d.supported?h():e("terminal:voiceAssistant.notSupported"),disabled:!d.supported||d.transcribing||n,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 NW=x.memo(function({isOpen:e,onToggle:n,onShowTerminal:s,onOpenSidebar:a,onOpenToolbox:r,onOpenCommander:i,onOpenSupervisor:c,onOpenControls:d,onOpenSkills:f,onOpenSnapshots:h,onTakeSnapshot:m,canTakeSnapshot:b,mobileView:y}){const{t:w}=dt(["terminal","common"]),C=Vr(),N=k=>{k(),n()};return o.jsxs(o.Fragment,{children:[C.experimentalVoiceAssistant&&o.jsx(JT,{className:"mobile-voice-assistant"}),y!=="terminal"&&o.jsx("button",{className:`mobile-fab-toggle ${e?"open":""}`,onClick:n,onTouchStart:k=>k.stopPropagation(),title:w(e?"terminal:mobileFab.closeMenu":"terminal:mobileFab.openMenu"),children:e?"✕":"☰"}),y==="3d"&&o.jsxs("div",{className:`mobile-fab-menu ${e?"open":""}`,children:[o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(s),onTouchEnd:k=>{k.preventDefault(),N(s)},title:w("terminal:mobileFab.showTerminal"),children:"💬"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(a),onTouchEnd:k=>{k.preventDefault(),N(a)},title:w("terminal:header.openSidebar"),children:"📋"}),b&&o.jsx("button",{className:"mobile-fab-option mobile-fab-option--highlight",onClick:()=>N(m),onTouchEnd:k=>{k.preventDefault(),N(m)},title:w("terminal:mobileFab.takeSnapshot"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(r),onTouchEnd:k=>{k.preventDefault(),N(r)},title:w("common:floatingButtons.settingsAndTools"),children:"⚙️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(i),onTouchEnd:k=>{k.preventDefault(),N(i)},title:w("common:floatingButtons.commanderView"),children:"📊"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(c),onTouchEnd:k=>{k.preventDefault(),N(c)},title:w("common:floatingButtons.supervisorOverview"),children:"🎖️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(d),onTouchEnd:k=>{k.preventDefault(),N(d)},title:w("common:floatingButtons.controls"),children:"⌨️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(f),onTouchEnd:k=>{k.preventDefault(),N(f)},title:w("common:floatingButtons.manageSkills"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>N(h),onTouchEnd:k=>{k.preventDefault(),N(h)},title:w("common:floatingButtons.viewSnapshots"),children:"📸"})]})]})}),TW=x.memo(function({onOpenToolbox:e,onOpenCommander:n,onOpenSupervisor:s,onOpenControls:a,onOpenSkills:r,onOpenSnapshots:i,isGeneratingReport:c,pip:d}){const{t:f}=dt(["common","terminal"]),h=Vr();return o.jsxs(o.Fragment,{children:[h.experimentalVoiceAssistant&&o.jsx(JT,{}),o.jsx(os,{content:f("common:floatingButtons.settingsAndTools"),position:"left",children:o.jsx("button",{className:"floating-settings-btn",onClick:e,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(os,{content:f("common:floatingButtons.commanderView"),position:"left",children:o.jsx("button",{className:"commander-toggle-btn",onClick:n,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(os,{content:f("common:floatingButtons.viewSnapshots"),position:"left",children:o.jsx("button",{className:"snapshots-toggle-btn",onClick:i,children:"📸"})}),o.jsx(os,{content:f(c?"terminal:supervisor.generating":"common:floatingButtons.supervisorOverview"),position:"left",children:o.jsxs("button",{className:`supervisor-toggle-btn ${c?"generating":""}`,onClick:s,children:["🎖️",c&&o.jsx("span",{className:"supervisor-generating-indicator"})]})}),o.jsx(os,{content:f("common:floatingButtons.controls"),position:"left",children:o.jsx("button",{className:"shortcuts-toggle-btn",onClick:a,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(os,{content:f("common:floatingButtons.manageSkills"),position:"left",children:o.jsx("button",{className:"skills-toggle-btn",onClick:r,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(os,{content:d.isSupported?d.isOpen?f("common:floatingButtons.closePip"):f("common:floatingButtons.openPip"):f("common:floatingButtons.pipNotSupported"),position:"left",disabled:!d.isSupported,children:o.jsx("button",{className:`pip-toggle-btn ${d.isOpen?"active":""}`,onClick:()=>d.isSupported&&d.toggle({width:320,height:400}),disabled:!d.isSupported,children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),o.jsx("rect",{x:"12",y:"9",width:"8",height:"6",rx:"1"})]})})})]})}),_W=Ce.lazy(()=>vt(()=>import("./SpawnModal-D2e4lCt9.js"),__vite__mapDeps([17,3,1,4])).then(t=>({default:t.SpawnModal}))),EW=Ce.lazy(()=>vt(()=>import("./BossSpawnModal-CWxP-MSv.js"),__vite__mapDeps([18,3,1,4])).then(t=>({default:t.BossSpawnModal}))),MW=Ce.lazy(()=>vt(()=>import("./SubordinateAssignmentModal-B_rjqVum.js"),__vite__mapDeps([19,3,1,4])).then(t=>({default:t.SubordinateAssignmentModal}))),DW=Ce.lazy(()=>vt(()=>import("./index-DHFWfrE-.js"),__vite__mapDeps([20,3,1,4,21])).then(t=>({default:t.Toolbox}))),RW=Ce.lazy(()=>vt(()=>import("./index-BoWUyxxn.js"),__vite__mapDeps([22,3,1,4])).then(t=>({default:t.BuildingConfigModal}))),OW=Ce.lazy(()=>vt(()=>import("./index-CsBPIIxt.js"),__vite__mapDeps([23,24,3,1,4])).then(t=>({default:t.CommanderView}))),LW=Ce.lazy(()=>vt(()=>import("./SupervisorPanel-BAXOUwAk.js"),__vite__mapDeps([25,3,1,4])).then(t=>({default:t.SupervisorPanel}))),IW=Ce.lazy(()=>vt(()=>import("./index-DWfphUcy.js").then(t=>t.y),[]).then(t=>({default:t.FileExplorerPanel}))),PW=Ce.lazy(()=>vt(()=>import("./index-D3k7Y2rz.js"),__vite__mapDeps([26,3,1,4])).then(t=>({default:t.Spotlight}))),BW=Ce.lazy(()=>vt(()=>import("./ControlsModal-B5r9l6t1.js"),__vite__mapDeps([27,3,1,4])).then(t=>({default:t.ControlsModal}))),FW=Ce.lazy(()=>vt(()=>import("./SkillsPanel-DqqJjbX5.js"),__vite__mapDeps([28,3,1,4])).then(t=>({default:t.SkillsPanel}))),zW=Ce.lazy(()=>vt(()=>Promise.resolve().then(()=>k2),void 0).then(t=>({default:t.AgentEditModal}))),$W=Ce.lazy(()=>vt(()=>import("./SnapshotManager-4ig8bV_o.js"),__vite__mapDeps([29,3,1,4])).then(t=>({default:t.SnapshotManager}))),UW=Ce.lazy(()=>vt(()=>import("./RestoreArchivedAreaModal-DvbQVeiA.js"),__vite__mapDeps([30,3,1,4])).then(t=>({default:t.RestoreArchivedAreaModal}))),HW=Ce.lazy(()=>vt(()=>import("./IntegrationsPanel-1xcUvOle.js"),__vite__mapDeps([31,3,1,4])).then(t=>({default:t.IntegrationsPanel}))),WW=Ce.lazy(()=>vt(()=>import("./MonitoringModal-DWk0piqs.js"),__vite__mapDeps([32,3,1,4])).then(t=>({default:t.MonitoringModal}))),qW=Ce.lazy(()=>vt(()=>import("./WorkflowEditorPanel-DkzFKMCZ.js"),__vite__mapDeps([33,3,1,4])).then(t=>({default:t.WorkflowEditorPanel}))),VW=Ce.lazy(()=>vt(()=>import("./TriggerManagerPanel-D48mxJNq.js"),__vite__mapDeps([34,3,1,4])).then(t=>({default:t.TriggerManagerPanel})));function YW({spawnModal:t,bossSpawnModal:e,subordinateModal:n,toolboxModal:s,commanderModal:a,deleteConfirmModal:r,supervisorModal:i,spotlightModal:c,controlsModal:d,skillsModal:f,integrationsModal:h,monitoringModal:m,workflowEditorModal:b,triggerManagerModal:y,buildingModal:w,agentEditModal:C,snapshotsModal:N,restoreArchivedModal:k,explorerModal:j,contextMenu:S,spawnPosition:T,spawnAreaId:D,explorerFolderPath:E,contextMenuActions:I,buildingInitialPosition:O,sceneConfig:_,onConfigChange:M,onToolChange:R,onOpenAreaExplorer:z,onDeleteSelectedAgents:$,pendingBuildingDelete:W,onCancelBuildingDelete:L,onConfirmBuildingDelete:F,showBackNavModal:H,onCloseBackNavModal:V,onLeave:G,onOpenPM2LogsModal:B,onOpenBossLogsModal:K,onOpenDatabasePanel:ne,onSyncScene:q}){const xe=Rs(),Ae=Array.from(xe.snapshots.values()),Z=xe.snapshotsLoading;xe.currentSnapshot,x.useEffect(()=>{N.isOpen&&U.fetchSnapshots()},[N.isOpen]);const ce=W==="selected",me=W&&W!=="selected"?xe.buildings.get(W):null,ee=xe.selectedBuildingIds.size;return o.jsxs(x.Suspense,{fallback:null,children:[o.jsx(DW,{config:_,onConfigChange:M,onToolChange:R,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:re=>w.open(re||null),onOpenAreaExplorer:z,onOpenIntegrationsModal:re=>h.open(re),onOpenMonitoringModal:()=>m.open(),onOpenWorkflowEditor:()=>b.open(),onOpenTriggerManager:()=>y.open()}),o.jsx(RW,{isOpen:w.isOpen,onClose:w.close,buildingId:w.data,initialPosition:O||void 0}),o.jsx(_W,{isOpen:t.isOpen,onClose:t.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T,spawnAreaId:D}),o.jsx(EW,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T}),o.jsx(MW,{isOpen:n.isOpen,bossId:n.data||"",onClose:n.close}),C.isOpen&&C.data&&(()=>{const re=xe.agents.get(C.data);return re?o.jsx(zW,{agent:re,isOpen:C.isOpen,onClose:C.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:re=>{re.key==="Escape"&&r.close(),re.key==="Enter"&&$()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:re=>re.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 ",xe.selectedAgentIds.size," selected agent",xe.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:$,autoFocus:!0,children:"Remove"})]})]})}),(me||ce)&&o.jsx("div",{className:"modal-overlay visible",onClick:L,onKeyDown:re=>{re.key==="Escape"&&L(),re.key==="Enter"&&F()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:re=>re.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",ce&&ee>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[ce?o.jsxs("p",{children:["Delete ",ee," selected building",ee>1?"s":"","?"]}):o.jsxs("p",{children:["Delete ",o.jsx("strong",{children:me==null?void 0:me.name}),"?"]}),o.jsxs("p",{className:"confirm-modal-note",children:["This will permanently remove the building",ce&&ee>1?"s":""," and ",ce&&ee>1?"their":"its"," configuration."]})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:L,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:F,autoFocus:!0,children:"Delete"})]})]})}),H&&o.jsx("div",{className:"modal-overlay navigation-confirm-overlay visible",onClick:V,onKeyDown:re=>{re.key==="Escape"&&V()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:re=>re.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:V,autoFocus:!0,children:"Stay"}),o.jsx("button",{className:"btn btn-danger",onClick:G,children:"Leave"})]})]})}),o.jsx(x.Profiler,{id:"CommanderView",onRender:yu,children:o.jsx(OW,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(LW,{isOpen:i.isOpen,onClose:i.close}),o.jsx(IW,{isOpen:j.isOpen||E!==null||xe.explorerAreaId!==null,areaId:j.id||xe.explorerAreaId||null,folderPath:E,onChangeArea:re=>j.open(re),onClose:()=>{j.close(),U.closeFileExplorer()}}),o.jsx(PW,{isOpen:c.isOpen,onClose:c.close,onOpenSpawnModal:()=>t.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenSupervisor:()=>i.open(),onOpenFileExplorer:re=>j.open(re),onOpenPM2LogsModal:B,onOpenBossLogsModal:K,onOpenDatabasePanel:ne,onOpenMonitoringModal:()=>m.open()}),o.jsx(BW,{isOpen:d.isOpen,onClose:d.close}),o.jsx(FW,{isOpen:f.isOpen,onClose:f.close}),o.jsx(HW,{isOpen:h.isOpen,onClose:h.close,initialTab:h.data}),o.jsx(WW,{isOpen:m.isOpen,onClose:m.close}),o.jsx(qW,{isOpen:b.isOpen,onClose:b.close}),o.jsx(VW,{isOpen:y.isOpen,onClose:y.close}),o.jsx(UW,{isOpen:k.isOpen,restorePosition:k.data??null,onClose:k.close,onRestored:q}),N.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:N.close,children:o.jsx("div",{className:"modal snapshot-manager-modal",onClick:re=>re.stopPropagation(),children:o.jsx($W,{snapshots:Ae,isLoading:Z,onViewSnapshot:async re=>{await U.loadSnapshot(re),xe.selectedAgentIds.clear(),U.setTerminalOpen(!0),N.close()},onDeleteSnapshot:async re=>{await U.deleteSnapshot(re),await U.fetchSnapshots()},onRestoreSnapshot:async re=>{await U.restoreFiles(re)},onExportSnapshot:async re=>{await U.loadSnapshot(re),N.close()},onClose:N.close})})}),o.jsx(Do,{isOpen:S.isOpen,position:S.screenPosition,worldPosition:S.worldPosition,actions:I,onClose:S.close})]})}function GW({pip:t,title:e="Tide Commander",children:n}){return x.useEffect(()=>{t.pipWindow&&e&&(t.pipWindow.document.title=e)},[t.pipWindow,e]),!t.isOpen||!t.pipContainer?null:ac.createPortal(n,t.pipContainer)}function Oy(t){switch(t){case"working":return"⚡";case"waiting":return"⏳";case"waiting_permission":return"🔐";case"error":return"❌";case"offline":return"💤";case"orphaned":return"👻";case"idle":default:return"●"}}function Ly(t){switch(t){case"working":return"#4aff9e";case"waiting":return"#ff9e4a";case"waiting_permission":return"#ff4a9e";case"error":return"#ff4a4a";case"offline":return"#666";case"orphaned":return"#9e4aff";case"idle":default:return"#888"}}function Iy(t){const e=_o[t.class];return(e==null?void 0:e.icon)||"🤖"}function Rb({agent:t,onClick:e}){const n=Ly(t.status),s=Oy(t.status),a=Iy(t);return o.jsxs("div",{className:`pip-agent-card pip-status-${t.status}`,onClick:()=>e(t.id),title:"Click to view conversation",children:[o.jsxs("div",{className:"pip-agent-header",children:[o.jsx("span",{className:"pip-agent-icon",children:a}),o.jsx("span",{className:"pip-agent-name",children:t.name}),o.jsx("span",{className:"pip-agent-status",style:{color:n},children:s})]}),t.taskLabel&&o.jsxs("div",{className:"pip-agent-task",children:["📋 ",t.taskLabel]}),!t.taskLabel&&t.status==="working"&&t.currentTask&&o.jsx("div",{className:"pip-agent-task",children:t.currentTask.length>60?t.currentTask.slice(0,60)+"...":t.currentTask}),t.currentTool&&o.jsxs("div",{className:"pip-agent-tool",children:[o.jsx("span",{className:"pip-tool-label",children:"Tool:"})," ",t.currentTool]}),o.jsxs("div",{className:"pip-agent-context",children:[o.jsx("div",{className:"pip-context-bar",children:o.jsx("div",{className:"pip-context-fill",style:{width:`${Math.min(Math.round(t.contextUsed/t.contextLimit*100),100)}%`,backgroundColor:t.contextUsed/t.contextLimit*100>80?"#ff4a4a":t.contextUsed/t.contextLimit*100>50?"#ff9e4a":"#4aff9e"}})}),o.jsxs("span",{className:"pip-context-percent",children:[Math.round(t.contextUsed/t.contextLimit*100),"%"]})]})]})}function xu(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}const XA={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},JA={systemPrompt:"System Prompt",systemTools:"System Tools",messages:"Messages",freeSpace:"Free Space",autocompactBuffer:"Autocompact Buffer"};function KW({agent:t,onBack:e}){const n=Iy(t),s=Ly(t.status),a=t.contextStats,r=Math.round(t.contextUsed/t.contextLimit*100),i=t.contextUsed/t.contextLimit*100>80?"#ff4a4a":t.contextUsed/t.contextLimit*100>50?"#ff9e4a":"#4aff9e",c=["systemPrompt","systemTools","messages","autocompactBuffer","freeSpace"];return o.jsxs("div",{className:"pip-container pip-stats-container",children:[o.jsxs("div",{className:"pip-header pip-header-conversation",children:[o.jsx("button",{className:"pip-back-btn",onClick:e,title:"Back to conversation",children:"←"}),o.jsx("span",{className:"pip-agent-icon",children:n}),o.jsx("span",{className:"pip-title",children:t.name}),o.jsx("span",{className:"pip-agent-status-small",style:{color:s},children:Oy(t.status)})]}),o.jsx("div",{className:"pip-stats-content",children:a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"pip-model-info",children:[o.jsxs("div",{className:"pip-model-info-item",children:[o.jsx("div",{className:"pip-model-info-label",children:"Model"}),o.jsx("div",{className:"pip-model-info-value",children:a.model})]}),o.jsxs("div",{className:"pip-model-info-item",children:[o.jsx("div",{className:"pip-model-info-label",children:"Window"}),o.jsx("div",{className:"pip-model-info-value",children:xu(a.contextWindow)})]})]}),o.jsxs("div",{className:"pip-stats-section",children:[o.jsxs("div",{className:"pip-usage-header",children:[o.jsx("span",{className:"pip-usage-label",children:"Context Usage"}),o.jsxs("span",{className:"pip-usage-value",style:{color:i},children:[xu(a.totalTokens)," / ",xu(a.contextWindow)," (",a.usedPercent,"%)"]})]}),o.jsx("div",{className:"pip-stacked-bar",children:c.map(d=>{const f=a.categories[d];return!f||f.percent<=0?null:o.jsx("div",{className:"pip-stacked-bar-segment",style:{width:`${f.percent}%`,backgroundColor:XA[d]},title:`${JA[d]}: ${xu(f.tokens)}`},d)})})]}),o.jsxs("div",{className:"pip-stats-section",children:[o.jsx("h3",{className:"pip-stats-title",children:"Token Breakdown"}),o.jsx("div",{className:"pip-category-list",children:c.map(d=>{const f=a.categories[d];if(!f)return null;const h=d==="freeSpace";return o.jsxs("div",{className:`pip-category-item ${h?"free-space":""}`,children:[o.jsx("div",{className:"pip-category-color",style:{backgroundColor:XA[d]}}),o.jsxs("div",{className:"pip-category-info",children:[o.jsx("div",{className:"pip-category-name",children:JA[d]}),o.jsxs("div",{className:"pip-category-tokens",children:[xu(f.tokens)," (",f.percent.toFixed(1),"%)"]})]})]},d)})})]}),o.jsxs("div",{className:"pip-stats-updated",children:["Updated: ",new Date(a.lastUpdated).toLocaleTimeString()]})]}):o.jsxs("div",{className:"pip-stats-section",children:[o.jsx("h3",{className:"pip-stats-title",children:"Context Usage"}),o.jsxs("div",{className:"pip-stats-bar-container",children:[o.jsx("div",{className:"pip-stats-bar",children:o.jsx("div",{className:"pip-stats-bar-fill",style:{width:`${Math.min(r,100)}%`,backgroundColor:i}})}),o.jsxs("span",{className:"pip-stats-percent",style:{color:i},children:[r,"%"]})]}),o.jsx("div",{className:"pip-stats-info",children:o.jsx("p",{className:"pip-stats-info-text",children:"Context usage represents how much of the conversation window is filled. Detailed breakdown not available yet."})})]})})]})}function QW({agentId:t,onBack:e}){const n=Kj(t),s=Qj(t),a=r1(),r=i1(),i=Ux(),c=x.useRef(null),d=x.useRef(null),[f,h]=x.useState(""),[m,b]=x.useState(!1),[y]=x.useState("simple"),w=!!(n!=null&&n.sessionId),C=Wj({selectedAgentId:t,hasSessionId:w,reconnectCount:a,historyRefreshTrigger:r,lastPrompts:i,outputScrollRef:c}),N=_T({outputs:s,viewMode:y}),k=x.useMemo(()=>{const{history:$}=C,W=new Map;for(const F of $)F.type==="tool_result"&&F.toolUseId&&W.set(F.toolUseId,F.content);return(F=>F.map(H=>{if(H.type==="tool_use"&&H.toolName==="Bash"&&H.toolUseId){const V=W.get(H.toolUseId);let G;try{G=(H.toolInput||(H.content?JSON.parse(H.content):{})).command}catch{}return{...H,_bashOutput:V,_bashCommand:G}}return H}))($.filter(F=>F.type==="user"||F.type==="assistant"||F.type==="tool_use"))},[C.history]),[j,S]=x.useState({top:!1,bottom:!0}),T=x.useCallback(()=>{if(!c.current)return;const{scrollTop:$,scrollHeight:W,clientHeight:L}=c.current;S({top:$>20,bottom:$<W-L-20})},[]);x.useEffect(()=>{c.current&&(c.current.scrollTop=c.current.scrollHeight,T())},[s.length,k.length,T]);const D=x.useCallback(()=>{c.current&&c.current.scrollBy({top:-200,behavior:"smooth"})},[]),E=x.useCallback(()=>{c.current&&c.current.scrollBy({top:200,behavior:"smooth"})},[]),I=x.useCallback(()=>{const $=f.trim();!$||!n||(U.sendCommand(t,$),h(""),setTimeout(()=>{var W;return(W=d.current)==null?void 0:W.focus()},50))},[f,t,n]),O=x.useCallback($=>{h($.target.value)},[]),_=x.useCallback($=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),I())},[I]);x.useEffect(()=>{const $=setTimeout(()=>{var W;return(W=d.current)==null?void 0:W.focus()},100);return()=>clearTimeout($)},[t]);const M=x.useCallback(($,W)=>{const L=sh($,n==null?void 0:n.cwd),F=L.line?{...W||{},targetLine:L.line}:W;U.setFileViewerPath(L.path,F,n==null?void 0:n.cwd)},[n==null?void 0:n.cwd]);if(!n)return o.jsx("div",{className:"pip-container",children:o.jsxs("div",{className:"pip-header pip-header-conversation",children:[o.jsx("button",{className:"pip-back-btn",onClick:e,title:"Back to agents list",children:"←"}),o.jsx("span",{className:"pip-title",children:"Agent not found"})]})});const R=Iy(n),z=Ly(n.status);return m?o.jsx(KW,{agent:n,onBack:()=>b(!1)}):o.jsxs("div",{className:"pip-container pip-conversation-container",children:[o.jsxs("div",{className:"pip-header pip-header-conversation",children:[o.jsx("button",{className:"pip-back-btn",onClick:e,title:"Back to agents list",children:"←"}),o.jsx("span",{className:"pip-agent-icon",children:R}),o.jsx("span",{className:"pip-title",children:n.name}),o.jsx("span",{className:"pip-agent-status-small",style:{color:z},children:Oy(n.status)})]}),o.jsx("div",{className:"pip-context-section",children:o.jsx(y1,{contextInfo:Xp(n),onClick:()=>b(!0)})}),o.jsxs("div",{className:"pip-conversation-wrapper",children:[o.jsxs("div",{className:"pip-conversation guake-output",ref:c,onScroll:T,children:[!C.loadingHistory&&C.hasMore&&o.jsx("div",{className:"guake-load-more pip-load-more",children:C.loadingMore?o.jsx("span",{children:"Loading older messages..."}):o.jsxs("button",{onClick:C.loadMoreHistory,children:["Load more (",C.totalCount-C.history.length," older)"]})}),C.loadingHistory&&o.jsx("div",{className:"pip-loading-indicator",children:o.jsxs("span",{className:"loading-dots",children:[o.jsx("span",{children:"."}),o.jsx("span",{children:"."}),o.jsx("span",{children:"."})]})}),k.map(($,W)=>o.jsx(QT,{message:$,agentId:t,simpleView:!0,onFileClick:M},`h-${W}`)),N.map(($,W)=>o.jsx(Dy,{output:$,agentId:t,onFileClick:M},`o-${W}`)),!C.loadingHistory&&k.length===0&&N.length===0&&n.status!=="working"&&o.jsx("div",{className:"pip-empty",children:o.jsx("p",{children:"No conversation yet"})})]}),o.jsxs("div",{className:"pip-scroll-controls",children:[j.top&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-up",onClick:D,title:"Scroll up",children:"↑"}),j.bottom&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-down",onClick:E,title:"Scroll down",children:"↓"})]})]}),n.currentTool&&o.jsx("div",{className:"pip-current-tool",children:o.jsxs("span",{className:"pip-tool-indicator",children:["Using: ",n.currentTool]})}),o.jsxs("div",{className:"pip-input-area",children:[o.jsx("input",{ref:d,type:"text",className:"pip-input",placeholder:`Message ${n.name}...`,value:f,onChange:O,onKeyDown:_,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1}),o.jsx("button",{className:"pip-send-btn",onClick:I,disabled:!f.trim(),title:"Send message",children:"➤"})]})]})}function XW({onSelectAgent:t}){const e=Kp(),n=e.filter(c=>c.status==="working"),s=e.filter(c=>c.status==="waiting"||c.status==="waiting_permission"),a=e.filter(c=>c.status!=="working"&&c.status!=="waiting"&&c.status!=="waiting_permission"),r=e.length,i=n.length+s.length;return o.jsxs("div",{className:"pip-container",children:[o.jsxs("div",{className:"pip-header",children:[o.jsx("span",{className:"pip-title",children:"Tide Commander"}),o.jsxs("span",{className:"pip-stats",children:[i,"/",r," active"]})]}),o.jsxs("div",{className:"pip-agents-list",children:[n.length>0&&o.jsxs("div",{className:"pip-section",children:[o.jsxs("div",{className:"pip-section-title",children:["Working (",n.length,")"]}),n.map(c=>o.jsx(Rb,{agent:c,onClick:t},c.id))]}),s.length>0&&o.jsxs("div",{className:"pip-section",children:[o.jsxs("div",{className:"pip-section-title",children:["Waiting (",s.length,")"]}),s.map(c=>o.jsx(Rb,{agent:c,onClick:t},c.id))]}),a.length>0&&o.jsxs("div",{className:"pip-section",children:[o.jsxs("div",{className:"pip-section-title",children:["Idle (",a.length,")"]}),a.map(c=>o.jsx(Rb,{agent:c,onClick:t},c.id))]}),e.length===0&&o.jsx("div",{className:"pip-empty",children:o.jsx("p",{children:"No agents spawned yet"})})]})]})}function JW(){const[t,e]=x.useState(null),n=a=>{e(a)},s=()=>{e(null)};return t?o.jsx(QW,{agentId:t,onBack:s}):o.jsx(XW,{onSelectAgent:n})}function ZW(t){const e=t.trim();if(!e)return{ok:!0,normalizedUrl:""};let n;try{n=new URL(e)}catch{return{ok:!1,normalizedUrl:"",error:"Invalid URL format. Use http://host:port"}}return n.protocol!=="http:"&&n.protocol!=="https:"?{ok:!1,normalizedUrl:"",error:"Unsupported protocol. Use http or https"}:{ok:!0,normalizedUrl:e}}async function eq(t,e=5e3,n=fetch){if(!t)return{ok:!0};const a=`${t.replace(/\/$/,"")}/api/health`,r=new AbortController,i=setTimeout(()=>r.abort(),e);try{const c=await n(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 tq=4e3;function nq(){const t=Jj(),[e,n]=x.useState(!1),[s,a]=x.useState(!1),[r,i]=x.useState(!0),[c,d]=x.useState(()=>Rx()),[f,h]=x.useState(!1),[m,b]=x.useState(null),[y,w]=x.useState(null),C=x.useRef(!0),N=x.useCallback((D=7e3)=>U.getState().isConnected?Promise.resolve(!0):new Promise(E=>{let I=!1;const O=R=>{I||(I=!0,clearTimeout(M),_(),E(R))},_=U.subscribe(()=>{U.getState().isConnected&&O(!0)}),M=setTimeout(()=>O(!1),D)}),[]);x.useEffect(()=>{const D=setTimeout(()=>i(!1),3e3);return()=>clearTimeout(D)},[]),x.useEffect(()=>()=>{C.current=!1},[]),x.useEffect(()=>VD(D=>{d(D)}),[]);const k=x.useCallback(()=>{navigator.clipboard.writeText("bunx tide-commander").then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(()=>{})},[]),j=x.useCallback(async()=>{if(f)return;const D=Date.now(),E=()=>tq-(Date.now()-D);b(null),w("Validating URL");const I=c.trim()||"http://localhost:6200",O=ZW(I);if(!O.ok){w(null),b(O.error||"Invalid backend URL");return}h(!0),w("Checking host reachability");const _=E();if(_<=0){h(!1),w(null),b("Connection timeout after 4 seconds");return}const M=await eq(O.normalizedUrl,_);if(!M.ok){if(!C.current)return;h(!1),w(null),E()<=0?b("Connection timeout after 4 seconds"):b(M.error||"Failed to reach host");return}qD(O.normalizedUrl),w("Connecting to server"),zR();const R=E();if(R<=0){h(!1),w(null),b("Connection timeout after 4 seconds");return}const z=await N(R);if(C.current){if(!z){h(!1),w(null),E()<=0?b("Connection timeout after 4 seconds"):b("Could not establish WebSocket connection. Verify host and auth token, then retry");return}h(!1),w("Connected"),b(null)}},[c,f,N]),S=x.useCallback(D=>{D.key==="Enter"&&!f&&j()},[j,f]),T=x.useCallback(()=>{n(!0)},[]);return t||e||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:k,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:c,disabled:f,onChange:D=>{const E=D.target.value;d(E),m&&b(null)},onKeyDown:S})}),o.jsx("span",{className:"config-hint",children:"Leave empty for auto-detect"}),y&&!m&&o.jsx("div",{className:"not-connected-status","aria-live":"polite",children:y}),m&&o.jsx("div",{className:"not-connected-error","aria-live":"assertive",children:m})]}),o.jsxs("div",{className:"not-connected-actions",children:[o.jsx("button",{className:"not-connected-btn not-connected-btn-retry",onClick:()=>{j()},disabled:f,children:f?"Connecting...":"↻ Connect"}),o.jsx("button",{className:"not-connected-btn not-connected-btn-explore",onClick:T,children:"Explore"})]})]})})}const ZA="tide-onboarding-dismissed";function sq({onCreateAgent:t}){const{t:e}=dt("common"),n=Jj(),s=Gj(),[a,r]=x.useState(()=>sessionStorage.getItem(ZA)==="1"),i=n&&!a&&s===0,c=x.useCallback(()=>{r(!0),sessionStorage.setItem(ZA,"1")},[]),d=x.useCallback(()=>{c(),t()},[c,t]),f=x.useCallback(h=>{h.key==="Escape"&&c()},[c]);return i?o.jsx(pr,{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 ZT(){return{"Content-Type":"application/json","X-Auth-Token":Ii()}}async function aq(t){const e=await fetch(`${Ea()}/api/areas/${t}/organize`,{method:"POST",headers:ZT()});if(!e.ok)throw new Error(`Failed to organize area: ${e.statusText}`);const n=await e.json();return{organized:Array.isArray(n.organized)?n.organized:[],buildings:Array.isArray(n.buildings)?n.buildings:[]}}async function rq(){const t=await fetch(`${Ea()}/api/areas/organize-all`,{method:"POST",headers:ZT()});if(!t.ok)throw new Error(`Failed to organize all areas: ${t.statusText}`);const e=await t.json();return Array.isArray(e.organized)?{organized:e.organized,buildings:Array.isArray(e.buildings)?e.buildings:[]}:(Array.isArray(e.results)?e.results:[]).reduce((n,s)=>(n.organized.push(...s.organized),n.buildings.push(...s.buildings),n),{organized:[],buildings:[]})}function e_(t,e){var s,a;const n=U.getState();for(const r of t.organized){const i=n.agents.get(r.agentId);if(i){const c={...i,position:r.position};U.updateAgent(c),(s=e.current)==null||s.updateAgent(c,!0)}}for(const r of t.buildings){const i=n.buildings.get(r.buildingId);i&&(U.updateBuilding(r.buildingId,{position:r.position}),(a=e.current)==null||a.updateBuilding({...i,position:r.position}))}}function iq(t,e,n,s,a,r){const i=[];if(e.type==="agent"&&e.id){const d=n.get(e.id);if(d)return i.push({id:"select-agent",label:`Select ${d.name}`,icon:"👆",onClick:()=>{var f;U.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:()=>{U.selectAgent(e.id),U.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;U.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:()=>{U.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}}))}}),i.push({id:"divider-area-layer",label:"",divider:!0,onClick:()=>{}}),i.push({id:"bring-to-front",label:"Bring to Front",icon:"⬆️",onClick:()=>{var f;U.bringAreaToFront(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),i.push({id:"send-to-back",label:"Send to Back",icon:"⬇️",onClick:()=>{var f;U.sendAreaToBack(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),d.assignedAgentIds.length>0&&i.push({id:"organize-area",label:"Organize Area",icon:"✨",onClick:()=>{aq(e.id).then(f=>{e_(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;U.archiveArea(e.id,y=>U.stopAgent(y)),(m=r.sceneRef.current)==null||m.syncAreas(),(b=r.sceneRef.current)==null||b.syncAgents(Array.from(U.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;U.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:()=>{U.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};U.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:()=>{U.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(t),r.openSpawnModal()}}),i.push({id:"spawn-boss",label:"Spawn Boss Here",icon:"👑",onClick:()=>{r.setSpawnPosition(t),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(t)}}),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 oq=Ce.lazy(()=>vt(()=>import("./index-BrgM4K8j.js"),__vite__mapDeps([35,3,1,4,36])).then(t=>({default:t.DatabasePanel}))),lq=Ce.lazy(()=>vt(()=>import("./PM2LogsModal-GxDWxG5c.js"),__vite__mapDeps([37,38,3,1,4])).then(t=>({default:t.PM2LogsModal}))),cq=Ce.lazy(()=>vt(()=>import("./DockerLogsModal-CWwOgxQG.js"),__vite__mapDeps([39,38,3,1,4])).then(t=>({default:t.DockerLogsModal}))),uq=Ce.lazy(()=>vt(()=>import("./BossLogsModal-Bn3z56OP.js"),__vite__mapDeps([40,38,3,1,4])).then(t=>({default:t.BossLogsModal}))),dq=Ce.lazy(()=>vt(()=>import("./Scene2DCanvas-DLvMkm2q.js"),__vite__mapDeps([41,3,1,4,42])).then(t=>({default:t.Scene2DCanvas}))),fq=Ce.lazy(()=>vt(()=>import("./index-CdlqvN8h.js"),__vite__mapDeps([43,3,1,4,44])).then(t=>({default:t.DashboardView}))),pq=Ce.lazy(()=>vt(()=>import("./IframeModal-BsbB4AMI.js"),__vite__mapDeps([45,3,1,4,46])).then(t=>({default:t.IframeModal}))),hq=Ce.lazy(()=>vt(()=>import("./SaveSnapshotModal-DpONGDMt.js"),__vite__mapDeps([47,3,1,4])).then(t=>({default:t.SaveSnapshotModal})));function mq(){const{t}=dt(["common","notifications"]),e=x.useRef(null),n=x.useRef(null),s=cs(),a=cs(),r=cs(),i=cs(),c=cs(),d=cs(),f=cs(),h=cs(),m=cs(),b=cs(),y=cs(),w=cs(),C=cs(),N=cs(),k=cs(),j=cs(),S=cs(),T=cs(),D=cs(),E=YD(),I=JO(),O=GD(),_=rR(),[M,R]=x.useState(null),z=KR(),[$,W]=x.useState(!1),[L,F]=x.useState(null),[H,V]=x.useState(null),[G,B]=x.useState(null),[K,ne]=x.useState(null),[q,xe]=x.useState(null),[Ae,Z]=x.useState(null),[ce,me]=x.useState(null),[ee,re]=x.useState(null),[We,ze]=x.useState(null),[Pe,ge]=x.useState(null),Te=x.useCallback(Ne=>{ge(Ne),Ne&&localStorage.setItem("tide-commander-last-database-building",Ne)},[]),qe=x.useCallback(()=>Te(null),[Te]),{handleMouseDown:it,handleClick:he}=Ta(qe),Be=x.useCallback(()=>ze(null),[]),{handleMouseDown:ie,handleClick:de}=Ta(Be),He=x.useRef(Ae);He.current=Ae;const et=x.useCallback(Ne=>{Z(Ne)},[]),ct=x.useCallback(()=>He.current,[]),fe=x.useRef(null),[X,se]=x.useState($j),[Se,J]=x.useState(0),[pe,Re]=x.useState(!1),[$e,ye]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[Ie,te]=x.useState(!1),[be,we]=x.useState(!1),Fe=t1(),Ke=o1(),st=Wx(),ft=qx(),wt=e1(),{showToast:rt}=u1(),{showAgentNotification:gt}=AL(),{showBackNavModal:ht,setShowBackNavModal:Gt,handleLeave:tn}=pO();iO({showToast:rt,showAgentNotification:gt});const[je,Oe]=x.useState(!1);x.useEffect(()=>{const Ne=Je=>{var ot;((ot=Je.detail)==null?void 0:ot.mode)==="3d"&&Oe(!0)};return window.addEventListener("tide:viewmode-switch-pressed",Ne),()=>{window.removeEventListener("tide:viewmode-switch-pressed",Ne)}},[]),x.useEffect(()=>{Ke==="3d"&&Oe(!0)},[Ke]);const Ye=rO({canvasRef:e,selectionBoxRef:n,viewMode:Ke,sceneMountKey:Se,showToast:rt,showAgentNotification:gt,toolboxModal:i,contextMenu:O,setHoveredAgentPopup:xe,setBuildingPopup:et,getBuildingPopup:ct,openBuildingModal:Ne=>k.open(Ne),openPM2LogsModal:Ne=>me(Ne),openBossLogsModal:Ne=>re(Ne),openDatabasePanel:Ne=>Te(Ne),onSceneLoadingChange:Oe}),Ze=Gj(),Ot=ur(),Ft=Hx(),Lt=$x(),Vt=VO(),ln=qO(),bt=WO(),at=Vr(),xt=GO(),$t=cL(),En=uL(),nn=x.useMemo(()=>Array.from(Lt),[Lt]),Un=x.useRef(!1);Mj("AppContent"),oO(Ye),lO(Ye),cO(Ye),gO(),uO(Ye,ln),dO(Ye,at.powerSaving),x.useEffect(()=>{var Ne;document.title=((Ne=at.tabTitle)==null?void 0:Ne.trim())||"Tide Commander"},[at.tabTitle]),x.useEffect(()=>{var Dn,Fs;if(Un.current||typeof window>"u")return;const Ne=new URLSearchParams(window.location.search),Je=(Dn=Ne.get("agentId"))==null?void 0:Dn.trim(),Ct=(Fs=Ne.get("agentName"))==null?void 0:Fs.trim();if(!Je&&!Ct||Ze===0)return;const ot=U.getState().agents,jn=Ne.get("openTerminal"),Mt=jn?["1","true","yes"].includes(jn.toLowerCase()):!0;let At=Je?ot.get(Je):void 0;if(!At&&Ct){const Qr=Ct.toLowerCase();At=Array.from(ot.values()).find(pa=>pa.name.toLowerCase()===Qr)}if(!At){console.warn("[DeepLink] No matching agent found for query params",{rawAgentId:Je,rawAgentName:Ct}),Un.current=!0;return}U.selectAgent(At.id),Mt&&U.setTerminalOpen(!0),Ne.delete("agentId"),Ne.delete("agentName"),Ne.delete("openTerminal");const kn=Ne.toString(),ms=`${window.location.pathname}${kn?`?${kn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,ms),Un.current=!0},[Ze]),fO({sceneRef:Ye,spawnModal:s,commanderModal:c,explorerModal:E,spotlightModal:h,deleteConfirmModal:d,onRequestBuildingDelete:()=>ne("selected"),onOpenDatabasePanel:Te,onCloseDatabasePanel:qe,databasePanelOpen:Pe!==null}),Xt("spawn-modal",s.isOpen,s.close),Xt("boss-spawn-modal",a.isOpen,a.close),Xt("subordinate-modal",r.isOpen,r.close),Xt("toolbox-modal",i.isOpen,i.close),Xt("commander-modal",c.isOpen,c.close),Xt("delete-confirm-modal",d.isOpen,d.close),Xt("supervisor-modal",f.isOpen,f.close),Xt("spotlight-modal",h.isOpen,h.close),Xt("controls-modal",m.isOpen,m.close),Xt("skills-modal",b.isOpen,b.close),Xt("integrations-modal",y.isOpen,y.close),Xt("monitoring-modal",w.isOpen,w.close),Xt("workflow-editor-modal",C.isOpen,C.close),Xt("trigger-manager-modal",N.isOpen,N.close),Xt("building-modal",k.isOpen,k.close),Xt("agent-edit-modal",j.isOpen,j.close),Xt("snapshots-modal",S.isOpen,S.close),Xt("save-snapshot-modal",T.isOpen,T.close),Xt("explorer-modal",E.isOpen||I!==null,()=>{E.close(),U.closeFileExplorer()}),Xt("context-menu",O.isOpen,O.close),Xt("mobile-sidebar",pe,()=>Re(!1)),Xt("mobile-fab-menu",be,()=>we(!1)),Xt("file-viewer",st!==null,()=>U.clearFileViewerPath()),Xt("context-modal",ft!==null,()=>U.closeContextModal()),Xt("terminal",wt,()=>U.setTerminalOpen(!1)),Xt("pm2-logs-modal",ce!==null,()=>me(null)),Xt("boss-logs-modal",ee!==null,()=>re(null)),Xt("database-panel",Pe!==null,qe),Xt("terminal-modal",We!==null,Be);const Os=x.useRef(wt),ps=x.useRef(b),ks=x.useRef(m);ps.current=b,ks.current=m,x.useEffect(()=>{Os.current&&!wt&&(ps.current.close(),ks.current.close()),Os.current=wt},[wt]),x.useEffect(()=>{},[]),x.useEffect(()=>{if(Fe!=="3d"||Ke!=="3d")return;const Ne=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(Ne)},[Fe,Ke]);const Qn=x.useCallback(Ne=>{var Je,Ct,ot,jn,Mt,At,kn,ms,Dn,Fs;se(Ne),sO(Ne),(Je=Ye.current)==null||Je.setCharacterScale(Ne.characterScale),(Ct=Ye.current)==null||Ct.setScale3D(Ne.scale3d),(ot=Ye.current)==null||ot.setGridVisible(Ne.gridVisible),(jn=Ye.current)==null||jn.setTimeMode(Ne.timeMode),(Mt=Ye.current)==null||Mt.setTerrainConfig(Ne.terrain),(At=Ye.current)==null||At.setFloorStyle(Ne.terrain.floorStyle),(kn=Ye.current)==null||kn.setAgentModelStyle(Ne.modelStyle),(ms=Ye.current)==null||ms.setIdleAnimation(Ne.animations.idleAnimation),(Dn=Ye.current)==null||Dn.setWorkingAnimation(Ne.animations.workingAnimation),(Fs=Ye.current)==null||Fs.setFpsLimit(Ne.fpsLimit)},[Ye]),Ss=x.useCallback(Ne=>{var Je;if((Je=Ye.current)==null||Je.setDrawingTool(Ne),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(Ne),Ne==="rectangle"||Ne==="circle"){const Ct=t(Ne==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");rt("info",Ct,t("notifications:drawing.clickAndDrag"),3e3)}},[Ye,rt]),Fn=x.useCallback(Ne=>{var Je;(Je=Ye.current)==null||Je.focusAgent(Ne)},[Ye]),Ls=x.useCallback(Ne=>{U.killAgent(Ne)},[]),Is=x.useCallback(Ne=>{var Je;(Je=Ye.current)==null||Je.callSubordinates(Ne)},[Ye]),wn=x.useCallback(Ne=>{E.open(Ne)},[E]),Po=x.useCallback(()=>{k.open(null)},[k]),Bo=x.useCallback(()=>{var Ne;(Ne=Ye.current)==null||Ne.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),rt("info",t("notifications:drawing.rectangleTool"),t("notifications:drawing.clickAndDrag"),3e3)},[Ye,rt]),Ps=x.useCallback(Ne=>{R(Ne)},[]),Ua=x.useCallback(()=>{R(null)},[]),Bi=x.useCallback(()=>{const Ne=Array.from(U.getState().selectedAgentIds);Ne.forEach(Je=>{var Ct;U.removeAgentFromServer(Je),(Ct=Ye.current)==null||Ct.removeAgent(Je)}),d.close(),rt("info",t("notifications:toast.agentsRemoved"),t("notifications:toast.agentsRemovedMsg",{count:Ne.length}))},[rt,d,Ye,t]),Fi=x.useCallback(()=>{var Ne,Je;if(K==="selected"){const Ct=Vt.size;U.deleteSelectedBuildings(),(Ne=Ye.current)==null||Ne.syncBuildings(),rt("info",t("notifications:toast.buildingsDeleted"),t("notifications:toast.buildingsDeletedMsg",{count:Ct}))}else if(K){const Ct=Ft.get(K);U.deleteBuilding(K),(Je=Ye.current)==null||Je.syncBuildings(),rt("info",t("notifications:toast.buildingDeleted"),t("notifications:toast.buildingDeletedMsg",{name:(Ct==null?void 0:Ct.name)||"Building"}))}ne(null)},[K,Ft,Vt.size,rt,Ye,t]),Bs=x.useMemo(()=>iq(O.worldPosition,O.target,U.getState().agents,Ot,Ft,{showToast:rt,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:Ne=>E.open(Ne),openBuildingModal:Ne=>k.open(Ne),openAgentEditModal:Ne=>j.open(Ne),requestBuildingDelete:Ne=>ne(Ne),setSpawnPosition:F,openRestoreArchivedModal:Ne=>D.open(Ne),sceneRef:Ye}),[O.worldPosition,O.target,Ot,Ft,s,a,k,i,c,E,j,D,rt,Ye]);x.useEffect(()=>{!s.isOpen&&!a.isOpen&&(F(null),B(null))},[s.isOpen,a.isOpen]),x.useEffect(()=>{const Ne=Mt=>{const At=Mt.detail;B((At==null?void 0:At.areaId)||null),F((At==null?void 0:At.position)||null),s.open()},Je=Mt=>{var ms,Dn;const At=Mt.detail;if(!(At!=null&&At.buildingId))return;const kn=U.getState().buildings.get(At.buildingId);kn&&(kn.type==="server"&&((ms=kn.pm2)!=null&&ms.enabled)?me(At.buildingId):kn.type==="boss"?re(At.buildingId):kn.type==="database"?Te(At.buildingId):kn.type==="folder"&&kn.folderPath?U.openFileExplorer(kn.folderPath):kn.type==="terminal"&&((Dn=kn.terminalStatus)!=null&&Dn.url)?ze(At.buildingId):k.open(At.buildingId))},Ct=Mt=>{const At=Mt.detail;At!=null&&At.buildingId&&k.open(At.buildingId)},ot=Mt=>{const At=Mt.detail;V((At==null?void 0:At.position)||null),k.open(null)},jn=Mt=>{const At=Mt.detail;At!=null&&At.buildingId?ze(At.buildingId):At!=null&&At.url&&R(At.url)};return window.addEventListener("tide:open-spawn-modal",Ne),window.addEventListener("tide:building-action",Je),window.addEventListener("tide:building-edit",Ct),window.addEventListener("tide:building-create",ot),window.addEventListener("tide:open-iframe-modal",jn),()=>{window.removeEventListener("tide:open-spawn-modal",Ne),window.removeEventListener("tide:building-action",Je),window.removeEventListener("tide:building-edit",Ct),window.removeEventListener("tide:building-create",ot),window.removeEventListener("tide:open-iframe-modal",jn)}},[s,k]);const lc=bt==="rectangle"||bt==="circle",Ma=x.useCallback(()=>{var Ne;(Ne=Ye.current)==null||Ne.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ye]),Ts=x.useCallback(()=>we(Ne=>!Ne),[]),hs=x.useCallback(()=>U.setMobileView("terminal"),[]),Mn=x.useCallback(()=>Re(!0),[]),zi=nn.length===1&&U.getOutputs(nn[0]).length>0;return o.jsxs("div",{className:`app ${wt?"terminal-open":""} ${lc?"drawing-mode":""} ${$e?"sidebar-collapsed":""} mobile-view-${Fe} view-mode-${Ke}`,children:[o.jsx(nq,{}),o.jsx(sq,{onCreateAgent:s.open}),o.jsx(SW,{visible:at.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(jW,{className:"app-view-mode-toggle"}),o.jsx(QR,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:$,title:"Auto-organize all agents in their areas",onClick:()=>{W(!0),rq().then(Ne=>{e_(Ne,Ye),rt("success","Organized",`Arranged ${Ne.organized.length} agent${Ne.organized.length!==1?"s":""}`)}).catch(Ne=>{console.error("organize all error:",Ne),rt("error","Organize Failed",Ne.message||"Failed to organize")}).finally(()=>W(!1))},children:[$?"⏳":"✨"," Organize"]})]}),o.jsxs("main",{className:"main-content",children:[o.jsxs("div",{className:"battlefield-container",children:[z&&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:Ke==="dashboard"?o.jsx(fq,{onSelectAgent:Ne=>U.selectAgent(Ne),onFocusAgent:Ne=>{U.setViewMode("3d"),Fn(Ne)},onKillAgent:Ls,onSelectBuilding:Ne=>U.selectBuilding(Ne),onOpenTerminal:Ne=>{U.selectAgent(Ne),U.setTerminalOpen(!0)},onFocusZone:Ne=>{U.setViewMode("3d");const Je=U.getState().areas.get(Ne);Je&&Je.assignedAgentIds.length>0&&Fn(Je.assignedAgentIds[0])}}):Ke==="2d"?o.jsx(dq,{onAgentClick:(Ne,Je)=>{Je?U.addToSelection(Ne):U.selectAgent(Ne)},onAgentDoubleClick:Ne=>{if(window.innerWidth<=768){U.openTerminalOnMobile(Ne);return}U.selectAgent(Ne),U.setTerminalOpen(!0)},onBuildingClick:(Ne,Je)=>{U.selectBuilding(Ne);const Ct=U.getState().buildings.get(Ne);(Ct==null?void 0:Ct.type)==="folder"&&Ct.folderPath?U.openFileExplorer(Ct.folderPath):((Ct==null?void 0:Ct.type)==="server"||(Ct==null?void 0:Ct.type)==="boss"||(Ct==null?void 0:Ct.type)==="database")&&(fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>{et({buildingId:Ne,screenPos:Je,fromClick:!0}),fe.current=null},150))},onBuildingDoubleClick:Ne=>{var Ct;fe.current&&(clearTimeout(fe.current),fe.current=null),et(null);const Je=U.getState().buildings.get(Ne);(Je==null?void 0:Je.type)==="server"&&((Ct=Je.pm2)!=null&&Ct.enabled)?me(Ne):(Je==null?void 0:Je.type)==="boss"?re(Ne):(Je==null?void 0:Je.type)==="database"?Te(Ne):(Je==null?void 0:Je.type)==="folder"&&Je.folderPath?U.openFileExplorer(Je.folderPath):k.open(Ne)},onGroundClick:()=>{U.selectAgent(null),U.selectBuilding(null)},onAreaDoubleClick:Ne=>{U.selectArea(Ne),i.open()},onContextMenu:(Ne,Je,Ct)=>{const ot=Ct?{type:Ct.type,id:Ct.id}:{type:"ground"};O.open(Ne,Je,ot)},onMoveCommand:(Ne,Je)=>{const ot=Ne.length,jn=[];if(ot===1)jn.push({x:Je.x,y:0,z:Je.z});else if(ot<=6){const Mt=1.2*Math.max(1,ot/3);for(let At=0;At<ot;At++){const kn=At/ot*Math.PI*2-Math.PI/2;jn.push({x:Je.x+Math.cos(kn)*Mt,y:0,z:Je.z+Math.sin(kn)*Mt})}}else{const Mt=Math.ceil(Math.sqrt(ot)),At=Math.ceil(ot/Mt),kn=(Mt-1)*1.2/2,ms=(At-1)*1.2/2;for(let Dn=0;Dn<ot;Dn++){const Fs=Dn%Mt,Qr=Math.floor(Dn/Mt);jn.push({x:Je.x+Fs*1.2-kn,y:0,z:Je.z+Qr*1.2-ms})}}Ne.forEach((Mt,At)=>{U.moveAgent(Mt,jn[At])})},onBuildingDragMove:(Ne,Je)=>{var ot;const Ct=U.getState().buildings.get(Ne);Ct&&(U.getState().buildings.set(Ne,{...Ct,position:{x:Je.x,z:Je.z}}),(ot=window.__tideScene2D)==null||ot.syncBuildings())},onBuildingDragEnd:(Ne,Je)=>{U.updateBuildingPosition(Ne,Je)},scale2d:X.scale2d,showTaskLabels:X.show2DTaskLabels,showGrid:X.gridVisible,fpsLimit:X.fpsLimit}):o.jsxs(Ce.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:n,id:"selection-box"})]},Se)}),je&&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(NW,{isOpen:be,onToggle:Ts,onShowTerminal:hs,onOpenSidebar:Mn,onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:b.open,onOpenSnapshots:S.open,onTakeSnapshot:T.open,canTakeSnapshot:zi,mobileView:Fe}),pe&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>Re(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${$e?"is-collapsed":""} ${Ie?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)Re(!pe);else{const Je=!$e;ye(Je),localStorage.setItem("tide-commander-sidebar-collapsed",String(Je))}},title:$e?"Open sidebar":"Close sidebar",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:Ie?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:$e?"15 18 9 12 15 6":"9 18 15 12 9 6"})})}),o.jsxs("aside",{className:`sidebar ${pe?"sidebar-open":""} ${$e?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>Re(!1),title:"Close sidebar",children:"✕"}),nn.length>0?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:yu,children:o.jsx(_S,{onFocusAgent:Fn,onKillAgent:Ls,onCallSubordinates:Is,onOpenAreaExplorer:wn})})}),o.jsx("div",{className:"sidebar-section tool-history-section",children:o.jsx(x.Profiler,{id:"ToolHistory",onRender:yu,children:o.jsx(T4,{agentIds:nn})})})]}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:yu,children:o.jsx(_S,{onFocusAgent:Fn,onKillAgent:Ls,onCallSubordinates:Is,onOpenAreaExplorer:wn})})})]}),o.jsx(x.Profiler,{id:"GuakeOutputPanel",onRender:yu,children:o.jsx(nW,{onSaveSnapshot:T.open})})]}),o.jsx(TW,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:b.open,onOpenSnapshots:S.open,isGeneratingReport:xt,pip:_}),o.jsx(pW,{activeTool:bt,onExit:Ma}),q&&(()=>{const Ne=U.getState().agents.get(q.agentId);return Ne?o.jsx(gW,{agent:Ne,screenPos:q.screenPos,onClose:()=>xe(null)}):null})(),Ae&&(()=>{const Ne=Ft.get(Ae.buildingId);if(!Ne)return null;const Je=()=>et(null);return Ne.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(wW,{building:Ne,screenPos:Ae.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ae.buildingId)},onOpenLogsModal:()=>{Je(),re(Ae.buildingId)},onOpenUrlInModal:Ps})]}):Ne.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(kW,{building:Ne,screenPos:Ae.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ae.buildingId)},onOpenDatabasePanel:()=>{Je(),Te(Ae.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(xW,{building:Ne,screenPos:Ae.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ae.buildingId)},onOpenLogsModal:()=>{me(Ae.buildingId)},onOpenUrlInModal:Ps})]})})(),ce&&(()=>{var Je;const Ne=Ft.get(ce);return Ne?(Je=Ne.docker)!=null&&Je.enabled?o.jsx(cq,{building:Ne,isOpen:!0,onClose:()=>me(null)}):o.jsx(lq,{building:Ne,isOpen:!0,onClose:()=>me(null)}):null})(),ee&&(()=>{const Ne=Ft.get(ee);return Ne?o.jsx(uq,{building:Ne,isOpen:!0,onClose:()=>re(null)}):null})(),Pe&&(()=>{const Ne=Ft.get(Pe);return Ne?o.jsx("div",{className:"modal-overlay visible",onMouseDown:it,onClick:he,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(oq,{building:Ne,onClose:qe})})}):null})(),We&&(()=>{var Je;const Ne=Ft.get(We);return!Ne||!((Je=Ne.terminalStatus)!=null&&Je.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:ie,onClick:de,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 - ",Ne.name]}),o.jsx("button",{className:"terminal-modal-close",onClick:Be,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(Ax,{terminalUrl:Ne.terminalStatus.url,visible:!0})]})})})(),o.jsx(GW,{pip:_,title:"Tide Commander - Agents",children:o.jsx(JW,{})}),o.jsx(pq,{url:M||"",title:M?`Preview - ${M}`:"",isOpen:!!M,onClose:Ua}),T.isOpen&&nn.length===1&&(()=>{const Ne=nn[0],Je=U.getState().agents.get(Ne);if(!Je)return null;const Ct=U.getOutputs(Ne);return o.jsx(hq,{isOpen:T.isOpen,onClose:T.close,agent:Je,outputCount:Ct.length,onSave:async ot=>{try{const jn=Ct.map(Mt=>({type:"message",content:Mt.text,timestamp:new Date(Mt.timestamp).toISOString()}));await U.createSnapshot(ot.agentId,Je.name,ot.title,ot.description,jn,[]),T.close(),rt("success",t("notifications:toast.snapshotSaved"),t("notifications:toast.snapshotSavedMsg"))}catch(jn){const Mt=jn instanceof Error?jn.message:t("notifications:toast.snapshotFailedMsg");rt("error",t("notifications:toast.snapshotFailed"),Mt)}},isSaving:$t,error:En||void 0})})(),o.jsx(fW,{onFocusAgent:Fn,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:Po,onNewAreaClick:Bo}),o.jsx(YW,{spawnModal:s,bossSpawnModal:a,subordinateModal:r,toolboxModal:i,commanderModal:c,deleteConfirmModal:d,supervisorModal:f,spotlightModal:h,controlsModal:m,skillsModal:b,integrationsModal:y,monitoringModal:w,workflowEditorModal:C,triggerManagerModal:N,buildingModal:k,buildingInitialPosition:H,agentEditModal:j,snapshotsModal:S,restoreArchivedModal:D,explorerModal:E,contextMenu:O,spawnPosition:L,spawnAreaId:G,explorerFolderPath:I,contextMenuActions:Bs,sceneConfig:X,onConfigChange:Qn,onToolChange:Ss,onOpenAreaExplorer:wn,onDeleteSelectedAgents:Bi,pendingBuildingDelete:K,onCancelBuildingDelete:()=>ne(null),onConfirmBuildingDelete:Fi,showBackNavModal:ht,onCloseBackNavModal:()=>Gt(!1),onLeave:tn,onOpenPM2LogsModal:Ne=>me(Ne),onOpenBossLogsModal:Ne=>re(Ne),onOpenDatabasePanel:Ne=>Te(Ne),onSyncScene:()=>{var Ne,Je;(Ne=Ye.current)==null||Ne.syncAreas(),(Je=Ye.current)==null||Je.syncAgents(Array.from(U.getState().agents.values()))}})]})}function gq(){return o.jsx(xL,{children:o.jsx(CL,{children:o.jsx(mq,{})})})}class bq extends x.Component{constructor(n){super(n);Xe(this,"handleReload",()=>{window.location.reload()});Xe(this,"handleDismiss",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[Tide] React Error:",n,s),this.setState({errorInfo:s})}render(){if(this.state.hasError){const{error:n,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:"💥"}),On.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:[n==null?void 0:n.name,": ",n==null?void 0:n.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:On.t("errors:crash.stackTrace")}),o.jsx("pre",{style:{color:"#ccc",fontSize:"12px",lineHeight:"1.5",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:n==null?void 0:n.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:On.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:On.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:On.t("common:buttons.tryToContinue")})]}),o.jsx("div",{style:{marginTop:"24px",color:"#666",fontSize:"12px"},children:On.t("errors:crash.checkConsole")})]})})}return this.props.children}}C6();document.addEventListener("wheel",t=>{if(Math.abs(t.deltaX)>Math.abs(t.deltaY)&&Math.abs(t.deltaX)>0){const e=t.target;if(e.tagName==="CANVAS"){t.preventDefault();return}let n=e;for(;n&&n!==document.documentElement;){if(n.scrollWidth>n.clientWidth)return;n=n.parentElement}t.preventDefault()}},{passive:!1});const t_=document.getElementById("app");if(!t_)throw new Error("Could not find #app container");const xq=SM.createRoot(t_);xq.render(o.jsx(Ce.StrictMode,{children:o.jsx(x.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(bq,{children:o.jsx(gq,{})})})}));console.log("[Tide] Tide Commander initialized");export{Df as $,jL as A,l1 as B,WD as C,vL as D,Ex as E,sV as F,Tx as G,ed as H,Hx as I,ur as J,$x as K,ZO as L,dr as M,Lq as N,NL as O,Fa as P,iV as Q,NH as R,pt as S,fs as T,Xq as U,Bt as V,g1 as W,rV as X,w2 as Y,Mu as Z,Rf as _,Yx as a,AN as a$,Wr as a0,Qp as a1,Qq as a2,Kj as a3,yp as a4,Cq as a5,yL as a6,qb as a7,Vq as a8,Ii as a9,i5 as aA,I6 as aB,P6 as aC,$6 as aD,Fq as aE,Qj as aF,$q as aG,Uq as aH,Mx as aI,Dx as aJ,np as aK,oV as aL,vt as aM,jN as aN,aV as aO,NN as aP,TN as aQ,Lu as aR,Fr as aS,zr as aT,H6 as aU,W6 as aV,u1 as aW,Ab as aX,q6 as aY,Do as aZ,ph as a_,Sq as aa,Hq as ab,_y as ac,ia as ad,Pu as ae,Up as af,Ea as ag,pr as ah,Rx as ai,VD as aj,On as ak,zR as al,qD as am,Yq as an,Gq as ao,Kq as ap,qq as aq,r1 as ar,rS as as,Oq as at,Xj as au,Xt as av,$H as aw,TT as ax,sh as ay,HD as az,iL as b,da as b0,DN as b1,u5 as b2,Ry as b3,mx as b4,y4 as b5,n1 as b6,Tq as b7,Iq as b8,_q as b9,Pq as ba,Bq as bb,Rq as bc,Mq as bd,zq as be,Kp as bf,IL as bg,b2 as bh,y2 as bi,Jq as bj,_o as bk,Ju as bl,TL as bm,Zq as bn,nV as bo,eV as bp,Dq as bq,Eq as br,tV as bs,$R as bt,UR as bu,su as bv,Ox as bw,Wq as c,oL as d,Ay as e,Rs as f,TH as g,Ta as h,Kl as i,o as j,yS as k,Na as l,Tn as m,jq as n,Aq as o,Nf as p,Fx as q,x as r,U as s,Nq as t,dt as u,Yb as v,Rt as w,YR as x,GR as y,Ce as z};