tide-commander 1.40.2 → 1.40.3
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.
- package/dist/assets/{BossLogsModal-CaDrNfm1.js → BossLogsModal-5ehRTeGs.js} +1 -1
- package/dist/assets/{BossSpawnModal-DLJInoVf.js → BossSpawnModal-DibwTCub.js} +1 -1
- package/dist/assets/{ControlsModal-Cnnhwfr_.js → ControlsModal-Bd5SZVzZ.js} +1 -1
- package/dist/assets/{DockerLogsModal-D4CbWK3-.js → DockerLogsModal-DWzJq-fY.js} +1 -1
- package/dist/assets/{EmbeddedEditor-36YBGNE2.js → EmbeddedEditor-D0Yo-o66.js} +1 -1
- package/dist/assets/{GmailOAuthSetup-DI5j7wkF.js → GmailOAuthSetup-CdX36hAm.js} +1 -1
- package/dist/assets/{GoogleOAuthSetup-Bsj02mND.js → GoogleOAuthSetup-B3zA-0E7.js} +1 -1
- package/dist/assets/{IframeModal-BJ4oeDBn.js → IframeModal-Cz8quXPm.js} +1 -1
- package/dist/assets/{IntegrationsPanel-DLmIJEUy.js → IntegrationsPanel-C1ktSqvl.js} +2 -2
- package/dist/assets/{LogViewerModal-D7CXMmZf.js → LogViewerModal-De8tLix0.js} +1 -1
- package/dist/assets/{MonitoringModal-PnEKvezF.js → MonitoringModal-DOaMyrjA.js} +1 -1
- package/dist/assets/{PM2LogsModal-EB_Au0iK.js → PM2LogsModal-D-Gq8l2H.js} +1 -1
- package/dist/assets/{RestoreArchivedAreaModal-C-X90Qxe.js → RestoreArchivedAreaModal-COSiM8Fi.js} +1 -1
- package/dist/assets/{SaveSnapshotModal-D6XAjL2T.js → SaveSnapshotModal-DxwK-i0L.js} +1 -1
- package/dist/assets/{Scene2DCanvas-DlVguRVM.js → Scene2DCanvas-4ByVcSoi.js} +1 -1
- package/dist/assets/{SceneManager-OOaJ_z8v.js → SceneManager-7WDKGyPC.js} +1 -1
- package/dist/assets/{SkillsPanel-D5wo2MHh.js → SkillsPanel-1Msh9dAe.js} +1 -1
- package/dist/assets/{SnapshotManager-BLjpctX_.js → SnapshotManager-DQ6jkxDW.js} +1 -1
- package/dist/assets/{SpawnModal-DQ4uUm1y.js → SpawnModal-CHALHOLz.js} +1 -1
- package/dist/assets/{SubordinateAssignmentModal-BDUDt6WC.js → SubordinateAssignmentModal-DBZsFe-S.js} +1 -1
- package/dist/assets/{SupervisorPanel-BZaBI9BA.js → SupervisorPanel-NYoLg7_B.js} +1 -1
- package/dist/assets/{TriggerManagerPanel-DuBiclsE.js → TriggerManagerPanel-CNhhmDvm.js} +1 -1
- package/dist/assets/{WorkflowEditorPanel-D49yDqth.js → WorkflowEditorPanel-BMpT0GGS.js} +1 -1
- package/dist/assets/{index-mQmnkGdF.js → index-BvYoT0dH.js} +1 -1
- package/dist/assets/{index-BxbFh16W.js → index-BzYz2FJi.js} +2 -2
- package/dist/assets/{index-BiGvhrCO.js → index-CDKrcnoB.js} +1 -1
- package/dist/assets/{index-BSl18-4e.js → index-CEZ1e3Of.js} +1 -1
- package/dist/assets/{index-DZ3f9mNd.js → index-CSOx3Jk0.js} +1 -1
- package/dist/assets/{index-Bxjd0N-j.js → index-CTINc_P-.js} +1 -1
- package/dist/assets/{index-DJdXbeWz.js → index-CqZxf78s.js} +3 -3
- package/dist/assets/{index-BwkNteiZ.js → index-DAOIgllP.js} +1 -1
- package/dist/assets/{main-DULfVodw.js → main-DSF4XPLl.js} +4 -4
- package/dist/assets/{web-DAqM9uoZ.js → web-2Scyvbzn.js} +1 -1
- package/dist/assets/{web-DQ10iSod.js → web-DXju9dHs.js} +1 -1
- package/dist/index.html +1 -1
- package/dist/src/packages/server/cli.js +17 -1
- package/dist/src/packages/server/data/builtin-skills/boss-instructions.js +2 -2
- package/dist/src/packages/server/websocket/handlers/boss-response-handler.js +5 -1
- 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-
|
|
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-BzYz2FJi.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-Chj50gSY.js","assets/web-2Scyvbzn.js","assets/SceneManager-7WDKGyPC.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-CHALHOLz.js","assets/BossSpawnModal-DibwTCub.js","assets/SubordinateAssignmentModal-DBZsFe-S.js","assets/index-CEZ1e3Of.js","assets/index-Bykeknjl.css","assets/index-BvYoT0dH.js","assets/index-DAOIgllP.js","assets/index-CqZxf78s.js","assets/SupervisorPanel-NYoLg7_B.js","assets/index-CTINc_P-.js","assets/ControlsModal-Bd5SZVzZ.js","assets/SkillsPanel-1Msh9dAe.js","assets/SnapshotManager-DQ6jkxDW.js","assets/RestoreArchivedAreaModal-COSiM8Fi.js","assets/IntegrationsPanel-C1ktSqvl.js","assets/MonitoringModal-DOaMyrjA.js","assets/WorkflowEditorPanel-BMpT0GGS.js","assets/TriggerManagerPanel-CNhhmDvm.js","assets/index-CSOx3Jk0.js","assets/index-CprCD9du.css","assets/PM2LogsModal-D-Gq8l2H.js","assets/LogViewerModal-De8tLix0.js","assets/DockerLogsModal-DWzJq-fY.js","assets/BossLogsModal-5ehRTeGs.js","assets/Scene2DCanvas-4ByVcSoi.js","assets/Scene2DCanvas-DwXbvB-b.css","assets/index-CDKrcnoB.js","assets/index-BZyCMBzi.css","assets/IframeModal-Cz8quXPm.js","assets/IframeModal-DJkCGwT6.css","assets/SaveSnapshotModal-DxwK-i0L.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var _E=Object.defineProperty;var EE=(t,e,n)=>e in t?_E(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Xe=(t,e,n)=>EE(t,typeof e!="symbol"?e+"":e,n);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as Nx,g as Xu,a as tj,c as Z0}from"./vendor-react--Eh9ivFN.js";import{T as ME,a as Lb,b as nj,L as sj,c as Cu,F as up,M as cr,V as aj,C as Hr,d as lr,S as Br,e as DE,P as RE,D as Ib,f as dp,g as wo,I as OE,Q as rj,h as LE,O as ij,i as IE,j as PE,B as Au,k as BE,l as oj,N as FE,m as zE,n as $E,o as Pb,p as lj,R as Bb,q as UE,r as HE,s as WE,t as Jf,u as qE,v as Tx,w as cj,x as Fl,y as VE,z as uj,A as YE,E as Il,G as GE,H as KE,J as QE,K as XE,U as xg,W as dj,X as JE,Y as ZE,Z as eM,_ as tM,$ as nM,a0 as sM,a1 as fj,a2 as aM,a3 as ek,a4 as tk,a5 as nk,a6 as sk,a7 as Fb,a8 as rM,a9 as iM,aa as oM,ab as lM,ac as cM,ad as uM,ae as dM,af as fM,ag as pM,ah as hM,ai as mM,aj as gM}from"./vendor-three-Chj50gSY.js";function bM(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 Ck;function aD(){if(Ck)return Ng;Ck=1;var t=Nx();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 Ak;function rD(){return Ak||(Ak=1,jg.exports=aD()),jg.exports}var iD=rD();const oD=(t,e)=>{if(No(e))return e;if(VM(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},lD={t:oD,ready:!1},cD=()=>()=>{},dt=(t,e={})=>{var _,M,R;const{i18n:n}=e,{i18n:s,defaultNS:a}=x.useContext(nD)||{},r=n||s||eD();r&&!r.reportNamespaces&&(r.reportNamespaces=new sD),r||$b(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=x.useMemo(()=>{var z;return{...JM(),...(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 cD;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 lD;const z=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(V=>qM(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}=iD.useSyncExternalStore(y,C,C);x.useEffect(()=>{if(r&&!S&&!c){const z=()=>k($=>$+1);e.lng?Sk(r,e.lng,m,z):Ub(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)=>($b(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?Sk(r,e.lng,m,$):Ub(r,m,$)});return O};function Wb(t){"@babel/helpers - typeof";return Wb=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},Wb(t)}function yj(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":Wb(XMLHttpRequest))==="object"}function uD(t){return!!t&&typeof t.then=="function"}function dD(t){return uD(t)?t:Promise.resolve(t)}var fD=/\{\{(.+?)\}\}/g;function jk(t,e){return t.replace(fD,function(n,s){var a=e[s.trim()];return a??n})}const pD="modulepreload",hD=function(t){return"/"+t},Nk={},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=hD(f),f in Nk)return;Nk[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":pD,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 Tk(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 _k(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Tk(Object(n),!0).forEach(function(s){mD(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Tk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function mD(t,e,n){return(e=gD(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function gD(t){var e=bD(t,"string");return To(e)=="symbol"?e:e+""}function bD(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;yj()&&(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 qb=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},Ek=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)},Mk=!1,xD=function(e,n,s,a){e.queryStringParams&&(n=qb(n,e.queryStringParams));var r=_k({},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=_k({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},Mk?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{Ek(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]}),Ek(n,c,a,d),Mk=!0}catch(h){a(h)}}},yD=function(e,n,s,a){s&&To(s)==="object"&&(s=qb("",s).slice(1)),e.queryStringParams&&(n=qb(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)}},vD=function(e,n,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Di&&n.indexOf("file:")!==0)return xD(e,n,s,a);if(yj()||typeof ActiveXObject=="function")return yD(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 Dk(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?Dk(Object(n),!0).forEach(function(s){vj(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Dk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function wD(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function kD(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,wj(s.key),s)}}function SD(t,e,n){return e&&kD(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function vj(t,e,n){return(e=wj(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function wj(t){var e=CD(t,"string");return Vl(e)=="symbol"?e:e+""}function CD(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 AD=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 vj({},s,a||"")},parseLoadPayload:function(n,s){},request:vD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},kj=(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]:{};wD(this,t),this.services=e,this.options=n,this.allOptions=s,this.type="backend",this.init(e,n,s)}return SD(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({},AD()),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=dD(d),d.then(function(f){if(!f)return i(null,{});var h=jk(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=jk(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)})})})}}}])})();kj.type="backend";const{slice:jD,forEach:ND}=[];function TD(t){return ND.call(jD.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function _D(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 Rk=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,ED=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(!Rk.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!Rk.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},Ok={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=ED(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 MD={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return Ok.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;n&&typeof document<"u"&&Ok.create(n,t,s,a,r)}},DD={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}},RD={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 Lk=()=>{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 OD={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&Lk())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&Lk()&&window.localStorage.setItem(n,t)}};let Tl=null;const Ik=()=>{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 LD={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&Ik())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&Ik()&&window.sessionStorage.setItem(n,t)}},ID={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}},PD={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}},BD={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}},FD={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 Sj=!1;try{document.cookie,Sj=!0}catch{}const Cj=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Sj||Cj.splice(1,1);const zD=()=>({order:Cj,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class Aj{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=TD(n,this.options||{},zD()),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(MD),this.addDetector(DD),this.addDetector(OD),this.addDetector(LD),this.addDetector(ID),this.addDetector(PD),this.addDetector(BD),this.addDetector(FD),this.addDetector(RD)}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&&!_D(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)}))}}Aj.type="languageDetector";const gp={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},Vb={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},$D={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},Cq=["#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 _x(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 Ex(t){return gp[t]??gp.default}let Zf=null;function jj(){if(!Zf)try{Zf=globalThis.__i18n}catch{}return Zf}function UD(t){Zf=t}function HD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function WD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function qD(t){var a;const e=jj(),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 Mx(t){var f;const e=jj(),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(kj).use(Aj).use(tD).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(()=>{UD(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"},Yb="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 Dx(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 Rx(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Pk(t){try{localStorage.removeItem(t)}catch(e){console.error(`Failed to remove from localStorage: ${t}`,e)}}function Ea(){const t=Ox();return t?t.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ii(){return Fa(pt.AUTH_TOKEN,"")}function Ox(){return Fa(pt.BACKEND_URL,"")}function VD(t){const e=t.trim();Wr(pt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Yb,{detail:e}))}function YD(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(Yb,e),window.addEventListener("storage",n),()=>{window.removeEventListener(Yb,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 Gb(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 GD(){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 KD(){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=[],QD=new Set;function bp(){QD.forEach(t=>t())}function XD(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 JD(t){const e=ca.findIndex(n=>n.id===t);return e===-1?!1:e<ca.length-1}function ZD(...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?XD(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,Bk=!1;async function eR(){if(Bk)return _u;Bk=!0;try{const t=await vt(()=>import("./index-BxbFh16W.js"),__vite__mapDeps([2,3,1,4]));_u={Haptics:t.Haptics,ImpactStyle:t.ImpactStyle}}catch{}return _u}eR();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 Fk(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 zk=8,tR=.93,$k=.4;function nR(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(_)<$k){_=0;return}N.scrollTop+=_,_*=tR,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,se=R-K;R=K,w(se);return}if(f.current&&V.touches.length===1){V.preventDefault();const K=V.touches[0].clientY,se=R-K;R=K,w(se);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),se=Math.abs(B-D);if(K<zk&&se<zk)return;if(se>=K)S=!0,j=!1,V.preventDefault();else{j=!1;return}}if(S){V.preventDefault();const K=performance.now(),se=K-O;N.scrollTop=E+(D-B),se>0&&(_=(I-B)/se*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(_)>$k&&(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 sR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function aR(){return"documentPictureInPicture"in window}function rR(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 iR(){const[t,e]=x.useState(!1),[n,s]=x.useState(null),[a,r]=x.useState(null),i=x.useRef(null),c=aR(),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={...sR,...m};try{const w=await window.documentPictureInPicture.requestWindow({width:b.width,height:b.height,disallowReturnToOpener:!0});i.current=w,b.copyStyleSheets&&rR(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 oR{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 oR,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 lR=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"},cR=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},s=n.Plugins=n.Plugins||{},a=()=>e!==null?e.name:lR(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},uR=t=>t.Capacitor=cR(t),yp=uR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Ju=yp.registerPlugin;class Lx{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 Uk=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Hk=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class dR extends Lx{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=Hk(a).trim(),r=Hk(r).trim(),n[a]=r}),n}async setCookie(e){try{const n=Uk(e.key),s=Uk(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 dR});const fR=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)}),pR=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=t[e[i]],a),{})},hR=(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,mR=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),a=pR(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 gR extends Lx{async request(e){const n=mR(e,e.webFetchExtra),s=hR(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 fR(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 Aq=Ju("CapacitorHttp",{web:()=>new gR});var Wk;(function(t){t.Dark="DARK",t.Light="LIGHT",t.Default="DEFAULT"})(Wk||(Wk={}));var qk;(function(t){t.StatusBar="StatusBar",t.NavigationBar="NavigationBar"})(qk||(qk={}));class bR extends Lx{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 bR});var Vk;(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"})(Vk||(Vk={}));const Ix=Ju("LocalNotifications",{web:()=>vt(()=>import("./web-DAqM9uoZ.js"),__vite__mapDeps([5,3,1,4])).then(t=>new t.LocalNotificationsWeb)}),xR=Ju("ServerConfig");let yR=100;const vR="agent_alerts",Kb="tide-notification-tap";function wR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function Nj(t){if(wR()){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 kR(){if(Zu())try{const t=await Ix.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 SR(t){const{title:e,body:n,icon:s,data:a}=t;if(Zu())try{const r=yR++;console.log("[Notifications] Scheduling native notification id="+r,e),await Ix.schedule({notifications:[{id:r,title:e,body:n,extra:a,channelId:vR,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(Kb,{detail:a}))}}}let Mg=!1;async function CR(t){const e=[];if(Mg)return()=>{};if(Mg=!0,t){const n=s=>{const a=s;a.detail&&t(a.detail)};window.addEventListener(Kb,n),e.push(()=>window.removeEventListener(Kb,n))}if(Zu())try{const n=await Ix.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 AR(t,e){Zu()&&xR.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,Yk=t=>{window.__tideWsState.ws=t},jR=()=>window.__tideWsState.isConnecting,nu=t=>{window.__tideWsState.isConnecting=t},Qb=()=>window.__tideWsState.reconnectAttempts,Xb=t=>{window.__tideWsState.reconnectAttempts=t},Tj=()=>window.__tideWsState.reconnectTimeout,_j=t=>{window.__tideWsState.reconnectTimeout=t},Gk=10,Px="tide_ws_has_connected";function Kk(){return sessionStorage.getItem(Px)==="true"}function NR(t){sessionStorage.setItem(Px,"true")}function TR(){sessionStorage.removeItem(Px)}let Ej=null;const _R=t=>{Ej=t},Qk=()=>Ej,Re={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 Mj(t){t.onToast&&(Re.onToast=t.onToast),t.onAgentCreated&&(Re.onAgentCreated=t.onAgentCreated),t.onAgentUpdated&&(Re.onAgentUpdated=t.onAgentUpdated),t.onAgentDeleted&&(Re.onAgentDeleted=t.onAgentDeleted),t.onAgentsSync&&(Re.onAgentsSync=t.onAgentsSync),t.onAreasSync&&(Re.onAreasSync=t.onAreasSync),t.onSpawnError&&(Re.onSpawnError=t.onSpawnError),t.onSpawnSuccess&&(Re.onSpawnSuccess=t.onSpawnSuccess),t.onToolUse&&(Re.onToolUse=t.onToolUse),t.onDirectoryNotFound&&(Re.onDirectoryNotFound=t.onDirectoryNotFound),t.onDelegation&&(Re.onDelegation=t.onDelegation),t.onCustomClassesSync&&(Re.onCustomClassesSync=t.onCustomClassesSync),t.onReconnect&&(Re.onReconnect=t.onReconnect),t.onAgentNotification&&(Re.onAgentNotification=t.onAgentNotification),t.onBuildingUpdated&&(Re.onBuildingUpdated=t.onBuildingUpdated),t.onSubagentStarted&&(Re.onSubagentStarted=t.onSubagentStarted),t.onSubagentCompleted&&(Re.onSubagentCompleted=t.onSubagentCompleted)}function ER(){Re.onToast=null,Re.onAgentCreated=null,Re.onAgentUpdated=null,Re.onAgentDeleted=null,Re.onAgentsSync=null,Re.onAreasSync=null,Re.onSpawnError=null,Re.onSpawnSuccess=null,Re.onToolUse=null,Re.onDirectoryNotFound=null,Re.onDelegation=null,Re.onCustomClassesSync=null,Re.onReconnect=null,Re.onAgentNotification=null,Re.onSubagentStarted=null,Re.onSubagentCompleted=null}function MR(){Re.onAgentCreated=null,Re.onAgentUpdated=null,Re.onAgentDeleted=null,Re.onAgentsSync=null,Re.onAreasSync=null,Re.onToolUse=null,Re.onDelegation=null,Re.onCustomClassesSync=null,Re.onBuildingUpdated=null,Re.onSubagentStarted=null,Re.onSubagentCompleted=null}const jf=new Map,DR=new Map,Jb={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(),DR.clear()},report(){}};class RR{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 RR;class OR{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 OR;function yu(t,e,n,s,a,r){}function Dj(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 Zb=pt.PENDING_MESSAGES,LR=300*1e3;function Rj(){try{const t=localStorage.getItem(Zb);if(!t)return[];const e=JSON.parse(t),n=Date.now();return e.filter(s=>n-s.queuedAt<LR)}catch{return[]}}function Oj(t){try{t.length===0?localStorage.removeItem(Zb):localStorage.setItem(Zb,JSON.stringify(t))}catch{}}function Tf(t){const e=Rj();e.push({message:t,queuedAt:Date.now()}),Oj(e)}function IR(){var s;const t=Rj();if(t.length===0)return 0;let e=0;const n=[];for(const a of t)PR(a.message)?e++:n.push(a);if(Oj(n),e>0){const a=e===1?"queued message":"queued messages";(s=Re.onToast)==null||s.call(Re,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function Bx(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 PR(t){const e=Yp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const n=JSON.stringify(t),s=Bx(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 Fx(t){var n,s,a,r,i,c,d,f,h,m;const e=Yp();if(!e)return(n=Qk())==null||n(),t.type==="send_command"?(Tf(t),(s=Re.onToast)==null||s.call(Re,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=Re.onToast)==null||a.call(Re,"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=Re.onToast)==null||r.call(Re,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=Re.onToast)==null||i.call(Re,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Qk())==null||c(),t.type==="send_command"?(Tf(t),(d=Re.onToast)==null||d.call(Re,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=Re.onToast)==null||f.call(Re,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const b=JSON.stringify(t),y=Bx(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=Re.onToast)==null||h.call(Re,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=Re.onToast)==null||m.call(Re,"error","Send Failed",`Failed to send message: ${b}`),!1}}const vu=new Set,BR=5e3;function Xk(t){if(!t.isDetached||!t.sessionId){vu.delete(t.id);return}vu.has(t.id)||(vu.add(t.id),Fx({type:"reattach_agent",payload:{agentId:t.id}}),setTimeout(()=>{vu.delete(t.id)},BR))}function FR(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(Jb.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=Re.onAgentsSync)==null||e.call(Re,_),U.loadToolHistory();for(const R of _)Xk(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=Re.onAgentCreated)==null||s.call(Re,_),(a=Re.onSpawnSuccess)==null||a.call(Re),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=Re.onToast)==null||r.call(Re,"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(_),Xk(_),(i=Re.onAgentUpdated)==null||i.call(Re,_,$);break}case"agent_deleted":{const{id:_}=t.payload;vu.delete(_),U.removeAgent(_),(c=Re.onAgentDeleted)==null||c.call(Re,_);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=Re.onToolUse)==null||d.call(Re,_.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=Re.onToast)==null||f.call(Re,"error","Error",_.message),(h=Re.onSpawnError)==null||h.call(Re),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=Re.onDirectoryNotFound)==null||m.call(Re,_),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=Re.onAreasSync)==null||b.call(Re);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=Re.onBuildingUpdated)==null||y.call(Re,_);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=Re.onToast)==null||w.call(Re,"info","Task Delegated",`Delegated to ${_.selectedAgentName}: ${_.reasoning.slice(0,80)}...`),_.bossId&&_.selectedAgentId&&((C=Re.onDelegation)==null||C.call(Re,_.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=Re.onAgentCreated)==null||N.call(Re,_),Fx({type:"move_agent",payload:{agentId:_.id,position:M}}),(k=Re.onToast)==null||k.call(Re,"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=Re.onCustomClassesSync)==null||j.call(Re,M);break}case"custom_agent_class_created":{const _=t.payload;U.addCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class created: ${_.name}`),(S=Re.onCustomClassesSync)==null||S.call(Re,U.getState().customAgentClasses);break}case"custom_agent_class_updated":{const _=t.payload;U.updateCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class updated: ${_.name}`),(T=Re.onCustomClassesSync)==null||T.call(Re,U.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:_}=t.payload;U.removeCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class deleted: ${_}`),(D=Re.onCustomClassesSync)==null||D.call(Re,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=Re.onAgentNotification)==null||E.call(Re,_);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=Re.onSubagentStarted)==null||I.call(Re,_);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=Re.onSubagentCompleted)==null||O.call(Re,_);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}}Jb.end(`ws:${t.type}`)}_R(()=>Hu());let Jk=!1;function Lj(){const t=Yp();t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Page unloading");const e=Tj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),TR()}function zR(){Jk||(window.addEventListener("beforeunload",Lj),Jk=!0)}function Ij(){Lj(),U.setConnected(!1),U.stopStatusPolling()}function $R(){Ij(),Xb(0),setTimeout(()=>Hu(),100)}function Hu(){zR();const t=Tj();t&&(clearTimeout(t),_j(null));const e=Yp();if(jR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Kk()&&Re.onReconnect&&Re.onReconnect();return}Xb(Qb()+1),nu(!0);const n=Ox(),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),Zk();return}Yk(i),i.onopen=()=>{var d,f,h;const c=Kk();nu(!1),Xb(0),NR(),U.setConnected(!0),U.startStatusPolling(),U.clearAllPermissions(),c?((d=Re.onToast)==null||d.call(Re,"success","Reconnected","Connection restored - refreshing data..."),(f=Re.onReconnect)==null||f.call(Re)):(h=Re.onToast)==null||h.call(Re,"success","Connected","Connected to Tide Commander server"),AR(n,s),IR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=Bx(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&vs.captureReceived(f,c.data),FR(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),Yk(null),U.setConnected(!1),U.stopStatusPolling();const c=Qb();c<Gk?((d=Re.onToast)==null||d.call(Re,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${Gk})`),Zk()):(f=Re.onToast)==null||f.call(Re,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{nu(!1)},U.setSendMessage(Fx)}function Zk(){const t=Qb(),e=Math.min(1e3*Math.pow(2,t-1),3e4);_j(setTimeout(Hu,e))}function UR(t,e){const n={position:t,target:e};La(pt.CAMERA_STATE,n)}function HR(){return Na(pt.CAMERA_STATE,null)}function jq(t,e,n){const s={posX:t,posZ:e,zoom:n};La(pt.CAMERA_STATE_2D,s)}function Nq(){return Na(pt.CAMERA_STATE_2D,null)}function sc(){return{Authorization:`Bearer ${Ii()}`,"Content-Type":"application/json"}}async function WR(){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 qR(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 eS(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 VR(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 YR(){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 tS(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=[],Pj=!1;const ex=new Set;function Dg(t){Pj=t,ex.forEach(e=>e(t))}const Bj="tide-commander-active-workspace";function nS(){return typeof window>"u"?null:localStorage.getItem(Bj)||null}function Rg(t){typeof window>"u"||localStorage.setItem(Bj,t||"")}function au(){Wu.forEach(t=>t())}function GR(){return sr}function zx(t){return sr?t?sr.areaIds.includes(t):!1:!0}function Tq(t){return sr?sr.areaIds.includes(t):!0}function Fj(){const[,t]=x.useState(0);return x.useEffect(()=>{const e=()=>t(n=>n+1);return Wu.add(e),()=>{Wu.delete(e)}},[]),[sr,xo]}function KR(t){return Wu.add(t),()=>{Wu.delete(t)}}function QR(){const[t,e]=x.useState(Pj);return x.useEffect(()=>{const n=s=>e(s);return ex.add(n),()=>{ex.delete(n)}},[]),t}const Og=new Map,XR=Se.memo(function(){const{t:e}=dt("common"),n=ur(),[s,a]=x.useState([]),[r,i]=x.useState(()=>nS()),[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=nS(),[H,V]=await Promise.all([WR(),YR()]);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=HR();B&&(Og.set(r,B),eS(r,{cameraState:B}).then(K=>{a(se=>{const q=se.map(be=>be.id===r?K:be);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&&(UR(K.position,K.target),Og.set(L,K))}tS(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 qR(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 eS(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 VR(L);const F=s.filter(H=>H.id!==L);a(F),xo=F,r===L&&(i(null),Rg(null),sr=null,await tS(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 zj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function JR(){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 $j(t){typeof window<"u"&&(window.__tideWsConnected=t)}function ZR(t){typeof window<"u"&&(window.__tideIsPageUnloading=t)}function eO(){sessionStorage.setItem(vp,"true")}function _f(t){ZR(!0),sessionStorage.removeItem(vp),Ij(),ER(),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),$j(!1);const n=document.getElementById("battlefield");n&&n.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function tO(){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=zj();n&&n!==s&&n.remove(),sessionStorage.removeItem(vp)}function nO(){typeof window>"u"||(tO(),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})`)}))}nO();const sS={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},aS={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},rS={idleAnimation:"sit",workingAnimation:"sprint"},sO=0;function Uj(){const t={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:sS,modelStyle:aS,animations:rS,fpsLimit:sO},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:{...sS,...e.terrain},modelStyle:{...aS,...e.modelStyle},animations:{...rS,...e.animations},fpsLimit:e.fpsLimit??t.fpsLimit}}return t}function aO(t){La(pt.CONFIG,t)}function rO(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function Hj(){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=Hj);function iO({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=zj()===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 se=U.getState().buildings.get(G);((se==null?void 0:se.type)==="server"||(se==null?void 0:se.type)==="boss"||(se==null?void 0:se.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),eO();try{const{SceneManager:W}=await vt(async()=>{const{SceneManager:H}=await import("./SceneManager-OOaJ_z8v.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=Uj();L.setCharacterScale(F.characterScale),L.setScale3D(F.scale3d),L.setTimeMode(F.timeMode),L.setTerrainConfig(F.terrain),L.setFloorStyle(F.terrain.floorStyle,!0),L.setGridVisible(F.gridVisible),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 $())}Mj({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=KR(()=>{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"&&rO()&&N.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),MR(),N.current.dispose(),N.current=null,qu(null),Eu(null))}},[n,s]),N}function oO({showToast:t,showAgentNotification:e}){x.useEffect(()=>{Mj({onToast:t,onReconnect:()=>{U.triggerReconnect()},onAgentNotification:a=>{e(a)}}),JR()||(Hu(),$j(!0)),kR();let n;CR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&Nj(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 lO(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 cO(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 uO(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 dO(t,e){x.useEffect(()=>{var n;(n=t.current)==null||n.highlightArea(e)},[t,e])}function fO(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 _q(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 Eq(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 pO({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 hO(){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 mO(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 gO=3e4;function bO(){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,gO),()=>{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:""},iS=90,Bg=["simple","chat","advanced"],oS=55,lS=20,cS=95,xO=200,yO=12e4,vO=5,la=new Map;function wO(t){const e=la.get(t);e&&(la.delete(t),la.set(t,e))}function kO(){for(;la.size>vO;){const t=la.keys().next().value;if(t!==void 0)la.delete(t);else break}}function Wj(t){la.delete(t)}function SO(t){return t.trim().replace(/\r\n/g,`
|
|
42
|
+
*/var Ck;function aD(){if(Ck)return Ng;Ck=1;var t=Nx();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 Ak;function rD(){return Ak||(Ak=1,jg.exports=aD()),jg.exports}var iD=rD();const oD=(t,e)=>{if(No(e))return e;if(VM(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},lD={t:oD,ready:!1},cD=()=>()=>{},dt=(t,e={})=>{var _,M,R;const{i18n:n}=e,{i18n:s,defaultNS:a}=x.useContext(nD)||{},r=n||s||eD();r&&!r.reportNamespaces&&(r.reportNamespaces=new sD),r||$b(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=x.useMemo(()=>{var z;return{...JM(),...(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 cD;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 lD;const z=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(V=>qM(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}=iD.useSyncExternalStore(y,C,C);x.useEffect(()=>{if(r&&!S&&!c){const z=()=>k($=>$+1);e.lng?Sk(r,e.lng,m,z):Ub(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)=>($b(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?Sk(r,e.lng,m,$):Ub(r,m,$)});return O};function Wb(t){"@babel/helpers - typeof";return Wb=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},Wb(t)}function yj(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":Wb(XMLHttpRequest))==="object"}function uD(t){return!!t&&typeof t.then=="function"}function dD(t){return uD(t)?t:Promise.resolve(t)}var fD=/\{\{(.+?)\}\}/g;function jk(t,e){return t.replace(fD,function(n,s){var a=e[s.trim()];return a??n})}const pD="modulepreload",hD=function(t){return"/"+t},Nk={},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=hD(f),f in Nk)return;Nk[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":pD,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 Tk(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 _k(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Tk(Object(n),!0).forEach(function(s){mD(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Tk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function mD(t,e,n){return(e=gD(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function gD(t){var e=bD(t,"string");return To(e)=="symbol"?e:e+""}function bD(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;yj()&&(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 qb=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},Ek=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)},Mk=!1,xD=function(e,n,s,a){e.queryStringParams&&(n=qb(n,e.queryStringParams));var r=_k({},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=_k({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},Mk?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{Ek(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]}),Ek(n,c,a,d),Mk=!0}catch(h){a(h)}}},yD=function(e,n,s,a){s&&To(s)==="object"&&(s=qb("",s).slice(1)),e.queryStringParams&&(n=qb(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)}},vD=function(e,n,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Di&&n.indexOf("file:")!==0)return xD(e,n,s,a);if(yj()||typeof ActiveXObject=="function")return yD(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 Dk(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?Dk(Object(n),!0).forEach(function(s){vj(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Dk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function wD(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function kD(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,wj(s.key),s)}}function SD(t,e,n){return e&&kD(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function vj(t,e,n){return(e=wj(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function wj(t){var e=CD(t,"string");return Vl(e)=="symbol"?e:e+""}function CD(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 AD=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 vj({},s,a||"")},parseLoadPayload:function(n,s){},request:vD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},kj=(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]:{};wD(this,t),this.services=e,this.options=n,this.allOptions=s,this.type="backend",this.init(e,n,s)}return SD(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({},AD()),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=dD(d),d.then(function(f){if(!f)return i(null,{});var h=jk(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=jk(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)})})})}}}])})();kj.type="backend";const{slice:jD,forEach:ND}=[];function TD(t){return ND.call(jD.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function _D(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 Rk=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,ED=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(!Rk.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!Rk.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},Ok={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=ED(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 MD={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return Ok.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;n&&typeof document<"u"&&Ok.create(n,t,s,a,r)}},DD={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}},RD={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 Lk=()=>{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 OD={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&Lk())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&Lk()&&window.localStorage.setItem(n,t)}};let Tl=null;const Ik=()=>{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 LD={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&Ik())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&Ik()&&window.sessionStorage.setItem(n,t)}},ID={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}},PD={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}},BD={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}},FD={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 Sj=!1;try{document.cookie,Sj=!0}catch{}const Cj=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Sj||Cj.splice(1,1);const zD=()=>({order:Cj,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class Aj{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=TD(n,this.options||{},zD()),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(MD),this.addDetector(DD),this.addDetector(OD),this.addDetector(LD),this.addDetector(ID),this.addDetector(PD),this.addDetector(BD),this.addDetector(FD),this.addDetector(RD)}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&&!_D(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)}))}}Aj.type="languageDetector";const gp={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},Vb={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},$D={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},Cq=["#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 _x(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 Ex(t){return gp[t]??gp.default}let Zf=null;function jj(){if(!Zf)try{Zf=globalThis.__i18n}catch{}return Zf}function UD(t){Zf=t}function HD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function WD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function qD(t){var a;const e=jj(),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 Mx(t){var f;const e=jj(),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(kj).use(Aj).use(tD).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(()=>{UD(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"},Yb="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 Dx(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 Rx(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Pk(t){try{localStorage.removeItem(t)}catch(e){console.error(`Failed to remove from localStorage: ${t}`,e)}}function Ea(){const t=Ox();return t?t.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ii(){return Fa(pt.AUTH_TOKEN,"")}function Ox(){return Fa(pt.BACKEND_URL,"")}function VD(t){const e=t.trim();Wr(pt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Yb,{detail:e}))}function YD(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(Yb,e),window.addEventListener("storage",n),()=>{window.removeEventListener(Yb,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 Gb(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 GD(){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 KD(){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=[],QD=new Set;function bp(){QD.forEach(t=>t())}function XD(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 JD(t){const e=ca.findIndex(n=>n.id===t);return e===-1?!1:e<ca.length-1}function ZD(...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?XD(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,Bk=!1;async function eR(){if(Bk)return _u;Bk=!0;try{const t=await vt(()=>import("./index-BzYz2FJi.js"),__vite__mapDeps([2,3,1,4]));_u={Haptics:t.Haptics,ImpactStyle:t.ImpactStyle}}catch{}return _u}eR();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 Fk(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 zk=8,tR=.93,$k=.4;function nR(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(_)<$k){_=0;return}N.scrollTop+=_,_*=tR,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,se=R-K;R=K,w(se);return}if(f.current&&V.touches.length===1){V.preventDefault();const K=V.touches[0].clientY,se=R-K;R=K,w(se);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),se=Math.abs(B-D);if(K<zk&&se<zk)return;if(se>=K)S=!0,j=!1,V.preventDefault();else{j=!1;return}}if(S){V.preventDefault();const K=performance.now(),se=K-O;N.scrollTop=E+(D-B),se>0&&(_=(I-B)/se*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(_)>$k&&(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 sR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function aR(){return"documentPictureInPicture"in window}function rR(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 iR(){const[t,e]=x.useState(!1),[n,s]=x.useState(null),[a,r]=x.useState(null),i=x.useRef(null),c=aR(),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={...sR,...m};try{const w=await window.documentPictureInPicture.requestWindow({width:b.width,height:b.height,disallowReturnToOpener:!0});i.current=w,b.copyStyleSheets&&rR(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 oR{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 oR,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 lR=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"},cR=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},s=n.Plugins=n.Plugins||{},a=()=>e!==null?e.name:lR(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},uR=t=>t.Capacitor=cR(t),yp=uR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Ju=yp.registerPlugin;class Lx{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 Uk=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Hk=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class dR extends Lx{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=Hk(a).trim(),r=Hk(r).trim(),n[a]=r}),n}async setCookie(e){try{const n=Uk(e.key),s=Uk(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 dR});const fR=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)}),pR=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=t[e[i]],a),{})},hR=(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,mR=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),a=pR(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 gR extends Lx{async request(e){const n=mR(e,e.webFetchExtra),s=hR(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 fR(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 Aq=Ju("CapacitorHttp",{web:()=>new gR});var Wk;(function(t){t.Dark="DARK",t.Light="LIGHT",t.Default="DEFAULT"})(Wk||(Wk={}));var qk;(function(t){t.StatusBar="StatusBar",t.NavigationBar="NavigationBar"})(qk||(qk={}));class bR extends Lx{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 bR});var Vk;(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"})(Vk||(Vk={}));const Ix=Ju("LocalNotifications",{web:()=>vt(()=>import("./web-2Scyvbzn.js"),__vite__mapDeps([5,3,1,4])).then(t=>new t.LocalNotificationsWeb)}),xR=Ju("ServerConfig");let yR=100;const vR="agent_alerts",Kb="tide-notification-tap";function wR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function Nj(t){if(wR()){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 kR(){if(Zu())try{const t=await Ix.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 SR(t){const{title:e,body:n,icon:s,data:a}=t;if(Zu())try{const r=yR++;console.log("[Notifications] Scheduling native notification id="+r,e),await Ix.schedule({notifications:[{id:r,title:e,body:n,extra:a,channelId:vR,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(Kb,{detail:a}))}}}let Mg=!1;async function CR(t){const e=[];if(Mg)return()=>{};if(Mg=!0,t){const n=s=>{const a=s;a.detail&&t(a.detail)};window.addEventListener(Kb,n),e.push(()=>window.removeEventListener(Kb,n))}if(Zu())try{const n=await Ix.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 AR(t,e){Zu()&&xR.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,Yk=t=>{window.__tideWsState.ws=t},jR=()=>window.__tideWsState.isConnecting,nu=t=>{window.__tideWsState.isConnecting=t},Qb=()=>window.__tideWsState.reconnectAttempts,Xb=t=>{window.__tideWsState.reconnectAttempts=t},Tj=()=>window.__tideWsState.reconnectTimeout,_j=t=>{window.__tideWsState.reconnectTimeout=t},Gk=10,Px="tide_ws_has_connected";function Kk(){return sessionStorage.getItem(Px)==="true"}function NR(t){sessionStorage.setItem(Px,"true")}function TR(){sessionStorage.removeItem(Px)}let Ej=null;const _R=t=>{Ej=t},Qk=()=>Ej,Re={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 Mj(t){t.onToast&&(Re.onToast=t.onToast),t.onAgentCreated&&(Re.onAgentCreated=t.onAgentCreated),t.onAgentUpdated&&(Re.onAgentUpdated=t.onAgentUpdated),t.onAgentDeleted&&(Re.onAgentDeleted=t.onAgentDeleted),t.onAgentsSync&&(Re.onAgentsSync=t.onAgentsSync),t.onAreasSync&&(Re.onAreasSync=t.onAreasSync),t.onSpawnError&&(Re.onSpawnError=t.onSpawnError),t.onSpawnSuccess&&(Re.onSpawnSuccess=t.onSpawnSuccess),t.onToolUse&&(Re.onToolUse=t.onToolUse),t.onDirectoryNotFound&&(Re.onDirectoryNotFound=t.onDirectoryNotFound),t.onDelegation&&(Re.onDelegation=t.onDelegation),t.onCustomClassesSync&&(Re.onCustomClassesSync=t.onCustomClassesSync),t.onReconnect&&(Re.onReconnect=t.onReconnect),t.onAgentNotification&&(Re.onAgentNotification=t.onAgentNotification),t.onBuildingUpdated&&(Re.onBuildingUpdated=t.onBuildingUpdated),t.onSubagentStarted&&(Re.onSubagentStarted=t.onSubagentStarted),t.onSubagentCompleted&&(Re.onSubagentCompleted=t.onSubagentCompleted)}function ER(){Re.onToast=null,Re.onAgentCreated=null,Re.onAgentUpdated=null,Re.onAgentDeleted=null,Re.onAgentsSync=null,Re.onAreasSync=null,Re.onSpawnError=null,Re.onSpawnSuccess=null,Re.onToolUse=null,Re.onDirectoryNotFound=null,Re.onDelegation=null,Re.onCustomClassesSync=null,Re.onReconnect=null,Re.onAgentNotification=null,Re.onSubagentStarted=null,Re.onSubagentCompleted=null}function MR(){Re.onAgentCreated=null,Re.onAgentUpdated=null,Re.onAgentDeleted=null,Re.onAgentsSync=null,Re.onAreasSync=null,Re.onToolUse=null,Re.onDelegation=null,Re.onCustomClassesSync=null,Re.onBuildingUpdated=null,Re.onSubagentStarted=null,Re.onSubagentCompleted=null}const jf=new Map,DR=new Map,Jb={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(),DR.clear()},report(){}};class RR{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 RR;class OR{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 OR;function yu(t,e,n,s,a,r){}function Dj(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 Zb=pt.PENDING_MESSAGES,LR=300*1e3;function Rj(){try{const t=localStorage.getItem(Zb);if(!t)return[];const e=JSON.parse(t),n=Date.now();return e.filter(s=>n-s.queuedAt<LR)}catch{return[]}}function Oj(t){try{t.length===0?localStorage.removeItem(Zb):localStorage.setItem(Zb,JSON.stringify(t))}catch{}}function Tf(t){const e=Rj();e.push({message:t,queuedAt:Date.now()}),Oj(e)}function IR(){var s;const t=Rj();if(t.length===0)return 0;let e=0;const n=[];for(const a of t)PR(a.message)?e++:n.push(a);if(Oj(n),e>0){const a=e===1?"queued message":"queued messages";(s=Re.onToast)==null||s.call(Re,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function Bx(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 PR(t){const e=Yp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const n=JSON.stringify(t),s=Bx(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 Fx(t){var n,s,a,r,i,c,d,f,h,m;const e=Yp();if(!e)return(n=Qk())==null||n(),t.type==="send_command"?(Tf(t),(s=Re.onToast)==null||s.call(Re,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=Re.onToast)==null||a.call(Re,"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=Re.onToast)==null||r.call(Re,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=Re.onToast)==null||i.call(Re,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Qk())==null||c(),t.type==="send_command"?(Tf(t),(d=Re.onToast)==null||d.call(Re,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=Re.onToast)==null||f.call(Re,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const b=JSON.stringify(t),y=Bx(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=Re.onToast)==null||h.call(Re,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=Re.onToast)==null||m.call(Re,"error","Send Failed",`Failed to send message: ${b}`),!1}}const vu=new Set,BR=5e3;function Xk(t){if(!t.isDetached||!t.sessionId){vu.delete(t.id);return}vu.has(t.id)||(vu.add(t.id),Fx({type:"reattach_agent",payload:{agentId:t.id}}),setTimeout(()=>{vu.delete(t.id)},BR))}function FR(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(Jb.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=Re.onAgentsSync)==null||e.call(Re,_),U.loadToolHistory();for(const R of _)Xk(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=Re.onAgentCreated)==null||s.call(Re,_),(a=Re.onSpawnSuccess)==null||a.call(Re),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=Re.onToast)==null||r.call(Re,"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(_),Xk(_),(i=Re.onAgentUpdated)==null||i.call(Re,_,$);break}case"agent_deleted":{const{id:_}=t.payload;vu.delete(_),U.removeAgent(_),(c=Re.onAgentDeleted)==null||c.call(Re,_);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=Re.onToolUse)==null||d.call(Re,_.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=Re.onToast)==null||f.call(Re,"error","Error",_.message),(h=Re.onSpawnError)==null||h.call(Re),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=Re.onDirectoryNotFound)==null||m.call(Re,_),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=Re.onAreasSync)==null||b.call(Re);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=Re.onBuildingUpdated)==null||y.call(Re,_);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=Re.onToast)==null||w.call(Re,"info","Task Delegated",`Delegated to ${_.selectedAgentName}: ${_.reasoning.slice(0,80)}...`),_.bossId&&_.selectedAgentId&&((C=Re.onDelegation)==null||C.call(Re,_.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=Re.onAgentCreated)==null||N.call(Re,_),Fx({type:"move_agent",payload:{agentId:_.id,position:M}}),(k=Re.onToast)==null||k.call(Re,"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=Re.onCustomClassesSync)==null||j.call(Re,M);break}case"custom_agent_class_created":{const _=t.payload;U.addCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class created: ${_.name}`),(S=Re.onCustomClassesSync)==null||S.call(Re,U.getState().customAgentClasses);break}case"custom_agent_class_updated":{const _=t.payload;U.updateCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class updated: ${_.name}`),(T=Re.onCustomClassesSync)==null||T.call(Re,U.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:_}=t.payload;U.removeCustomAgentClassFromServer(_),console.log(`[WebSocket] Custom agent class deleted: ${_}`),(D=Re.onCustomClassesSync)==null||D.call(Re,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=Re.onAgentNotification)==null||E.call(Re,_);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=Re.onSubagentStarted)==null||I.call(Re,_);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=Re.onSubagentCompleted)==null||O.call(Re,_);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}}Jb.end(`ws:${t.type}`)}_R(()=>Hu());let Jk=!1;function Lj(){const t=Yp();t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Page unloading");const e=Tj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),TR()}function zR(){Jk||(window.addEventListener("beforeunload",Lj),Jk=!0)}function Ij(){Lj(),U.setConnected(!1),U.stopStatusPolling()}function $R(){Ij(),Xb(0),setTimeout(()=>Hu(),100)}function Hu(){zR();const t=Tj();t&&(clearTimeout(t),_j(null));const e=Yp();if(jR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Kk()&&Re.onReconnect&&Re.onReconnect();return}Xb(Qb()+1),nu(!0);const n=Ox(),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),Zk();return}Yk(i),i.onopen=()=>{var d,f,h;const c=Kk();nu(!1),Xb(0),NR(),U.setConnected(!0),U.startStatusPolling(),U.clearAllPermissions(),c?((d=Re.onToast)==null||d.call(Re,"success","Reconnected","Connection restored - refreshing data..."),(f=Re.onReconnect)==null||f.call(Re)):(h=Re.onToast)==null||h.call(Re,"success","Connected","Connected to Tide Commander server"),AR(n,s),IR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=Bx(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&vs.captureReceived(f,c.data),FR(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),Yk(null),U.setConnected(!1),U.stopStatusPolling();const c=Qb();c<Gk?((d=Re.onToast)==null||d.call(Re,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${Gk})`),Zk()):(f=Re.onToast)==null||f.call(Re,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{nu(!1)},U.setSendMessage(Fx)}function Zk(){const t=Qb(),e=Math.min(1e3*Math.pow(2,t-1),3e4);_j(setTimeout(Hu,e))}function UR(t,e){const n={position:t,target:e};La(pt.CAMERA_STATE,n)}function HR(){return Na(pt.CAMERA_STATE,null)}function jq(t,e,n){const s={posX:t,posZ:e,zoom:n};La(pt.CAMERA_STATE_2D,s)}function Nq(){return Na(pt.CAMERA_STATE_2D,null)}function sc(){return{Authorization:`Bearer ${Ii()}`,"Content-Type":"application/json"}}async function WR(){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 qR(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 eS(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 VR(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 YR(){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 tS(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=[],Pj=!1;const ex=new Set;function Dg(t){Pj=t,ex.forEach(e=>e(t))}const Bj="tide-commander-active-workspace";function nS(){return typeof window>"u"?null:localStorage.getItem(Bj)||null}function Rg(t){typeof window>"u"||localStorage.setItem(Bj,t||"")}function au(){Wu.forEach(t=>t())}function GR(){return sr}function zx(t){return sr?t?sr.areaIds.includes(t):!1:!0}function Tq(t){return sr?sr.areaIds.includes(t):!0}function Fj(){const[,t]=x.useState(0);return x.useEffect(()=>{const e=()=>t(n=>n+1);return Wu.add(e),()=>{Wu.delete(e)}},[]),[sr,xo]}function KR(t){return Wu.add(t),()=>{Wu.delete(t)}}function QR(){const[t,e]=x.useState(Pj);return x.useEffect(()=>{const n=s=>e(s);return ex.add(n),()=>{ex.delete(n)}},[]),t}const Og=new Map,XR=Se.memo(function(){const{t:e}=dt("common"),n=ur(),[s,a]=x.useState([]),[r,i]=x.useState(()=>nS()),[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=nS(),[H,V]=await Promise.all([WR(),YR()]);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=HR();B&&(Og.set(r,B),eS(r,{cameraState:B}).then(K=>{a(se=>{const q=se.map(be=>be.id===r?K:be);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&&(UR(K.position,K.target),Og.set(L,K))}tS(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 qR(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 eS(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 VR(L);const F=s.filter(H=>H.id!==L);a(F),xo=F,r===L&&(i(null),Rg(null),sr=null,await tS(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 zj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function JR(){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 $j(t){typeof window<"u"&&(window.__tideWsConnected=t)}function ZR(t){typeof window<"u"&&(window.__tideIsPageUnloading=t)}function eO(){sessionStorage.setItem(vp,"true")}function _f(t){ZR(!0),sessionStorage.removeItem(vp),Ij(),ER(),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),$j(!1);const n=document.getElementById("battlefield");n&&n.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function tO(){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=zj();n&&n!==s&&n.remove(),sessionStorage.removeItem(vp)}function nO(){typeof window>"u"||(tO(),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})`)}))}nO();const sS={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},aS={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},rS={idleAnimation:"sit",workingAnimation:"sprint"},sO=0;function Uj(){const t={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:sS,modelStyle:aS,animations:rS,fpsLimit:sO},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:{...sS,...e.terrain},modelStyle:{...aS,...e.modelStyle},animations:{...rS,...e.animations},fpsLimit:e.fpsLimit??t.fpsLimit}}return t}function aO(t){La(pt.CONFIG,t)}function rO(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function Hj(){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=Hj);function iO({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=zj()===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 se=U.getState().buildings.get(G);((se==null?void 0:se.type)==="server"||(se==null?void 0:se.type)==="boss"||(se==null?void 0:se.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),eO();try{const{SceneManager:W}=await vt(async()=>{const{SceneManager:H}=await import("./SceneManager-7WDKGyPC.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=Uj();L.setCharacterScale(F.characterScale),L.setScale3D(F.scale3d),L.setTimeMode(F.timeMode),L.setTerrainConfig(F.terrain),L.setFloorStyle(F.terrain.floorStyle,!0),L.setGridVisible(F.gridVisible),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 $())}Mj({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=KR(()=>{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"&&rO()&&N.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),MR(),N.current.dispose(),N.current=null,qu(null),Eu(null))}},[n,s]),N}function oO({showToast:t,showAgentNotification:e}){x.useEffect(()=>{Mj({onToast:t,onReconnect:()=>{U.triggerReconnect()},onAgentNotification:a=>{e(a)}}),JR()||(Hu(),$j(!0)),kR();let n;CR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&Nj(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 lO(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 cO(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 uO(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 dO(t,e){x.useEffect(()=>{var n;(n=t.current)==null||n.highlightArea(e)},[t,e])}function fO(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 _q(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 Eq(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 pO({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 hO(){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 mO(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 gO=3e4;function bO(){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,gO),()=>{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:""},iS=90,Bg=["simple","chat","advanced"],oS=55,lS=20,cS=95,xO=200,yO=12e4,vO=5,la=new Map;function wO(t){const e=la.get(t);e&&(la.delete(t),la.set(t,e))}function kO(){for(;la.size>vO;){const t=la.keys().next().value;if(t!==void 0)la.delete(t);else break}}function Wj(t){la.delete(t)}function SO(t){return t.trim().replace(/\r\n/g,`
|
|
43
43
|
`)}function tx(t,e){return`${t}:${SO(e)}`}function uS(t,e,n,s){if(t.uuid&&e.has(t.uuid))return!1;const a=t.isUserPrompt?"user":"assistant",r=tx(a,t.text),i=t.timestamp||0,c=n.get(r);return c!==void 0&&Math.abs(i-c)<=yO?!1:i>s}function qj({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,se=!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(ie=>({...ie})))}z.current&&(clearTimeout(z.current),z.current=null),B&&la.delete(t),D.current+=1;const be=D.current;m(!0);const Ce=la.get(t);Ce?(wO(t),c(Ce.messages),E.current=Ce.messages.length,k(Ce.hasMore),O.current=Ce.hasMore,S(Ce.totalCount)):(c([]),E.current=0,k(!1),O.current=!1,S(0)),se||(z.current=setTimeout(()=>{f(!0)},150)),Bt(Rt(`/api/agents/${t}/history?limit=${iS}&offset=0`)).then(Z=>{if(!Z.ok)throw new Error(`HTTP ${Z.status}: ${Z.statusText}`);return Z.json()}).then(Z=>{if(be!==D.current)return;const ie=Array.isArray(Z.messages)?Z.messages:[],me=Array.isArray(Z.subagents)?Z.subagents:[];c(ie),E.current=ie.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:ie,hasMore:Ee,totalCount:Z.totalCount||0}),kO(),q&&q.length>0){const Te=ie.length>0?Math.max(...ie.map(ne=>ne.timestamp?new Date(ne.timestamp).getTime():0)):0,Ve=new Set(ie.map(ne=>ne.uuid).filter(ne=>typeof ne=="string"&&ne.length>0)),We=new Map;for(const ne of ie){if(ne.type!=="user"&&ne.type!=="assistant")continue;const Ne=tx(ne.type,ne.content),ze=ne.timestamp?new Date(ne.timestamp).getTime():0,st=We.get(Ne)??0;ze>st&&We.set(Ne,ze)}const ee=q.filter(ne=>uS(ne,Ve,We,Te));U.clearOutputs(t);for(const ne of ee)U.addOutput(t,ne)}else if(ie.length>0){const Te=Math.max(...ie.map(Ne=>Ne.timestamp?new Date(Ne.timestamp).getTime():0)),Ve=new Set(ie.map(Ne=>Ne.uuid).filter(Ne=>typeof Ne=="string"&&Ne.length>0)),We=new Map;for(const Ne of ie){if(Ne.type!=="user"&&Ne.type!=="assistant")continue;const ze=tx(Ne.type,Ne.content),st=Ne.timestamp?new Date(Ne.timestamp).getTime():0,pe=We.get(ze)??0;st>pe&&We.set(ze,st)}const ee=U.getOutputs(t),ne=ee.filter(Ne=>{const ze=uS(Ne,Ve,We,Te);return ze||console.warn(`[HISTORY-DEDUP] Removing live output: uuid=${Ne.uuid||"none"} ts=${Ne.timestamp} lastHistTs=${Te} text="${Ne.text.slice(0,80)}"`),ze});if(ee.length!==ne.length){console.warn(`[HISTORY-DEDUP] Cleared ${ee.length-ne.length}/${ee.length} overlapping outputs for agent ${t}`),U.clearOutputs(t);for(const Ne of ne)U.addOutput(t,Ne)}}if(!a.get(t)){for(let Te=ie.length-1;Te>=0;Te--)if(ie[Te].type==="user"){U.setLastPrompt(t,ie[Te].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 ie of q)U.addOutput(t,ie)}}).finally(()=>{T.current&&be===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 se=await(await Bt(Rt(`/api/agents/${t}/history?limit=${iS}&offset=${B}`))).json(),q=Array.isArray(se.subagents)?se.subagents:[];if(q.length>0&&U.hydrateSubagentsFromHistory(t,q),se.messages&&se.messages.length>0){if(!T.current)return;c(Ce=>{const Z=[...se.messages,...Ce];return E.current=Z.length,Z});const be=se.hasMore||!1;O.current=be,k(be),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<xO&&$()},[$,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 se=Array.isArray(K.subagents)?K.subagents:[];se.length>0&&U.hydrateSubagentsFromHistory(t,se),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 CO(t){return(t.tokensUsed??0)===0&&(t.contextUsed??0)===0&&!t.contextStats&&!t.sessionId&&!t.currentTask&&!t.lastAssignedTask}function dS(t,e){var r,i;if(!t||CO(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 AO(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,dS(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,dS(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)}),Wj(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,j,S){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,effort:j,opencodeModel:S,customInstructions:k?`${k.length} chars`:void 0});const T=d?{x:d.x,y:0,z:d.z}:void 0,D={type:"spawn_agent",payload:{name:r,class:i,cwd:c,position:T,sessionId:f,useChrome:h,permissionMode:m,initialSkillIds:b,provider:y,codexConfig:w,codexModel:C,opencodeModel:S,model:N,effort:j,customInstructions:k}},E=s();if(!E){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}E(D)},createDirectoryAndSpawn(r,i,c){var d;(d=s())==null||d({type:"create_directory",payload:{path:r,name:i,class:c}})},sendCommand(r,i){var c;e(d=>{d.lastPrompts.set(r,{text:i,timestamp:Date.now()})}),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.effort!==void 0&&(m.effort=i.effort),i.provider!==void 0&&(m.provider=i.provider),i.codexConfig!==void 0&&(m.codexConfig=i.codexConfig),i.codexModel!==void 0&&(m.codexModel=i.codexModel),i.opencodeModel!==void 0&&(m.opencodeModel=i.opencodeModel),i.useChrome!==void 0&&(m.useChrome=i.useChrome),i.cwd!==void 0&&(m.cwd=i.cwd);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 fS=200;function pS(t){return t.length<=fS?t:t.slice(-fS)}function jO(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=pS([...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=pS(c),e(d=>{const f=new Map(d.agentOutputs);f.set(a,c),d.agentOutputs=f}),n(),c}}}function NO(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 TO(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 Vj="tide:bottom-pm2-log-retention",Fg=5e3,_O=[1e3,2500,5e3,1e4,null];function Yj(){if(typeof window>"u")return Fg;try{const t=window.localStorage.getItem(Vj);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 EO(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Vj,t===null?"unlimited":String(t))}catch{}}function Gj(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 MO(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=Yj(),m=Gj(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 DO(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 RO(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 OO(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 LO(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 Z5(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 eW(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 tW=1;function Xf(){return`bp-${tW++}`}const nW=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(()=>Gj(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=RN({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 sW=x.memo(function({onSaveSnapshot:e}={}){var xd,Ko,ti,yd,mc;const{t:n}=dt(["terminal","common"]),s=ed(),a=Ux(),r=t1(),i=Hx(),c=i1(),d=o1(),f=n1(),h=qx(),m=Vx(),b=cL(),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=(Qj(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=Wx(),O=x.useMemo(()=>{if(!T)return null;const Q=new Set,ue=[];for(const Me of E.values())Me.archived||Me.directories.length===0||Me.assignedAgentIds.includes(T)&&(Q.add(Me.id),ue.push(Me));const ce=s.get(T);if(ce)for(const Me of E.values())Me.archived||Me.directories.length===0||Q.has(Me.id)||eW({x:ce.position.x,z:ce.position.z},Me)&&(Q.add(Me.id),ue.push(Me));return ue.length===0?null:ue.flatMap(Me=>Me.directories.filter(nt=>nt&&nt.trim().length>0).map(nt=>({areaId:Me.id,areaName:Me.name,dir:nt})))},[T,E,s]),_=x.useMemo(()=>{var ce;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Me of I.values())Me.type==="terminal"&&U.isPositionInArea(Me.position,Q)&&ue.push({id:Me.id,name:Me.name,hasUrl:!!((ce=Me.terminalStatus)!=null&&ce.url)});return ue},[T,I,E]),M=x.useMemo(()=>{var ce;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Me of I.values())Me.type==="server"&&((ce=Me.pm2)!=null&&ce.enabled)&&U.isPositionInArea(Me.position,Q)&&ue.push({id:Me.id,name:Me.name});return ue},[T,I,E]),R=x.useMemo(()=>{if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const ce of I.values())ce.type==="database"&&ce.database&&U.isPositionInArea(ce.position,Q)&&ue.push({id:ce.id,name:ce.name});return ue},[T,I,E]),{branches:z,fetchRemote:$,fetchingDirs:W}=qH(O),{terminalHeight:L,terminalRef:F,handleResizeStart:H}=DH(),{mobileOverviewHeight:V,handleResizeMouseDown:G,handleResizeTouchStart:B}=LH(),K=MH(),[se,q]=x.useState(()=>{const Q=Dx(pt.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,Q))}),be=x.useRef(null),Ce=x.useCallback((Q,ue)=>{Q.preventDefault(),be.current={startX:Q.clientX,startW:se},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",U.setTerminalResizing(!0);let ce=se;const Me=ut=>{if(!be.current)return;const Nt=ut.clientX-be.current.startX,_t=ue==="left"?-Nt:Nt;ce=Math.max(280,Math.min(700,be.current.startW+_t)),q(ce)},nt=()=>{be.current=null,document.body.style.cursor="",document.body.style.userSelect="",U.setTerminalResizing(!1),document.removeEventListener("mousemove",Me),document.removeEventListener("mouseup",nt),Rx(pt.SIDE_PANEL_WIDTH,ce)};document.addEventListener("mousemove",Me),document.addEventListener("mouseup",nt)},[se]),Z=Xj(T),ie=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),Te=x.useRef(null),Ve=x.useRef(null),[We,ee]=x.useState(()=>{const Q=Fa(pt.VIEW_MODE);return Q==="simple"||Q==="chat"||Q==="advanced"?Q:Fa(pt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[ne,Ne]=x.useState(()=>Ni(pt.TERMINAL_FULLSCREEN,!1)),[ze,st]=x.useState(null),[pe,Be]=x.useState(null),[oe,de]=x.useState(null),[He,et]=x.useState(null),[ct,fe]=x.useState(!1);Xt("guake-image-modal",ze!==null,()=>st(null)),Xt("guake-bash-modal",pe!==null,()=>Be(null)),Xt("guake-response-modal",He!==null,()=>et(null)),Xt("guake-context-confirm",oe!==null,()=>de(null)),Xt("guake-agent-info",ct,()=>fe(!1));const[X,ae]=x.useState(!1),[ke,J]=x.useState(()=>vs.isEnabled()),[he,Oe]=x.useState(()=>Ni(pt.GIT_PANEL_OPEN,!1)),$e=x.useCallback(Q=>{Oe(Q),Ti(pt.GIT_PANEL_OPEN,Q)},[]),[xe,Pe]=x.useState(()=>Ni(pt.BUILDINGS_PANEL_OPEN,!1)),te=x.useCallback(Q=>{Pe(Q),Ti(pt.BUILDINGS_PANEL_OPEN,Q)},[]),[ge,ve]=x.useState(()=>Ni(pt.WORKFLOW_PANEL_OPEN,!1)),Fe=x.useCallback(Q=>{ve(Q),Ti(pt.WORKFLOW_PANEL_OPEN,Q)},[]),[Ke,at]=x.useState(!1);x.useEffect(()=>{if(!T){at(!1);return}let Q=!1;return(async()=>{try{const ue=await Bt(Rt("/api/workflows/definitions"));if(Q||!ue.ok)return;const Me=(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||at(Me)}catch{Q||at(!1)}})(),()=>{Q=!0}},[T]);const ft=mL(),wt=x.useCallback(Q=>U.setOverviewPanelOpen(Q),[]),[it,gt]=x.useState([]),[ht,Gt]=x.useState({}),[tn,Ae]=x.useState(()=>Yj()),[Le,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),[rt,xt]=x.useState(null),[$t,En]=x.useState(null),nn=x.useMemo(()=>it.filter(Q=>Q.areaId===$t),[it,$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(([ce,Me])=>[ce,Me.map(nt=>({id:nt.id??Xf(),type:nt.type,buildingId:nt.buildingId}))]))}else{const ue=localStorage.getItem("tide:bottom-terminals");if(ue){const ce=JSON.parse(ue);for(const[Me,nt]of ce)Os.current.set(Me,[{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(Me=>({id:Me.id,type:Me.type,buildingId:Me.buildingId}))):Os.current.delete(ue.id);const ce=Array.from(Os.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(ce))}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 ce=ks();Gt({}),gt(Me=>{for(const _t of Me)_t.areaId===ce&&_t.type==="pm2-logs"&&U.stopLogStreaming(_t.buildingId);const nt=Me.filter(_t=>_t.areaId!==ce),ut={id:Xf(),type:ue,buildingId:Q,areaId:ce??void 0},Nt=[...nt,ut];return ps([ut]),Nt})},[ps,ks]),Ss=x.useCallback((Q,ue,ce)=>{const Me=ks();Ye(ce);try{localStorage.setItem("tide:bottom-split-direction",ce)}catch{}gt(nt=>{const ut=nt.filter(sn=>sn.areaId===Me);if(ut.length>=4||ut.some(sn=>sn.buildingId===Q))return nt;const Nt={id:Xf(),type:ue,buildingId:Q,areaId:Me??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 ce={...ue};return delete ce[Q],ce}),gt(ue=>{const ce=ue.find(ut=>ut.id===Q);(ce==null?void 0:ce.type)==="pm2-logs"&&U.stopLogStreaming(ce.buildingId);const Me=ue.filter(ut=>ut.id!==Q),nt=ce==null?void 0:ce.areaId;return nt&&ps(Me.filter(ut=>ut.areaId===nt)),Me})},[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 Me=Os.current.get(Q.id);if(!Me||Me.length===0)return ue;const nt=Me.map(ut=>({id:ut.id,type:ut.type,buildingId:ut.buildingId,areaId:Q.id}));return[...ue,...nt]})},[T]),x.useEffect(()=>{const Q=ue=>{const ce=ue.detail;ce!=null&&ce.buildingId&&Qn(ce.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",Q),()=>window.removeEventListener("tide:open-bottom-terminal",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const ce=ue.detail;ce!=null&&ce.buildingId&&Qn(ce.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 ce=ue.detail;ce!=null&&ce.buildingId&&Qn(ce.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",Q),()=>window.removeEventListener("tide:open-bottom-database",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const ce=ue.detail;ce!=null&&ce.buildingId&&(ce!=null&&ce.type)&&(ce!=null&&ce.direction)&&(nn.length===0?Qn(ce.buildingId,ce.type):Ss(ce.buildingId,ce.type,ce.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 ce=Le==="horizontal";ln.current={index:ue,startPos:ce?Q.clientX:Q.clientY,startRatios:[...Lt]},document.body.style.cursor=ce?"col-resize":"row-resize",document.body.style.userSelect="none";const Me=(sn=bt.current)==null?void 0:sn.querySelectorAll("iframe");Me==null||Me.forEach(gn=>gn.style.pointerEvents="none");const nt=bt.current,ut=nt?ce?nt.offsetWidth:nt.offsetHeight:1,Nt=gn=>{const qn=ln.current;if(!qn||!nt)return;const Qo=(ce?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="",Me==null||Me.forEach(gn=>gn.style.pointerEvents=""),document.removeEventListener("mousemove",Nt),document.removeEventListener("mouseup",_t)};document.addEventListener("mousemove",Nt),document.addEventListener("mouseup",_t)},[Le,Lt]),Is=x.useRef(new Set);x.useEffect(()=>{const Q=new Set(it.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},[it]);const wn=x.useRef(new Set);x.useEffect(()=>{var ce;const Q=it.filter(Me=>Me.type==="terminal");for(const Me of Q){const nt=I.get(Me.buildingId);!!((ce=nt==null?void 0:nt.terminalStatus)!=null&&ce.url)?wn.current.add(Me.buildingId):wn.current.has(Me.buildingId)&&(wn.current.delete(Me.buildingId),Fn(Me.id))}const ue=new Set(Q.map(Me=>Me.buildingId));for(const Me of wn.current)ue.has(Me)||wn.current.delete(Me)},[it,I,Fn]);const Po=x.useCallback(Q=>{Q.preventDefault(),Ft.current={startY:Q.clientY,startH:Ze};let ue=Ze;const ce=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)},Me=()=>{Ft.current=null,document.removeEventListener("mousemove",ce),document.removeEventListener("mouseup",Me);try{localStorage.setItem("tide:bottom-terminal-height",String(ue))}catch{}};document.addEventListener("mousemove",ce),document.addEventListener("mouseup",Me)},[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),[je,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 ce=Mt.current+Q;for(;ce>=0&&ce<ue.length;){const Me=ue[ce];if(s.has(Me)){At.current=!0,Mt.current=ce,ha(),U.selectAgent(Me);return}ce+=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 ce=window.history.state,nt={...typeof ce=="object"&&ce!==null?ce:{},__guakeAgentNav:{agentId:Q}};ue==="replace"?window.history.replaceState(nt,"",window.location.href):window.history.pushState(nt,"",window.location.href)},[]),Fo=x.useCallback(()=>{Ne(Q=>{const ue=!Q;return Ti(pt.TERMINAL_FULLSCREEN,ue),ue})},[]),It=qj({selectedAgentId:T,hasSessionId:D,reconnectCount:c,historyRefreshTrigger:d,lastPrompts:i,outputScrollRef:me}),Hn=IH({agents:s,selectedAgentId:T,isOpen:ot,overviewPanelOpen:ft,loadingHistory:It.fetchingHistory,hasModalOpen:!!(ze||pe||He||h||m),outputRef:me});x.useEffect(()=>{const Q=F.current;if(!Q||!ot)return;const ue=Me=>{Me.button===3?(Me.preventDefault(),Me.stopPropagation(),gr()):Me.button===4&&(Me.preventDefault(),Me.stopPropagation(),Ui())},ce=Me=>{(Me.button===3||Me.button===4)&&Me.preventDefault()};return Q.addEventListener("mouseup",ue),Q.addEventListener("mousedown",ce),()=>{Q.removeEventListener("mouseup",ue),Q.removeEventListener("mousedown",ce)}},[ot,gr,Ui]);const uc=x.useCallback(Q=>{U.setLastSelectionViaDirectClick(!0),U.selectAgent(Q)},[]),Xr=typeof window<"u"&&window.innerWidth<=768&&ft&&ot,Jr=nR({gestureRef:me,agentListRef:Ee,enabled:Xr,onSelect:uc}),ts=UH({selectedAgentId:k}),zo=QO(),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=sL(!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=aL(y?null:T),ud=hL(y?null:T);x.useEffect(()=>{X&&!ke&&(J(!0),vs.setEnabled(!0))},[X,ke]),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 ce=T?i.get(T):void 0;Bi(ce!=null&&ce.timestamp?Date.now()-ce.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 Me of Q)Me.type==="tool_result"&&Me.toolUseId&&ue.set(Me.toolUseId,Me.content);return(Me=>Me.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,We]),qi=ET({outputs:ie,viewMode:We}),Wa=x.useMemo(()=>{const Q=[],ue=new Set,ce=new Set;let Me=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=Mb(ut.content),_t=ut.uuid?`uuid:${ut.uuid}:${Nt}`:null;if(_t&&ce.has(_t))continue;const sn=ut.timestamp?new Date(ut.timestamp).getTime():0;Me===Nt&&Math.abs(sn-nt)<=YA||(Q.push(ut),_t&&ce.add(_t),Me=Nt,nt=sn)}return Q},[Wi]),Wn=x.useMemo(()=>{const Q=new Map,ue=new Set,ce=new Map;for(const Nt of Wa){const _t=Nt.timestamp?new Date(Nt.timestamp).getTime():0;if(Nt.type==="user"){const qn=Mb(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=ce.get(sn)??0;_t>gn&&ce.set(sn,_t)}const Me=[];let nt=null,ut=0;for(const Nt of qi){if(!Nt.isUserPrompt){if(!Nt.isStreaming&&!Z5(Nt.text)){if(Nt.uuid&&ue.has(Nt.uuid))continue;const qn=Qf(Nt.text),Va=Nt.timestamp||0,Qo=ce.get(qn);if(Qo&&Math.abs(Va-Qo)<=Q5)continue}Me.push(Nt);continue}const _t=Mb(Nt.text),sn=Nt.timestamp||0,gn=Q.get(_t);gn&&sn>=gn&&sn-gn<=K5||nt===_t&&Math.abs(sn-ut)<=YA||(Me.push(Nt),nt=_t,ut=sn)}return Me},[qi,Wa]),xr=x.useMemo(()=>[...Wa,...Wn],[Wa,Wn]),Ln=FH({selectedAgentId:T,isOpen:ot,allItems:xr,viewMode:We,hasMoreHistory:It.hasMore,loadAllHistory:It.loadAllHistory,loadingMore:It.loadingMore}),Vi=Wa.length+Wn.length,dd=HH({totalMessages:Vi,isOpen:ot,hasModalOpen:!!(ze||pe||He||h),scrollContainerRef:me,selectedAgentId:T,inputRef:Te,textareaRef:Ve,useTextarea:ts.useTextarea});x.useEffect(()=>{if(!(!(pe!=null&&pe.isLive)||!pe.command)){for(const Q of Wn)if(Q._bashCommand===pe.command&&Q._bashOutput){Be({command:pe.command,output:Q._bashOutput,isLive:!1});return}}},[pe,Wn]);const Ho=x.useCallback((Q,ue)=>{st({url:Q,name:ue})},[]),Wo=x.useCallback((Q,ue)=>{const ce=sh(Q,S==null?void 0:S.cwd),Me=ce.line?{...ue||{},targetLine:ce.line}:ue;U.setFileViewerPath(ce.path,Me,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(X5),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{U.setMobileView("3d"),fc(!1),ei(0)},J5))},[]),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 ce=ue<Q.length-1?Q.slice(0,ue+1):Q.slice();ce.push(T),ce.length>100&&ce.shift(),jn.current=ce,Mt.current=ce.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 ce=(Nt=(ut=ue.state)==null?void 0:ut.__guakeAgentNav)==null?void 0:Nt.agentId;if(!ce||typeof ce!="string"||!s.has(ce)||ce===k)return;kn.current=!0,At.current=!0;const Me=jn.current,nt=Me.lastIndexOf(ce);nt>=0?Mt.current=nt:(Me.push(ce),Mt.current=Me.length-1),ha(),U.selectAgent(ce)};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:ce}=me.current,Me=ue-Q-ce<150;Yo.current||(Yi.current=!Me,Me&&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 ce=performance.now();let Me=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?Me+=1:Me=0,nt=sn,Me>=3){hs(!1),ue=null;return}if(_t-ce>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 ce=ue.target;ce.tagName!=="INPUT"&&ce.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)):pe?(ue.stopImmediatePropagation(),Be(null)):ze?(ue.stopImmediatePropagation(),st(null)):Ln.searchMode&&(ue.stopImmediatePropagation(),Ln.closeSearch()))};return document.addEventListener("keydown",Q,!0),()=>document.removeEventListener("keydown",Q,!0)},[ze,pe,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},ce=nt=>{if(!bd.current){Gi.current=!1;return}if(JD("terminal")){Gi.current=!1;return}Gi.current=!ue(nt.target)},Me=nt=>{Gi.current&&(ue(nt.target)||U.setTerminalOpen(!1),Gi.current=!1)};return document.addEventListener("mousedown",ce,!0),document.addEventListener("mouseup",Me,!0),()=>{document.removeEventListener("mousedown",ce,!0),document.removeEventListener("mouseup",Me,!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 ${ne?"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 ${ne?"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 ce of ue){const Me=await ts.uploadFile(ce);Me&&ts.setAttachedFiles(nt=>[...nt,Me])}};return o.jsxs("div",{ref:F,className:`guake-terminal ${ot?"open":"collapsed"} ${ne&&ot?"fullscreen":""} ${X&&ot?"with-debug-panel":""} ${he&&ot?"with-git-panel":""} ${xe&&ot?"with-buildings-panel":""} ${ge&&ot?"with-workflow-panel":""} ${ft&&ot?"with-overview-panel":""} ${je?"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":`${se}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(l5,{agentId:T,onClose:()=>ae(!1)}),!y&&he&&ot&&T&&o.jsx(x5,{agentId:T,agents:s,onClose:()=>$e(!1),branchInfoMap:z,fetchRemote:$,fetchingDirs:W}),!y&&xe&&ot&&T&&o.jsx(R5,{agentId:T,onClose:()=>te(!1)}),!y&&ge&&ot&&T&&o.jsx(I5,{agentId:T,onClose:()=>Fe(!1)}),!y&&(X||he||xe||ge)&&ot&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:Q=>Ce(Q,"right")}),!y&&ft&&ot&&T&&o.jsx(E5,{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=>Ce(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(j6,{selectedAgent:S,selectedAgentId:T,sortedAgents:Hn.sortedAgents,swipeOffset:Hn.swipeOffset,viewMode:We,setViewMode:ee,searchMode:Ln.searchMode,toggleSearch:Ln.toggleSearch,closeSearch:Ln.closeSearch,debugPanelOpen:X,setDebugPanelOpen:ae,debuggerEnabled:ke,setDebuggerEnabled:J,gitPanelOpen:he,setGitPanelOpen:$e,buildingsPanelOpen:xe,setBuildingsPanelOpen:te,workflowPanelOpen:ge,setWorkflowPanelOpen:Fe,hasWorkflow:Ke,overviewPanelOpen:ft,setOverviewPanelOpen:wt,agentInfoOpen:ct,onToggleAgentInfo:fd,isFullscreen:ne,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(N6,{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&&ie.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(o5,{historyMessages:Wa,liveOutputs:Wn,agentId:T,execTasks:Uo,subagents:ud,viewMode:We,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(U5,{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(L6,{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:Te,textareaRef:Ve,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:ce})=>{const Me=z.get(ce),nt=W.has(ce);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${ue}: ${ce}${Me?` (${Me.branch}${Me.ahead?` ↑${Me.ahead}`:""}${Me.behind?` ↓${Me.behind}`:""})`:""}`,onClick:()=>U.openFileExplorerForAreaFolder(Q,ce),children:["📂 ",ce.split("/").filter(Boolean).pop()||ce,Me&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",Me.branch]}),Me.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${Me.ahead} ahead`,children:["↑",Me.ahead]}),Me.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${Me.behind} behind`,children:["↓",Me.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${nt?"fetching":""}`,title:"Git fetch",onClick:ut=>{ut.stopPropagation(),$(ce)},children:nt?"⏳":"⇣"})]})]},`${Q}:${ce}`)}),!y&&S&&(()=>{const Q=S.contextStats,ue=!!Q,ce=Q?Q.totalTokens:S.contextUsed||0,Me=Q?Q.contextWindow:S.contextLimit||2e5,nt=Q?Q.usedPercent:Math.round(ce/Me*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=(ce/1e3).toFixed(1),gn=(Me/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 ce=it.find(Me=>Me.buildingId===Q.id);ce&&Fn(ce.id)}else Q.hasUrl||U.sendBuildingCommand(Q.id,"start"),Qn(Q.id,"terminal")},onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),Un.has(Q.id)||xt({position:{x:ce.clientX,y:ce.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 ce=it.find(Me=>Me.buildingId===Q.id);ce&&Fn(ce.id)}else Qn(Q.id,"pm2-logs")},onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),Un.has(Q.id)||xt({position:{x:ce.clientX,y:ce.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 ce=it.find(Me=>Me.buildingId===Q.id);ce&&Fn(ce.id)}else Qn(Q.id,"database")},onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),Un.has(Q.id)||xt({position:{x:ce.clientX,y:ce.clientY},buildingId:Q.id,type:"database"})},children:"🗄️"},Q.id)})}),o.jsx(W5,{})]})]}),(()=>{const Q=[];return rt&&(Q.push({id:"open",label:"Open",icon:"⬇",onClick:()=>Qn(rt.buildingId,rt.type)}),nn.length>0&&(Q.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Ss(rt.buildingId,rt.type,"horizontal")}),Q.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Ss(rt.buildingId,rt.type,"vertical")}))),o.jsx(pr,{children:o.jsx(Do,{isOpen:rt!==null,position:(rt==null?void 0:rt.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 ${Le}`,style:{height:Ze},onWheel:Q=>Q.stopPropagation(),children:nn.map((Q,ue)=>{const ce=I.get(Q.buildingId);if(!ce)return null;const Me=Lt[ue]??1,nt=(()=>{var ut;if(Q.type==="terminal")return(ut=ce.terminalStatus)!=null&&ut.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ce.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(jx,{terminalUrl:ce.terminalStatus.url,visible:!0})]},Q.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ce.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:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",ce.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 ${ce.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);Ae(sn),EO(sn)},"aria-label":`Max log retention for ${ce.name}`,children:_O.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(nW,{buildingId:Q.buildingId,filterText:Nt,maxRetention:tn})]},Q.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",ce.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(EH,{building:ce})]},Q.id)})();return ue>0?o.jsxs(Se.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${Le}`,onMouseDown:ut=>Ls(ut,ue-1)}),nt]},Q.id):nt})})]}),it.filter(Q=>Q.areaId!==$t&&Q.type==="terminal").map(Q=>{var ce;const ue=I.get(Q.buildingId);return(ce=ue==null?void 0:ue.terminalStatus)!=null&&ce.url?o.jsx(jx,{terminalUrl:ue.terminalStatus.url,visible:!1},Q.id):null})]}),ot&&!ne&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:H,title:n("common:rightPanel.dragToResize")}),!(ot&&ne)&&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})]}),ze&&o.jsx(P6,{url:ze.url,name:ze.name,onClose:()=>st(null)}),pe&&o.jsx(B6,{state:pe,onClose:()=>Be(null)}),oe&&o.jsx(F6,{action:oe,selectedAgentId:T,subordinateCount:((mc=S==null?void 0:S.subordinateIds)==null?void 0:mc.length)||0,onClose:()=>de(null),onClearHistory:It.clearHistory}),o.jsx(z6,{}),o.jsx($6,{}),o.jsx(H6,{agent:S,isOpen:ct,onClose:()=>fe(!1)}),!y&&o.jsx(U6,{agent:S,content:He,onClose:()=>et(null)})]})});function aW(t){return t.trim().replace(/^v/i,"")}function GA(t){const n=aW(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 rW(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 iW(t,e){const n=GA(t),s=GA(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 rW(n.prerelease,s.prerelease)}function oW(t,e){const n=iW(t,e);return n===null?"unknown":n<0?"behind":n>0?"ahead":"equal"}async function lW(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 cW(t,e,n={}){const s=await lW(t,n);return s?{currentVersion:e,latestVersion:s,relation:oW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const uW="tide-commander",Db="1.40.2";function dW(){const[t,e]=x.useState({currentVersion:Db,latestVersion:null,relation:"unknown",isChecking:!1}),n=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await cW(uW,Db);e({currentVersion:Db,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return x.useEffect(()=>{n()},[n]),{...t,refresh:n}}const fW=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:Ex(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:_x(e.lastActivity)},title:Mx(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${n+1}`,children:["^",n+1]})]})}),pW=x.memo(function({onFocusAgent:e,onSpawnClick:n,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=dt(["common"]),c=ed(),d=ur(),f=Ux(),h=WO(),m=Hx(),b=Vr(),y=dr(),w=c1(),[C]=Fj(),[N,k]=x.useState(!1);Dj("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 ve=S.current;if(!ve)return;const Fe=Ke=>{ve.scrollWidth<=ve.clientWidth||(Ke.preventDefault(),Math.abs(Ke.deltaX)>Math.abs(Ke.deltaY)?ve.scrollLeft+=Ke.deltaX:ve.scrollLeft+=Ke.deltaY)};return ve.addEventListener("wheel",Fe,{passive:!1}),()=>ve.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,se=8,q=x.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),be=x.useMemo(()=>Array.from(c.values()).filter(ve=>{if(U.isAgentInArchivedArea(ve.id))return!1;if(C){const Fe=U.getAreaForAgent(ve.id);if(!zx((Fe==null?void 0:Fe.id)??null))return!1}return!0}).sort((ve,Fe)=>(ve.createdAt||0)-(Fe.createdAt||0)),[c,d,C]),{orderedAgents:Ce,moveAgent:Z}=mO(be),ie=Ce,me=x.useMemo(()=>{const ve=new Map;for(const Fe of ie)ve.set(Fe.id,U.getAreaForAgent(Fe.id));return ve},[ie,d]),Ee=x.useMemo(()=>{const ve=new Map;for(const Ke of ie){const at=me.get(Ke.id)||null,ft=(at==null?void 0:at.id)||null;ve.has(ft)||ve.set(ft,{area:at,agents:[]}),ve.get(ft).agents.push(Ke)}const Fe=Array.from(ve.values());return Fe.sort((Ke,at)=>{var ft,wt;return!Ke.area&&at.area?1:Ke.area&&!at.area?-1:!Ke.area&&!at.area?0:(((ft=Ke.area)==null?void 0:ft.name)||"").localeCompare(((wt=at.area)==null?void 0:wt.name)||"")}),Fe},[ie,me]),Te=x.useRef(e);Te.current=e;const Ve=x.useRef(M);Ve.current=M;const We=x.useRef(ie);We.current=ie;const ee=x.useRef(me);ee.current=me;const ne=x.useRef(Z);ne.current=Z,x.useEffect(()=>{const ve=new Map(O);let Fe=!1;for(const Ke of ie){const at=O.get(Ke.id);Ke.currentTool?(!at||at.tool!==Ke.currentTool)&&(ve.set(Ke.id,{tool:Ke.currentTool,key:Date.now()}),Fe=!0):at&&setTimeout(()=>{_(ft=>{const wt=new Map(ft);return wt.delete(Ke.id),wt})},1500)}Fe&&_(ve)},[ie.map(ve=>ve.currentTool).join(",")]),x.useEffect(()=>{const ve=h;if(!ve)return;const Fe=D.current.get(ve),Ke=S.current;Fe&&Ke&&requestAnimationFrame(()=>{const at=Fe.getBoundingClientRect(),ft=Ke.getBoundingClientRect(),it=at.left-ft.left+Ke.scrollLeft+at.width/2,gt=Ke.clientWidth;Ke.scrollTo({left:it-gt/2,behavior:"smooth"})})},[h]);const Ne=x.useCallback((ve,Fe)=>{if(G.current===ve.id){G.current=null,Fe.preventDefault(),Fe.stopPropagation();return}U.setLastSelectionViaDirectClick(!0),Fe.shiftKey?U.addToSelection(ve.id):U.selectAgent(ve.id),U.setTerminalOpen(!0)},[]),ze=x.useCallback(ve=>{var Fe;(Fe=Te.current)==null||Fe.call(Te,ve.id),U.setTerminalOpen(!0)},[]),st=x.useCallback(()=>I(null),[]),pe=x.useCallback((ve,Fe)=>{Fe?D.current.set(ve,Fe):D.current.delete(ve)},[]),Be=x.useCallback((ve,Fe)=>{R(Fe),F(Fe.id),ve.dataTransfer.effectAllowed="move",ve.dataTransfer.setData("text/plain",Fe.id),requestAnimationFrame(()=>{ve.target.classList.add("dragging")})},[]),oe=x.useCallback(ve=>{R(null),$(null),F(null),W.current=0,ve.target.classList.remove("dragging")},[]),de=x.useCallback((ve,Fe)=>{ve.preventDefault();const Ke=Ve.current;if(Ke){const at=ee.current.get(Ke.id),ft=We.current[Fe],wt=ft?ee.current.get(ft.id):null,it=(at==null?void 0:at.id)??null,gt=(wt==null?void 0:wt.id)??null;ve.dataTransfer.dropEffect=it===gt?"move":"none"}else ve.dataTransfer.dropEffect="move"},[]),He=x.useCallback((ve,Fe)=>{ve.preventDefault(),W.current++;const Ke=Ve.current;if(Ke){const at=ee.current.get(Ke.id),ft=We.current[Fe],wt=ft?ee.current.get(ft.id):null,it=(at==null?void 0:at.id)??null,gt=(wt==null?void 0:wt.id)??null;$(it===gt?Fe:null)}else $(Fe)},[]),et=x.useCallback(ve=>{W.current--,W.current===0&&$(null)},[]),ct=x.useCallback((ve,Fe)=>{ve.preventDefault();const Ke=Ve.current;if(!Ke)return;const at=We.current,ft=ee.current,wt=at.findIndex(it=>it.id===Ke.id);if(wt!==-1&&wt!==Fe){const it=ft.get(Ke.id),gt=at[Fe],ht=gt?ft.get(gt.id):null,Gt=(it==null?void 0:it.id)??null,tn=(ht==null?void 0:ht.id)??null;Gt===tn&&ne.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)},[]),ae=x.useCallback((ve,Fe)=>{if(!q||ve.touches.length!==1)return;fe(),X(),F(null);const Ke=ve.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]),ke=x.useCallback(ve=>{if(!q||ve.touches.length!==1)return;const Fe=V.current;if(!Fe||!H.current)return;const Ke=ve.touches[0],at=Ke.clientX-Fe.x,ft=Ke.clientY-Fe.y;Math.sqrt(at*at+ft*ft)>se&&(fe(),V.current=null)},[fe,q]),J=x.useCallback(()=>{fe(),V.current=null,Ve.current||F(null),X(),B.current=setTimeout(()=>{G.current=null,B.current=null},450)},[fe,X]);x.useEffect(()=>()=>{fe(),X()},[fe,X]);const he=ve=>{const Fe=`common:status.${ve}`;return i(Fe,{defaultValue:i("common:status.unknown")})},{currentVersion:Oe,latestVersion:$e,relation:xe,isChecking:Pe}=dW(),te=Oe;let ge=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]}),xe==="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]}):xe==="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,xe==="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)"})}):xe==="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)"})}):xe==="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")}):Pe?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:Hj,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(ve=>{var at,ft,wt,it,gt;const Fe=ve.agents,Ke=!ve.area;return o.jsxs("div",{className:`agent-bar-group ${Ke?"unassigned":""}`,style:{borderColor:((at=ve.area)==null?void 0:at.color)||void 0,background:ve.area?`${ve.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=ve.area)==null?void 0:ft.color)||"#888"},children:((wt=ve.area)==null?void 0:wt.name)||i("common:agentBar.unassigned")})}),((it=ve.area)==null?void 0:it.directories)&&ve.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:ve.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=ge++,tn=ie.findIndex(Ae=>Ae.id===ht.id);return o.jsx(fW,{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:oe,onDragOver:de,onDragEnter:He,onDragLeave:et,onDrop:ct,onAgentClick:Ne,onAgentDoubleClick:ze,onTouchStart:ae,onTouchMove:ke,onTouchEnd:J,onTouchCancel:J,onHoverEnter:I,onHoverLeave:st,onItemRef:pe},ht.id)})]},((gt=ve.area)==null?void 0:gt.id)||"unassigned")})]})]}),Array.from(O.entries()).map(([ve,Fe])=>{const Ke=D.current.get(ve);if(!Ke)return null;const at=Ke.getBoundingClientRect(),ft=fs[Fe.tool]||fs.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:Fe.tool,style:{position:"fixed",left:at.left+at.width/2,bottom:window.innerHeight-at.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-${ve}-${Fe.key}`)}),E&&(()=>{const ve=U.getAreaForAgent(E.id),Fe=m.get(E.id),Ke=fr(E.class,y),at=U.getAgentSupervisorHistory(E.id),ft=at.length>0?at[at.length-1]:void 0,wt=Date.now()-(E.createdAt||Date.now()),it=Math.floor(wt/6e4),gt=Math.floor(it/60),ht=gt>0?`${gt}h ${it%60}m`:`${it}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,Ae=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"}},Le=D.current.get(E.id),Ye={};if(Le){const Ze=Le.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":E.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:E.provider,className:"agent-bar-provider-icon",title:E.provider==="codex"?"Codex Agent":E.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),E.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Ex(E.status)},children:he(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]})]}),ve&&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:ve.color},children:ve.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:Ae(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 hW({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 mW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Rb=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),gW=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"}},bW=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:Ex(e.status)},children:a(mW[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:[Rb(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:[Rb(e.contextUsed)," / ",Rb(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:gW(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 KA(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 QA(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 XA={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 xW(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:XA[c]&&(a=XA[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 yW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var F,H,V,G,B,K,se,q,be,Ce,Z,ie,me,Ee,Te,Ve,We,ee,ne,Ne;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(ze=>{ze.preventDefault();const st=C.current?C.current.x:0,pe=C.current?C.current.y:0;w.current={mouseX:ze.clientX,mouseY:ze.clientY,popupX:st,popupY:pe},y(!0),T.current=Be=>{if(!w.current)return;const oe=Be.clientX-w.current.mouseX,de=Be.clientY-w.current.mouseY;m({x:w.current.popupX+oe,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=ze=>{if(ze==="logs"){if((j||S)&&r){r();return}U.sendBuildingCommand(e.id,ze),f(!0)}else U.sendBuildingCommand(e.id,ze)},O=(ze,st)=>{if(ze){const pe=`http://localhost:${ze}`;st&&i?i(pe):window.open(pe,"_blank")}},_=((V=e.pm2Status)==null?void 0:V.ports)||[],M=((B=(G=e.dockerStatus)==null?void 0:G.ports)==null?void 0:B.map(ze=>ze.host))||[],R=j?_:S?M:[],z=j?!!((K=e.pm2)!=null&&K.script):S?!!((se=e.docker)!=null&&se.image)||((q=e.docker)==null?void 0:q.mode)==="compose"||((be=e.docker)==null?void 0:be.mode)==="existing":!!((Ce=e.commands)!=null&&Ce.start),$=j?!!((Z=e.pm2)!=null&&Z.script):S?!0:!!((ie=e.commands)!=null&&ie.stop),W=j?!!((me=e.pm2)!=null&&me.script):S?!0:!!((Ee=e.commands)!=null&&Ee.restart),L=x.useMemo(()=>{const st=d?400:250;let pe=n.x+20,Be=n.y-80;return typeof window<"u"&&!h&&(n.x+20+280>window.innerWidth&&(pe=n.x-280-20),n.y-80<0?Be=10:n.y-80+st>window.innerHeight&&(Be=window.innerHeight-st-10)),{position:"fixed",left:pe+((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:ze=>ze.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(ze=>o.jsxs("a",{href:`http://localhost:${ze}`,className:"building-popup-port-link",onClick:st=>{st.preventDefault(),st.stopPropagation(),O(ze,st.altKey)},onMouseDown:st=>st.stopPropagation(),title:`Open http://localhost:${ze} (Alt+Click for modal)`,children:[":",ze]},ze))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:Vb[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:[((Te=e.pm2Status.cpu)==null?void 0:Te.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:KA(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:QA(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:KA(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:QA(e.dockerStatus.startedAt)})]})]}),S&&((Ve=e.dockerStatus)==null?void 0:Ve.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((ze,st)=>o.jsxs("span",{className:"service-item",title:`${ze.name}: ${ze.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:ze.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:ze.name})]},st))}),(e.lastError||j&&((We=e.pm2Status)==null?void 0:We.status)==="errored"||S&&((ee=e.dockerStatus)==null?void 0:ee.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),j&&((ne=e.pm2Status)==null?void 0:ne.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),S&&((Ne=e.dockerStatus)==null?void 0:Ne.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:ze=>O(R[0],ze.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(ze=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:st=>O(ze,st.altKey),title:`Open http://localhost:${ze} (Alt+Click for modal)`,children:[":",ze]},ze))]})]}),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((ze,st)=>o.jsx("pre",{children:xW(ze)},st))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function vW(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 wW(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 kW=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:Vb[_]||"#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:Vb[_.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),"% | ",vW(_.pm2Status.memory||0)]}),((z=_.pm2Status)==null?void 0:z.uptime)&&o.jsx("span",{className:"sub-uptime",children:wW(_.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")})]})}),SW=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=Gx(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=wL[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 CW({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 ie=setInterval(Z,w?3e3:1e4);return()=>clearInterval(ie)},[t,w]),x.useEffect(()=>{if(!t)return;const Z=su.getUsage();Z&&M===null&&R(Z.usedMB);const ie=setInterval(()=>{var st,pe;Nf.update();const me=Nf.getStats();s(me.current),r(Be=>[...Be,me.current].slice(-60));const Ee=su.getUsage();Ee&&c(Ee);const Te=window.__tideScene;if(Te){const Be=(st=Te.getMemoryDiagnostics)==null?void 0:st.call(Te);Be!=null&&Be.threeJs&&m(Be.threeJs);const oe=Te.renderer;if((pe=oe==null?void 0:oe.info)!=null&&pe.memory){const de=oe.info.memory.textures||0,He=Math.round(de*1);I({count:de,estimatedMB:He})}}const Ve=document.getElementsByTagName("*"),We=document.getElementsByTagName("canvas"),ee=document.getElementsByTagName("img"),ne=document.getElementsByTagName("video");let Ne=0;for(let Be=0;Be<Math.min(Ve.length,500);Be++){const oe=Ve[Be];oe.onclick&&Ne++,oe.onmousedown&&Ne++,oe.onkeydown&&Ne++}Ne+=10,S({nodeCount:Ve.length,listenerCount:Ne,canvasCount:We.length,imageCount:ee.length,videoCount:ne.length}),Ee&&f(Be=>{const oe=L.current,de={timestamp:Date.now(),heapMB:Ee.usedMB,geometries:(oe==null?void 0:oe.geometries)??0,textures:(oe==null?void 0:oe.textures)??0};return[...Be,de].slice(-120)});const ze=W.current;if(ze.length>=10){const Be=ze[0],oe=ze[ze.length-1],de=(oe.timestamp-Be.timestamp)/1e3/60;de>.1&&y((oe.heapMB-Be.heapMB)/de)}},1e3);return()=>{clearInterval(ie)}},[t,M]),!t)return null;const F=Z=>{const ie=Math.floor(Z/3600),me=Math.floor(Z%3600/60),Ee=Z%60;return ie>0?`${ie}h ${me}m`:me>0?`${me}m ${Ee}s`:`${Ee}s`},H=Z=>Z>=55?"#4aff9e":Z>=30?"#ffcc00":"#ff4a4a",V=(Z,ie)=>{const me=Z/ie;return me<.5?"#4aff9e":me<.8?"#ffcc00":"#ff4a4a"},G=Z=>Z===null?"#888":Z<1?"#4aff9e":Z<5?"#ffcc00":"#ff4a4a",B=Nf.getStats(),se=O<=768?80:10,q={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:se,left:10},"bottom-right":{bottom:se,right:10}},be=M&&i?i.usedMB-M:0,Ce=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:Ce("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:Ce("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:Ce("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:Ce("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:Ce("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:Ce("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,ie)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,Z/60*100)}%`,background:H(Z),opacity:.8}},ie))})]})]}),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:be>50?"#ff4a4a":be>20?"#ffcc00":"#4aff9e"},children:[be>0?"+":"",be," 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,ie)=>{const me=Math.min(...d.map(We=>We.heapMB)),Te=Math.max(...d.map(We=>We.heapMB))-me||1,Ve=(Z.heapMB-me)/Te*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,Ve)}%`,background:Z.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${Z.heapMB}MB`},ie)})})]}),$.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,ie)=>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"]})]},ie))})]})]}),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,ie)=>{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`},ie)})})]}),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 ie=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&ie.push("","--- Memory ---",`Heap Used: ${i.usedMB} MB`,`Heap Total: ${i.totalMB} MB`,`Heap Limit: ${i.limitMB} MB`,`Baseline: ${M??"N/A"} MB`,`Growth: ${be>0?"+":""}${be} MB`,`Growth Rate: ${b!==null?`${b.toFixed(2)} MB/min`:"N/A"}`),h&&ie.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),$.agentCount>0&&(ie.push("","--- Agent Memory ---",`Total: ${$.totalMB} MB`,`Agents: ${$.agentCount}`),$.agents.slice(0,5).forEach(Ee=>{ie.push(` ${Ee.name}: ${Ee.memoryMB} MB (${Ee.status})`)})),j&&ie.push("","--- DOM ---",`DOM Nodes: ${j.nodeCount.toLocaleString()}`,`Canvases: ${j.canvasCount}`,`Images: ${j.imageCount}`,`Videos: ${j.videoCount}`),E&&ie.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&&(ie.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&&(ie.push("","--- Agent Processes ---",`Total: ${T.agents.total} (${T.agents.working} working, ${T.agents.idle} idle)`),T.agents.processes.forEach(Ee=>{ie.push(` ${Ee.name}: ${Ee.memoryMB!=null?`${Ee.memoryMB}MB`:"N/A"} (${Ee.status})${Ee.pid?` PID:${Ee.pid}`:""}`)})));const me=ie.join(`
|
|
152
|
-
`);navigator.clipboard.writeText(me).then(()=>{const Ee=Z.currentTarget,Te=Ee.textContent;Ee.textContent="Copied!",setTimeout(()=>{Ee.textContent=Te},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 ie=window.__tideScene;ie!=null&&ie.logMemoryDiagnostics&&ie.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(),Jb.clear(),Nf.reset(),su.reset(),r([]),f([]);const ie=su.getUsage();ie&&R(ie.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 AW(){const t=l1(),e=x.useCallback(n=>{U.setViewMode(n)},[]);return[t,e]}const jW=["3d","2d","dashboard"],NW=x.memo(function({className:e=""}){const{t:n}=dt(["common"]),[s,a]=AW(),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}}),jW.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 ZT({className:t}){const{t:e}=dt(["terminal"]),[n,s]=x.useState(!1),[a,r]=x.useState(null),i=Dy(),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=HT({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 TW=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(ZT,{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:"📸"})]})]})}),_W=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(ZT,{}),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"})]})})})]})}),EW=Se.lazy(()=>vt(()=>import("./SpawnModal-DQ4uUm1y.js"),__vite__mapDeps([17,3,1,4])).then(t=>({default:t.SpawnModal}))),MW=Se.lazy(()=>vt(()=>import("./BossSpawnModal-DLJInoVf.js"),__vite__mapDeps([18,3,1,4])).then(t=>({default:t.BossSpawnModal}))),DW=Se.lazy(()=>vt(()=>import("./SubordinateAssignmentModal-BDUDt6WC.js"),__vite__mapDeps([19,3,1,4])).then(t=>({default:t.SubordinateAssignmentModal}))),RW=Se.lazy(()=>vt(()=>import("./index-BSl18-4e.js"),__vite__mapDeps([20,3,1,4,21])).then(t=>({default:t.Toolbox}))),OW=Se.lazy(()=>vt(()=>import("./index-mQmnkGdF.js"),__vite__mapDeps([22,3,1,4])).then(t=>({default:t.BuildingConfigModal}))),LW=Se.lazy(()=>vt(()=>import("./index-BwkNteiZ.js"),__vite__mapDeps([23,24,3,1,4])).then(t=>({default:t.CommanderView}))),IW=Se.lazy(()=>vt(()=>import("./SupervisorPanel-BZaBI9BA.js"),__vite__mapDeps([25,3,1,4])).then(t=>({default:t.SupervisorPanel}))),PW=Se.lazy(()=>vt(()=>import("./index-DJdXbeWz.js").then(t=>t.y),[]).then(t=>({default:t.FileExplorerPanel}))),BW=Se.lazy(()=>vt(()=>import("./index-Bxjd0N-j.js"),__vite__mapDeps([26,3,1,4])).then(t=>({default:t.Spotlight}))),FW=Se.lazy(()=>vt(()=>import("./ControlsModal-Cnnhwfr_.js"),__vite__mapDeps([27,3,1,4])).then(t=>({default:t.ControlsModal}))),zW=Se.lazy(()=>vt(()=>import("./SkillsPanel-D5wo2MHh.js"),__vite__mapDeps([28,3,1,4])).then(t=>({default:t.SkillsPanel}))),$W=Se.lazy(()=>vt(()=>Promise.resolve().then(()=>S2),void 0).then(t=>({default:t.AgentEditModal}))),UW=Se.lazy(()=>vt(()=>import("./SnapshotManager-BLjpctX_.js"),__vite__mapDeps([29,3,1,4])).then(t=>({default:t.SnapshotManager}))),HW=Se.lazy(()=>vt(()=>import("./RestoreArchivedAreaModal-C-X90Qxe.js"),__vite__mapDeps([30,3,1,4])).then(t=>({default:t.RestoreArchivedAreaModal}))),WW=Se.lazy(()=>vt(()=>import("./IntegrationsPanel-DLmIJEUy.js"),__vite__mapDeps([31,3,1,4])).then(t=>({default:t.IntegrationsPanel}))),qW=Se.lazy(()=>vt(()=>import("./MonitoringModal-PnEKvezF.js"),__vite__mapDeps([32,3,1,4])).then(t=>({default:t.MonitoringModal}))),VW=Se.lazy(()=>vt(()=>import("./WorkflowEditorPanel-D49yDqth.js"),__vite__mapDeps([33,3,1,4])).then(t=>({default:t.WorkflowEditorPanel}))),YW=Se.lazy(()=>vt(()=>import("./TriggerManagerPanel-DuBiclsE.js"),__vite__mapDeps([34,3,1,4])).then(t=>({default:t.TriggerManagerPanel})));function GW({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:se,onSyncScene:q}){const be=Rs(),Ce=Array.from(be.snapshots.values()),Z=be.snapshotsLoading;be.currentSnapshot,x.useEffect(()=>{N.isOpen&&U.fetchSnapshots()},[N.isOpen]);const ie=W==="selected",me=W&&W!=="selected"?be.buildings.get(W):null,Ee=be.selectedBuildingIds.size;return o.jsxs(x.Suspense,{fallback:null,children:[o.jsx(RW,{config:_,onConfigChange:M,onToolChange:R,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:Te=>w.open(Te||null),onOpenAreaExplorer:z,onOpenIntegrationsModal:Te=>h.open(Te),onOpenMonitoringModal:()=>m.open(),onOpenWorkflowEditor:()=>b.open(),onOpenTriggerManager:()=>y.open()}),o.jsx(OW,{isOpen:w.isOpen,onClose:w.close,buildingId:w.data,initialPosition:O||void 0}),o.jsx(EW,{isOpen:t.isOpen,onClose:t.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T,spawnAreaId:D}),o.jsx(MW,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T}),o.jsx(DW,{isOpen:n.isOpen,bossId:n.data||"",onClose:n.close}),C.isOpen&&C.data&&(()=>{const Te=be.agents.get(C.data);return Te?o.jsx($W,{agent:Te,isOpen:C.isOpen,onClose:C.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:Te=>{Te.key==="Escape"&&r.close(),Te.key==="Enter"&&$()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Te=>Te.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 ",be.selectedAgentIds.size," selected agent",be.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||ie)&&o.jsx("div",{className:"modal-overlay visible",onClick:L,onKeyDown:Te=>{Te.key==="Escape"&&L(),Te.key==="Enter"&&F()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Te=>Te.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",ie&&Ee>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[ie?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",ie&&Ee>1?"s":""," and ",ie&&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:Te=>{Te.key==="Escape"&&V()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:Te=>Te.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(LW,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(IW,{isOpen:i.isOpen,onClose:i.close}),o.jsx(PW,{isOpen:j.isOpen||E!==null||be.explorerAreaId!==null,areaId:j.id||be.explorerAreaId||null,folderPath:E,onChangeArea:Te=>j.open(Te),onClose:()=>{j.close(),U.closeFileExplorer()}}),o.jsx(BW,{isOpen:c.isOpen,onClose:c.close,onOpenSpawnModal:()=>t.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenSupervisor:()=>i.open(),onOpenFileExplorer:Te=>j.open(Te),onOpenPM2LogsModal:B,onOpenBossLogsModal:K,onOpenDatabasePanel:se,onOpenMonitoringModal:()=>m.open()}),o.jsx(FW,{isOpen:d.isOpen,onClose:d.close}),o.jsx(zW,{isOpen:f.isOpen,onClose:f.close}),o.jsx(WW,{isOpen:h.isOpen,onClose:h.close,initialTab:h.data}),o.jsx(qW,{isOpen:m.isOpen,onClose:m.close}),o.jsx(VW,{isOpen:b.isOpen,onClose:b.close}),o.jsx(YW,{isOpen:y.isOpen,onClose:y.close}),o.jsx(HW,{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:Te=>Te.stopPropagation(),children:o.jsx(UW,{snapshots:Ce,isLoading:Z,onViewSnapshot:async Te=>{await U.loadSnapshot(Te),be.selectedAgentIds.clear(),U.setTerminalOpen(!0),N.close()},onDeleteSnapshot:async Te=>{await U.deleteSnapshot(Te),await U.fetchSnapshots()},onRestoreSnapshot:async Te=>{await U.restoreFiles(Te)},onExportSnapshot:async Te=>{await U.loadSnapshot(Te),N.close()},onClose:N.close})})}),o.jsx(Do,{isOpen:S.isOpen,position:S.screenPosition,worldPosition:S.worldPosition,actions:I,onClose:S.close})]})}function KW({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 Ly(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 Iy(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 Py(t){const e=_o[t.class];return(e==null?void 0:e.icon)||"🤖"}function Ob({agent:t,onClick:e}){const n=Iy(t.status),s=Ly(t.status),a=Py(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 JA={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},ZA={systemPrompt:"System Prompt",systemTools:"System Tools",messages:"Messages",freeSpace:"Free Space",autocompactBuffer:"Autocompact Buffer"};function QW({agent:t,onBack:e}){const n=Py(t),s=Iy(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:Ly(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:JA[d]},title:`${ZA[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:JA[d]}}),o.jsxs("div",{className:"pip-category-info",children:[o.jsx("div",{className:"pip-category-name",children:ZA[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 XW({agentId:t,onBack:e}){const n=Qj(t),s=Xj(t),a=i1(),r=o1(),i=Hx(),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=qj({selectedAgentId:t,hasSessionId:w,reconnectCount:a,historyRefreshTrigger:r,lastPrompts:i,outputScrollRef:c}),N=ET({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=Py(n),z=Iy(n.status);return m?o.jsx(QW,{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:Ly(n.status)})]}),o.jsx("div",{className:"pip-context-section",children:o.jsx(v1,{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(XT,{message:$,agentId:t,simpleView:!0,onFileClick:M},`h-${W}`)),N.map(($,W)=>o.jsx(Ry,{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 JW({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(Ob,{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(Ob,{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(Ob,{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 ZW(){const[t,e]=x.useState(null),n=a=>{e(a)},s=()=>{e(null)};return t?o.jsx(XW,{agentId:t,onBack:s}):o.jsx(JW,{onSelectAgent:n})}function eq(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 tq(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 nq=4e3;function sq(){const t=Zj(),[e,n]=x.useState(!1),[s,a]=x.useState(!1),[r,i]=x.useState(!0),[c,d]=x.useState(()=>Ox()),[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(()=>YD(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=()=>nq-(Date.now()-D);b(null),w("Validating URL");const I=c.trim()||"http://localhost:6200",O=eq(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 tq(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}VD(O.normalizedUrl),w("Connecting to server"),$R();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 ej="tide-onboarding-dismissed";function aq({onCreateAgent:t}){const{t:e}=dt("common"),n=Zj(),s=Kj(),[a,r]=x.useState(()=>sessionStorage.getItem(ej)==="1"),i=n&&!a&&s===0,c=x.useCallback(()=>{r(!0),sessionStorage.setItem(ej,"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 e_(){return{"Content-Type":"application/json","X-Auth-Token":Ii()}}async function rq(t){const e=await fetch(`${Ea()}/api/areas/${t}/organize`,{method:"POST",headers:e_()});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 iq(){const t=await fetch(`${Ea()}/api/areas/organize-all`,{method:"POST",headers:e_()});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 t_(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 oq(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,position:{x:d.center.x,z:d.center.z}}}))}}),i.push({id:"divider-area-layer",label:"",divider:!0,onClick:()=>{}}),i.push({id:"bring-to-front",label:"Bring to Front",icon:"⬆️",onClick:()=>{var f;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:()=>{rq(e.id).then(f=>{t_(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 lq=Se.lazy(()=>vt(()=>import("./index-DZ3f9mNd.js"),__vite__mapDeps([35,3,1,4,36])).then(t=>({default:t.DatabasePanel}))),cq=Se.lazy(()=>vt(()=>import("./PM2LogsModal-EB_Au0iK.js"),__vite__mapDeps([37,38,3,1,4])).then(t=>({default:t.PM2LogsModal}))),uq=Se.lazy(()=>vt(()=>import("./DockerLogsModal-D4CbWK3-.js"),__vite__mapDeps([39,38,3,1,4])).then(t=>({default:t.DockerLogsModal}))),dq=Se.lazy(()=>vt(()=>import("./BossLogsModal-CaDrNfm1.js"),__vite__mapDeps([40,38,3,1,4])).then(t=>({default:t.BossLogsModal}))),fq=Se.lazy(()=>vt(()=>import("./Scene2DCanvas-DlVguRVM.js"),__vite__mapDeps([41,3,1,4,42])).then(t=>({default:t.Scene2DCanvas}))),pq=Se.lazy(()=>vt(()=>import("./index-BiGvhrCO.js"),__vite__mapDeps([43,3,1,4,44])).then(t=>({default:t.DashboardView}))),hq=Se.lazy(()=>vt(()=>import("./IframeModal-BJ4oeDBn.js"),__vite__mapDeps([45,3,1,4,46])).then(t=>({default:t.IframeModal}))),mq=Se.lazy(()=>vt(()=>import("./SaveSnapshotModal-D6XAjL2T.js"),__vite__mapDeps([47,3,1,4])).then(t=>({default:t.SaveSnapshotModal})));function gq(){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=GD(),I=ZO(),O=KD(),_=iR(),[M,R]=x.useState(null),z=QR(),[$,W]=x.useState(!1),[L,F]=x.useState(null),[H,V]=x.useState(null),[G,B]=x.useState(null),[K,se]=x.useState(null),[q,be]=x.useState(null),[Ce,Z]=x.useState(null),[ie,me]=x.useState(null),[Ee,Te]=x.useState(null),[Ve,We]=x.useState(null),[ee,ne]=x.useState(null),Ne=x.useCallback(je=>{ne(je),je&&localStorage.setItem("tide-commander-last-database-building",je)},[]),ze=x.useCallback(()=>Ne(null),[Ne]),{handleMouseDown:st,handleClick:pe}=Ta(ze),Be=x.useCallback(()=>We(null),[]),{handleMouseDown:oe,handleClick:de}=Ta(Be),He=x.useRef(Ce);He.current=Ce;const et=x.useCallback(je=>{Z(je)},[]),ct=x.useCallback(()=>He.current,[]),fe=x.useRef(null),[X,ae]=x.useState(Uj),[ke,J]=x.useState(0),[he,Oe]=x.useState(!1),[$e,xe]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[Pe,te]=x.useState(!1),[ge,ve]=x.useState(!1),Fe=n1(),Ke=l1(),at=qx(),ft=Vx(),wt=t1(),{showToast:it}=d1(),{showAgentNotification:gt}=jL(),{showBackNavModal:ht,setShowBackNavModal:Gt,handleLeave:tn}=hO();oO({showToast:it,showAgentNotification:gt});const[Ae,Le]=x.useState(!1);x.useEffect(()=>{const je=Je=>{var ot;((ot=Je.detail)==null?void 0:ot.mode)==="3d"&&Le(!0)};return window.addEventListener("tide:viewmode-switch-pressed",je),()=>{window.removeEventListener("tide:viewmode-switch-pressed",je)}},[]),x.useEffect(()=>{Ke==="3d"&&Le(!0)},[Ke]);const Ye=iO({canvasRef:e,selectionBoxRef:n,viewMode:Ke,sceneMountKey:ke,showToast:it,showAgentNotification:gt,toolboxModal:i,contextMenu:O,setHoveredAgentPopup:be,setBuildingPopup:et,getBuildingPopup:ct,openBuildingModal:je=>k.open(je),openPM2LogsModal:je=>me(je),openBossLogsModal:je=>Te(je),openDatabasePanel:je=>Ne(je),onSceneLoadingChange:Le}),Ze=Kj(),Ot=ur(),Ft=Wx(),Lt=Ux(),Vt=YO(),ln=VO(),bt=qO(),rt=Vr(),xt=KO(),$t=uL(),En=dL(),nn=x.useMemo(()=>Array.from(Lt),[Lt]),Un=x.useRef(!1);Dj("AppContent"),lO(Ye),cO(Ye),uO(Ye),bO(),dO(Ye,ln),fO(Ye,rt.powerSaving),x.useEffect(()=>{var je;document.title=((je=rt.tabTitle)==null?void 0:je.trim())||"Tide Commander"},[rt.tabTitle]),x.useEffect(()=>{var Dn,Fs;if(Un.current||typeof window>"u")return;const je=new URLSearchParams(window.location.search),Je=(Dn=je.get("agentId"))==null?void 0:Dn.trim(),Ct=(Fs=je.get("agentName"))==null?void 0:Fs.trim();if(!Je&&!Ct||Ze===0)return;const ot=U.getState().agents,jn=je.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),je.delete("agentId"),je.delete("agentName"),je.delete("openTerminal");const kn=je.toString(),ms=`${window.location.pathname}${kn?`?${kn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,ms),Un.current=!0},[Ze]),pO({sceneRef:Ye,spawnModal:s,commanderModal:c,explorerModal:E,spotlightModal:h,deleteConfirmModal:d,onRequestBuildingDelete:()=>se("selected"),onOpenDatabasePanel:Ne,onCloseDatabasePanel:ze,databasePanelOpen:ee!==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",he,()=>Oe(!1)),Xt("mobile-fab-menu",ge,()=>ve(!1)),Xt("file-viewer",at!==null,()=>U.clearFileViewerPath()),Xt("context-modal",ft!==null,()=>U.closeContextModal()),Xt("terminal",wt,()=>U.setTerminalOpen(!1)),Xt("pm2-logs-modal",ie!==null,()=>me(null)),Xt("boss-logs-modal",Ee!==null,()=>Te(null)),Xt("database-panel",ee!==null,ze),Xt("terminal-modal",Ve!==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 je=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(je)},[Fe,Ke]);const Qn=x.useCallback(je=>{var Je,Ct,ot,jn,Mt,At,kn,ms,Dn,Fs;ae(je),aO(je),(Je=Ye.current)==null||Je.setCharacterScale(je.characterScale),(Ct=Ye.current)==null||Ct.setScale3D(je.scale3d),(ot=Ye.current)==null||ot.setTimeMode(je.timeMode),(jn=Ye.current)==null||jn.setTerrainConfig(je.terrain),(Mt=Ye.current)==null||Mt.setFloorStyle(je.terrain.floorStyle),(At=Ye.current)==null||At.setGridVisible(je.gridVisible),(kn=Ye.current)==null||kn.setAgentModelStyle(je.modelStyle),(ms=Ye.current)==null||ms.setIdleAnimation(je.animations.idleAnimation),(Dn=Ye.current)==null||Dn.setWorkingAnimation(je.animations.workingAnimation),(Fs=Ye.current)==null||Fs.setFpsLimit(je.fpsLimit)},[Ye]),Ss=x.useCallback(je=>{var Je;if((Je=Ye.current)==null||Je.setDrawingTool(je),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(je),je==="rectangle"||je==="circle"){const Ct=t(je==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");it("info",Ct,t("notifications:drawing.clickAndDrag"),3e3)}},[Ye,it]),Fn=x.useCallback(je=>{var Je;(Je=Ye.current)==null||Je.focusAgent(je)},[Ye]),Ls=x.useCallback(je=>{U.killAgent(je)},[]),Is=x.useCallback(je=>{var Je;(Je=Ye.current)==null||Je.callSubordinates(je)},[Ye]),wn=x.useCallback(je=>{E.open(je)},[E]),Po=x.useCallback(()=>{k.open(null)},[k]),Bo=x.useCallback(()=>{var je;(je=Ye.current)==null||je.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),it("info",t("notifications:drawing.rectangleTool"),t("notifications:drawing.clickAndDrag"),3e3)},[Ye,it]),Ps=x.useCallback(je=>{R(je)},[]),Ua=x.useCallback(()=>{R(null)},[]),Bi=x.useCallback(()=>{const je=Array.from(U.getState().selectedAgentIds);je.forEach(Je=>{var Ct;U.removeAgentFromServer(Je),(Ct=Ye.current)==null||Ct.removeAgent(Je)}),d.close(),it("info",t("notifications:toast.agentsRemoved"),t("notifications:toast.agentsRemovedMsg",{count:je.length}))},[it,d,Ye,t]),Fi=x.useCallback(()=>{var je,Je;if(K==="selected"){const Ct=Vt.size;U.deleteSelectedBuildings(),(je=Ye.current)==null||je.syncBuildings(),it("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(),it("info",t("notifications:toast.buildingDeleted"),t("notifications:toast.buildingDeletedMsg",{name:(Ct==null?void 0:Ct.name)||"Building"}))}se(null)},[K,Ft,Vt.size,it,Ye,t]),Bs=x.useMemo(()=>oq(O.worldPosition,O.target,U.getState().agents,Ot,Ft,{showToast:it,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:je=>E.open(je),openBuildingModal:je=>k.open(je),openAgentEditModal:je=>j.open(je),requestBuildingDelete:je=>se(je),setSpawnPosition:F,openRestoreArchivedModal:je=>D.open(je),sceneRef:Ye}),[O.worldPosition,O.target,Ot,Ft,s,a,k,i,c,E,j,D,it,Ye]);x.useEffect(()=>{!s.isOpen&&!a.isOpen&&(F(null),B(null))},[s.isOpen,a.isOpen]),x.useEffect(()=>{const je=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"?Te(At.buildingId):kn.type==="database"?Ne(At.buildingId):kn.type==="folder"&&kn.folderPath?U.openFileExplorer(kn.folderPath):kn.type==="terminal"&&((Dn=kn.terminalStatus)!=null&&Dn.url)?We(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?We(At.buildingId):At!=null&&At.url&&R(At.url)};return window.addEventListener("tide:open-spawn-modal",je),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",je),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 je;(je=Ye.current)==null||je.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ye]),Ts=x.useCallback(()=>ve(je=>!je),[]),hs=x.useCallback(()=>U.setMobileView("terminal"),[]),Mn=x.useCallback(()=>Oe(!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(sq,{}),o.jsx(aq,{onCreateAgent:s.open}),o.jsx(CW,{visible:rt.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(NW,{className:"app-view-mode-toggle"}),o.jsx(XR,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:$,title:"Auto-organize all agents in their areas",onClick:()=>{W(!0),iq().then(je=>{t_(je,Ye),it("success","Organized",`Arranged ${je.organized.length} agent${je.organized.length!==1?"s":""}`)}).catch(je=>{console.error("organize all error:",je),it("error","Organize Failed",je.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(Se.Suspense,{fallback:null,children:Ke==="dashboard"?o.jsx(pq,{onSelectAgent:je=>U.selectAgent(je),onFocusAgent:je=>{U.setViewMode("3d"),Fn(je)},onKillAgent:Ls,onSelectBuilding:je=>U.selectBuilding(je),onOpenTerminal:je=>{U.selectAgent(je),U.setTerminalOpen(!0)},onFocusZone:je=>{U.setViewMode("3d");const Je=U.getState().areas.get(je);Je&&Je.assignedAgentIds.length>0&&Fn(Je.assignedAgentIds[0])}}):Ke==="2d"?o.jsx(fq,{onAgentClick:(je,Je)=>{Je?U.addToSelection(je):U.selectAgent(je)},onAgentDoubleClick:je=>{if(window.innerWidth<=768){U.openTerminalOnMobile(je);return}U.selectAgent(je),U.setTerminalOpen(!0)},onBuildingClick:(je,Je)=>{U.selectBuilding(je);const Ct=U.getState().buildings.get(je);(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:je,screenPos:Je,fromClick:!0}),fe.current=null},150))},onBuildingDoubleClick:je=>{var Ct;fe.current&&(clearTimeout(fe.current),fe.current=null),et(null);const Je=U.getState().buildings.get(je);(Je==null?void 0:Je.type)==="server"&&((Ct=Je.pm2)!=null&&Ct.enabled)?me(je):(Je==null?void 0:Je.type)==="boss"?Te(je):(Je==null?void 0:Je.type)==="database"?Ne(je):(Je==null?void 0:Je.type)==="folder"&&Je.folderPath?U.openFileExplorer(Je.folderPath):k.open(je)},onGroundClick:()=>{U.selectAgent(null),U.selectBuilding(null)},onAreaDoubleClick:je=>{U.selectArea(je),i.open()},onContextMenu:(je,Je,Ct)=>{const ot=Ct?{type:Ct.type,id:Ct.id}:{type:"ground"};O.open(je,Je,ot)},onMoveCommand:(je,Je)=>{const ot=je.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})}}je.forEach((Mt,At)=>{U.moveAgent(Mt,jn[At])})},onBuildingDragMove:(je,Je)=>{var ot;const Ct=U.getState().buildings.get(je);Ct&&(U.getState().buildings.set(je,{...Ct,position:{x:Je.x,z:Je.z}}),(ot=window.__tideScene2D)==null||ot.syncBuildings())},onBuildingDragEnd:(je,Je)=>{U.updateBuildingPosition(je,Je)},scale2d:X.scale2d,showTaskLabels:X.show2DTaskLabels,showGrid:X.gridVisible,fpsLimit:X.fpsLimit}):o.jsxs(Se.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:n,id:"selection-box"})]},ke)}),Ae&&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(TW,{isOpen:ge,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}),he&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>Oe(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${$e?"is-collapsed":""} ${Pe?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)Oe(!he);else{const Je=!$e;xe(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:Pe?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 ${he?"sidebar-open":""} ${$e?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>Oe(!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(ES,{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(_4,{agentIds:nn})})})]}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:yu,children:o.jsx(ES,{onFocusAgent:Fn,onKillAgent:Ls,onCallSubordinates:Is,onOpenAreaExplorer:wn})})})]}),o.jsx(x.Profiler,{id:"GuakeOutputPanel",onRender:yu,children:o.jsx(sW,{onSaveSnapshot:T.open})})]}),o.jsx(_W,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:b.open,onOpenSnapshots:S.open,isGeneratingReport:xt,pip:_}),o.jsx(hW,{activeTool:bt,onExit:Ma}),q&&(()=>{const je=U.getState().agents.get(q.agentId);return je?o.jsx(bW,{agent:je,screenPos:q.screenPos,onClose:()=>be(null)}):null})(),Ce&&(()=>{const je=Ft.get(Ce.buildingId);if(!je)return null;const Je=()=>et(null);return je.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(kW,{building:je,screenPos:Ce.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ce.buildingId)},onOpenLogsModal:()=>{Je(),Te(Ce.buildingId)},onOpenUrlInModal:Ps})]}):je.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(SW,{building:je,screenPos:Ce.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ce.buildingId)},onOpenDatabasePanel:()=>{Je(),Ne(Ce.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(yW,{building:je,screenPos:Ce.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ce.buildingId)},onOpenLogsModal:()=>{me(Ce.buildingId)},onOpenUrlInModal:Ps})]})})(),ie&&(()=>{var Je;const je=Ft.get(ie);return je?(Je=je.docker)!=null&&Je.enabled?o.jsx(uq,{building:je,isOpen:!0,onClose:()=>me(null)}):o.jsx(cq,{building:je,isOpen:!0,onClose:()=>me(null)}):null})(),Ee&&(()=>{const je=Ft.get(Ee);return je?o.jsx(dq,{building:je,isOpen:!0,onClose:()=>Te(null)}):null})(),ee&&(()=>{const je=Ft.get(ee);return je?o.jsx("div",{className:"modal-overlay visible",onMouseDown:st,onClick:pe,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(lq,{building:je,onClose:ze})})}):null})(),Ve&&(()=>{var Je;const je=Ft.get(Ve);return!je||!((Je=je.terminalStatus)!=null&&Je.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:oe,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 - ",je.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(jx,{terminalUrl:je.terminalStatus.url,visible:!0})]})})})(),o.jsx(KW,{pip:_,title:"Tide Commander - Agents",children:o.jsx(ZW,{})}),o.jsx(hq,{url:M||"",title:M?`Preview - ${M}`:"",isOpen:!!M,onClose:Ua}),T.isOpen&&nn.length===1&&(()=>{const je=nn[0],Je=U.getState().agents.get(je);if(!Je)return null;const Ct=U.getOutputs(je);return o.jsx(mq,{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(),it("success",t("notifications:toast.snapshotSaved"),t("notifications:toast.snapshotSavedMsg"))}catch(jn){const Mt=jn instanceof Error?jn.message:t("notifications:toast.snapshotFailedMsg");it("error",t("notifications:toast.snapshotFailed"),Mt)}},isSaving:$t,error:En||void 0})})(),o.jsx(pW,{onFocusAgent:Fn,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:Po,onNewAreaClick:Bo}),o.jsx(GW,{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:()=>se(null),onConfirmBuildingDelete:Fi,showBackNavModal:ht,onCloseBackNavModal:()=>Gt(!1),onLeave:tn,onOpenPM2LogsModal:je=>me(je),onOpenBossLogsModal:je=>Te(je),onOpenDatabasePanel:je=>Ne(je),onSyncScene:()=>{var je,Je;(je=Ye.current)==null||je.syncAreas(),(Je=Ye.current)==null||Je.syncAgents(Array.from(U.getState().agents.values()))}})]})}function bq(){return o.jsx(yL,{children:o.jsx(AL,{children:o.jsx(gq,{})})})}class xq 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}}A6();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 n_=document.getElementById("app");if(!n_)throw new Error("Could not find #app container");const yq=CM.createRoot(n_);yq.render(o.jsx(Se.StrictMode,{children:o.jsx(x.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(xq,{children:o.jsx(bq,{})})})}));console.log("[Tide] Tide Commander initialized");export{Df as $,NL as A,c1 as B,qD as C,wL as D,Mx as E,aV as F,_x as G,ed as H,Wx as I,ur as J,Ux as K,eL as L,dr as M,Iq as N,TL as O,Fa as P,oV as Q,TH as R,pt as S,fs as T,Jq as U,Bt as V,b1 as W,iV as X,k2 as Y,Mu as Z,Rf as _,Gx as a,ph as a$,Hg as a0,Wr as a1,Qp as a2,Xq as a3,Qj as a4,yp as a5,Aq as a6,vL as a7,Vb as a8,Yq as a9,WD as aA,o5 as aB,P6 as aC,B6 as aD,U6 as aE,zq as aF,Xj as aG,Uq as aH,Hq as aI,Dx as aJ,Rx as aK,np as aL,lV as aM,vt as aN,NN as aO,rV as aP,TN as aQ,_N as aR,Lu as aS,Fr as aT,zr as aU,W6 as aV,q6 as aW,d1 as aX,jb as aY,V6 as aZ,Do as a_,Ii as aa,Cq as ab,Wq as ac,Ey as ad,ia as ae,Pu as af,Up as ag,Ea as ah,pr as ai,Ox as aj,YD as ak,On as al,$R as am,VD as an,Gq as ao,Kq as ap,Qq as aq,Vq as ar,i1 as as,iS as at,Lq as au,Jj as av,Xt as aw,UH as ax,_T as ay,sh as az,oL as b,jN as b0,da as b1,RN as b2,d5 as b3,Oy as b4,gx as b5,v4 as b6,s1 as b7,_q as b8,Pq as b9,Eq as ba,Bq as bb,Fq as bc,Oq as bd,Dq as be,$q as bf,Kp as bg,PL as bh,x2 as bi,v2 as bj,Zq as bk,_o as bl,Ju as bm,_L as bn,eV as bo,sV as bp,tV as bq,Rq as br,Mq as bs,nV as bt,UR as bu,HR as bv,su as bw,Lx as bx,qq as c,lL as d,jy as e,Rs as f,_H as g,Ta as h,Kl as i,o as j,vS as k,Na as l,Tn as m,Nq as n,jq as o,Nf as p,zx as q,x as r,U as s,Tq as t,dt as u,Gb as v,Rt as w,GR as x,KR as y,Se 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=RN({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 sW=x.memo(function({onSaveSnapshot:e}={}){var xd,Ko,ti,yd,mc;const{t:n}=dt(["terminal","common"]),s=ed(),a=Ux(),r=t1(),i=Hx(),c=i1(),d=o1(),f=n1(),h=qx(),m=Vx(),b=cL(),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=(Qj(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=Wx(),O=x.useMemo(()=>{if(!T)return null;const Q=new Set,ue=[];for(const Me of E.values())Me.archived||Me.directories.length===0||Me.assignedAgentIds.includes(T)&&(Q.add(Me.id),ue.push(Me));const ce=s.get(T);if(ce)for(const Me of E.values())Me.archived||Me.directories.length===0||Q.has(Me.id)||eW({x:ce.position.x,z:ce.position.z},Me)&&(Q.add(Me.id),ue.push(Me));return ue.length===0?null:ue.flatMap(Me=>Me.directories.filter(nt=>nt&&nt.trim().length>0).map(nt=>({areaId:Me.id,areaName:Me.name,dir:nt})))},[T,E,s]),_=x.useMemo(()=>{var ce;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Me of I.values())Me.type==="terminal"&&U.isPositionInArea(Me.position,Q)&&ue.push({id:Me.id,name:Me.name,hasUrl:!!((ce=Me.terminalStatus)!=null&&ce.url)});return ue},[T,I,E]),M=x.useMemo(()=>{var ce;if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const Me of I.values())Me.type==="server"&&((ce=Me.pm2)!=null&&ce.enabled)&&U.isPositionInArea(Me.position,Q)&&ue.push({id:Me.id,name:Me.name});return ue},[T,I,E]),R=x.useMemo(()=>{if(!T)return[];const Q=U.getAreaForAgent(T);if(!Q)return[];const ue=[];for(const ce of I.values())ce.type==="database"&&ce.database&&U.isPositionInArea(ce.position,Q)&&ue.push({id:ce.id,name:ce.name});return ue},[T,I,E]),{branches:z,fetchRemote:$,fetchingDirs:W}=qH(O),{terminalHeight:L,terminalRef:F,handleResizeStart:H}=DH(),{mobileOverviewHeight:V,handleResizeMouseDown:G,handleResizeTouchStart:B}=LH(),K=MH(),[se,q]=x.useState(()=>{const Q=Dx(pt.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,Q))}),be=x.useRef(null),Ce=x.useCallback((Q,ue)=>{Q.preventDefault(),be.current={startX:Q.clientX,startW:se},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",U.setTerminalResizing(!0);let ce=se;const Me=ut=>{if(!be.current)return;const Nt=ut.clientX-be.current.startX,_t=ue==="left"?-Nt:Nt;ce=Math.max(280,Math.min(700,be.current.startW+_t)),q(ce)},nt=()=>{be.current=null,document.body.style.cursor="",document.body.style.userSelect="",U.setTerminalResizing(!1),document.removeEventListener("mousemove",Me),document.removeEventListener("mouseup",nt),Rx(pt.SIDE_PANEL_WIDTH,ce)};document.addEventListener("mousemove",Me),document.addEventListener("mouseup",nt)},[se]),Z=Xj(T),ie=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),Te=x.useRef(null),Ve=x.useRef(null),[We,ee]=x.useState(()=>{const Q=Fa(pt.VIEW_MODE);return Q==="simple"||Q==="chat"||Q==="advanced"?Q:Fa(pt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[ne,Ne]=x.useState(()=>Ni(pt.TERMINAL_FULLSCREEN,!1)),[ze,st]=x.useState(null),[pe,Be]=x.useState(null),[oe,de]=x.useState(null),[He,et]=x.useState(null),[ct,fe]=x.useState(!1);Xt("guake-image-modal",ze!==null,()=>st(null)),Xt("guake-bash-modal",pe!==null,()=>Be(null)),Xt("guake-response-modal",He!==null,()=>et(null)),Xt("guake-context-confirm",oe!==null,()=>de(null)),Xt("guake-agent-info",ct,()=>fe(!1));const[X,ae]=x.useState(!1),[ke,J]=x.useState(()=>vs.isEnabled()),[he,Oe]=x.useState(()=>Ni(pt.GIT_PANEL_OPEN,!1)),$e=x.useCallback(Q=>{Oe(Q),Ti(pt.GIT_PANEL_OPEN,Q)},[]),[xe,Pe]=x.useState(()=>Ni(pt.BUILDINGS_PANEL_OPEN,!1)),te=x.useCallback(Q=>{Pe(Q),Ti(pt.BUILDINGS_PANEL_OPEN,Q)},[]),[ge,ve]=x.useState(()=>Ni(pt.WORKFLOW_PANEL_OPEN,!1)),Fe=x.useCallback(Q=>{ve(Q),Ti(pt.WORKFLOW_PANEL_OPEN,Q)},[]),[Ke,at]=x.useState(!1);x.useEffect(()=>{if(!T){at(!1);return}let Q=!1;return(async()=>{try{const ue=await Bt(Rt("/api/workflows/definitions"));if(Q||!ue.ok)return;const Me=(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||at(Me)}catch{Q||at(!1)}})(),()=>{Q=!0}},[T]);const ft=mL(),wt=x.useCallback(Q=>U.setOverviewPanelOpen(Q),[]),[it,gt]=x.useState([]),[ht,Gt]=x.useState({}),[tn,Ae]=x.useState(()=>Yj()),[Le,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),[rt,xt]=x.useState(null),[$t,En]=x.useState(null),nn=x.useMemo(()=>it.filter(Q=>Q.areaId===$t),[it,$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(([ce,Me])=>[ce,Me.map(nt=>({id:nt.id??Xf(),type:nt.type,buildingId:nt.buildingId}))]))}else{const ue=localStorage.getItem("tide:bottom-terminals");if(ue){const ce=JSON.parse(ue);for(const[Me,nt]of ce)Os.current.set(Me,[{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(Me=>({id:Me.id,type:Me.type,buildingId:Me.buildingId}))):Os.current.delete(ue.id);const ce=Array.from(Os.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(ce))}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 ce=ks();Gt({}),gt(Me=>{for(const _t of Me)_t.areaId===ce&&_t.type==="pm2-logs"&&U.stopLogStreaming(_t.buildingId);const nt=Me.filter(_t=>_t.areaId!==ce),ut={id:Xf(),type:ue,buildingId:Q,areaId:ce??void 0},Nt=[...nt,ut];return ps([ut]),Nt})},[ps,ks]),Ss=x.useCallback((Q,ue,ce)=>{const Me=ks();Ye(ce);try{localStorage.setItem("tide:bottom-split-direction",ce)}catch{}gt(nt=>{const ut=nt.filter(sn=>sn.areaId===Me);if(ut.length>=4||ut.some(sn=>sn.buildingId===Q))return nt;const Nt={id:Xf(),type:ue,buildingId:Q,areaId:Me??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 ce={...ue};return delete ce[Q],ce}),gt(ue=>{const ce=ue.find(ut=>ut.id===Q);(ce==null?void 0:ce.type)==="pm2-logs"&&U.stopLogStreaming(ce.buildingId);const Me=ue.filter(ut=>ut.id!==Q),nt=ce==null?void 0:ce.areaId;return nt&&ps(Me.filter(ut=>ut.areaId===nt)),Me})},[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 Me=Os.current.get(Q.id);if(!Me||Me.length===0)return ue;const nt=Me.map(ut=>({id:ut.id,type:ut.type,buildingId:ut.buildingId,areaId:Q.id}));return[...ue,...nt]})},[T]),x.useEffect(()=>{const Q=ue=>{const ce=ue.detail;ce!=null&&ce.buildingId&&Qn(ce.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",Q),()=>window.removeEventListener("tide:open-bottom-terminal",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const ce=ue.detail;ce!=null&&ce.buildingId&&Qn(ce.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 ce=ue.detail;ce!=null&&ce.buildingId&&Qn(ce.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",Q),()=>window.removeEventListener("tide:open-bottom-database",Q)},[Qn]),x.useEffect(()=>{const Q=ue=>{const ce=ue.detail;ce!=null&&ce.buildingId&&(ce!=null&&ce.type)&&(ce!=null&&ce.direction)&&(nn.length===0?Qn(ce.buildingId,ce.type):Ss(ce.buildingId,ce.type,ce.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 ce=Le==="horizontal";ln.current={index:ue,startPos:ce?Q.clientX:Q.clientY,startRatios:[...Lt]},document.body.style.cursor=ce?"col-resize":"row-resize",document.body.style.userSelect="none";const Me=(sn=bt.current)==null?void 0:sn.querySelectorAll("iframe");Me==null||Me.forEach(gn=>gn.style.pointerEvents="none");const nt=bt.current,ut=nt?ce?nt.offsetWidth:nt.offsetHeight:1,Nt=gn=>{const qn=ln.current;if(!qn||!nt)return;const Qo=(ce?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="",Me==null||Me.forEach(gn=>gn.style.pointerEvents=""),document.removeEventListener("mousemove",Nt),document.removeEventListener("mouseup",_t)};document.addEventListener("mousemove",Nt),document.addEventListener("mouseup",_t)},[Le,Lt]),Is=x.useRef(new Set);x.useEffect(()=>{const Q=new Set(it.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},[it]);const wn=x.useRef(new Set);x.useEffect(()=>{var ce;const Q=it.filter(Me=>Me.type==="terminal");for(const Me of Q){const nt=I.get(Me.buildingId);!!((ce=nt==null?void 0:nt.terminalStatus)!=null&&ce.url)?wn.current.add(Me.buildingId):wn.current.has(Me.buildingId)&&(wn.current.delete(Me.buildingId),Fn(Me.id))}const ue=new Set(Q.map(Me=>Me.buildingId));for(const Me of wn.current)ue.has(Me)||wn.current.delete(Me)},[it,I,Fn]);const Po=x.useCallback(Q=>{Q.preventDefault(),Ft.current={startY:Q.clientY,startH:Ze};let ue=Ze;const ce=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)},Me=()=>{Ft.current=null,document.removeEventListener("mousemove",ce),document.removeEventListener("mouseup",Me);try{localStorage.setItem("tide:bottom-terminal-height",String(ue))}catch{}};document.addEventListener("mousemove",ce),document.addEventListener("mouseup",Me)},[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),[je,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 ce=Mt.current+Q;for(;ce>=0&&ce<ue.length;){const Me=ue[ce];if(s.has(Me)){At.current=!0,Mt.current=ce,ha(),U.selectAgent(Me);return}ce+=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 ce=window.history.state,nt={...typeof ce=="object"&&ce!==null?ce:{},__guakeAgentNav:{agentId:Q}};ue==="replace"?window.history.replaceState(nt,"",window.location.href):window.history.pushState(nt,"",window.location.href)},[]),Fo=x.useCallback(()=>{Ne(Q=>{const ue=!Q;return Ti(pt.TERMINAL_FULLSCREEN,ue),ue})},[]),It=qj({selectedAgentId:T,hasSessionId:D,reconnectCount:c,historyRefreshTrigger:d,lastPrompts:i,outputScrollRef:me}),Hn=IH({agents:s,selectedAgentId:T,isOpen:ot,overviewPanelOpen:ft,loadingHistory:It.fetchingHistory,hasModalOpen:!!(ze||pe||He||h||m),outputRef:me});x.useEffect(()=>{const Q=F.current;if(!Q||!ot)return;const ue=Me=>{Me.button===3?(Me.preventDefault(),Me.stopPropagation(),gr()):Me.button===4&&(Me.preventDefault(),Me.stopPropagation(),Ui())},ce=Me=>{(Me.button===3||Me.button===4)&&Me.preventDefault()};return Q.addEventListener("mouseup",ue),Q.addEventListener("mousedown",ce),()=>{Q.removeEventListener("mouseup",ue),Q.removeEventListener("mousedown",ce)}},[ot,gr,Ui]);const uc=x.useCallback(Q=>{U.setLastSelectionViaDirectClick(!0),U.selectAgent(Q)},[]),Xr=typeof window<"u"&&window.innerWidth<=768&&ft&&ot,Jr=nR({gestureRef:me,agentListRef:Ee,enabled:Xr,onSelect:uc}),ts=UH({selectedAgentId:k}),zo=QO(),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=sL(!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=aL(y?null:T),ud=hL(y?null:T);x.useEffect(()=>{X&&!ke&&(J(!0),vs.setEnabled(!0))},[X,ke]),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 ce=T?i.get(T):void 0;Bi(ce!=null&&ce.timestamp?Date.now()-ce.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 Me of Q)Me.type==="tool_result"&&Me.toolUseId&&ue.set(Me.toolUseId,Me.content);return(Me=>Me.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,We]),qi=ET({outputs:ie,viewMode:We}),Wa=x.useMemo(()=>{const Q=[],ue=new Set,ce=new Set;let Me=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=Mb(ut.content),_t=ut.uuid?`uuid:${ut.uuid}:${Nt}`:null;if(_t&&ce.has(_t))continue;const sn=ut.timestamp?new Date(ut.timestamp).getTime():0;Me===Nt&&Math.abs(sn-nt)<=YA||(Q.push(ut),_t&&ce.add(_t),Me=Nt,nt=sn)}return Q},[Wi]),Wn=x.useMemo(()=>{const Q=new Map,ue=new Set,ce=new Map;for(const Nt of Wa){const _t=Nt.timestamp?new Date(Nt.timestamp).getTime():0;if(Nt.type==="user"){const qn=Mb(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=ce.get(sn)??0;_t>gn&&ce.set(sn,_t)}const Me=[];let nt=null,ut=0;for(const Nt of qi){if(!Nt.isUserPrompt){if(!Nt.isStreaming&&!Z5(Nt.text)){if(Nt.uuid&&ue.has(Nt.uuid))continue;const qn=Qf(Nt.text),Va=Nt.timestamp||0,Qo=ce.get(qn);if(Qo&&Math.abs(Va-Qo)<=Q5)continue}Me.push(Nt);continue}const _t=Mb(Nt.text),sn=Nt.timestamp||0,gn=Q.get(_t);gn&&sn>=gn&&sn-gn<=K5||nt===_t&&Math.abs(sn-ut)<=YA||(Me.push(Nt),nt=_t,ut=sn)}return Me},[qi,Wa]),xr=x.useMemo(()=>[...Wa,...Wn],[Wa,Wn]),Ln=FH({selectedAgentId:T,isOpen:ot,allItems:xr,viewMode:We,hasMoreHistory:It.hasMore,loadAllHistory:It.loadAllHistory,loadingMore:It.loadingMore}),Vi=Wa.length+Wn.length,dd=HH({totalMessages:Vi,isOpen:ot,hasModalOpen:!!(ze||pe||He||h),scrollContainerRef:me,selectedAgentId:T,inputRef:Te,textareaRef:Ve,useTextarea:ts.useTextarea});x.useEffect(()=>{if(!(!(pe!=null&&pe.isLive)||!pe.command)){for(const Q of Wn)if(Q._bashCommand===pe.command&&Q._bashOutput){Be({command:pe.command,output:Q._bashOutput,isLive:!1});return}}},[pe,Wn]);const Ho=x.useCallback((Q,ue)=>{st({url:Q,name:ue})},[]),Wo=x.useCallback((Q,ue)=>{const ce=sh(Q,S==null?void 0:S.cwd),Me=ce.line?{...ue||{},targetLine:ce.line}:ue;U.setFileViewerPath(ce.path,Me,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(X5),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{U.setMobileView("3d"),fc(!1),ei(0)},J5))},[]),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 ce=ue<Q.length-1?Q.slice(0,ue+1):Q.slice();ce.push(T),ce.length>100&&ce.shift(),jn.current=ce,Mt.current=ce.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 ce=(Nt=(ut=ue.state)==null?void 0:ut.__guakeAgentNav)==null?void 0:Nt.agentId;if(!ce||typeof ce!="string"||!s.has(ce)||ce===k)return;kn.current=!0,At.current=!0;const Me=jn.current,nt=Me.lastIndexOf(ce);nt>=0?Mt.current=nt:(Me.push(ce),Mt.current=Me.length-1),ha(),U.selectAgent(ce)};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:ce}=me.current,Me=ue-Q-ce<150;Yo.current||(Yi.current=!Me,Me&&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 ce=performance.now();let Me=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?Me+=1:Me=0,nt=sn,Me>=3){hs(!1),ue=null;return}if(_t-ce>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 ce=ue.target;ce.tagName!=="INPUT"&&ce.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)):pe?(ue.stopImmediatePropagation(),Be(null)):ze?(ue.stopImmediatePropagation(),st(null)):Ln.searchMode&&(ue.stopImmediatePropagation(),Ln.closeSearch()))};return document.addEventListener("keydown",Q,!0),()=>document.removeEventListener("keydown",Q,!0)},[ze,pe,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},ce=nt=>{if(!bd.current){Gi.current=!1;return}if(JD("terminal")){Gi.current=!1;return}Gi.current=!ue(nt.target)},Me=nt=>{Gi.current&&(ue(nt.target)||U.setTerminalOpen(!1),Gi.current=!1)};return document.addEventListener("mousedown",ce,!0),document.addEventListener("mouseup",Me,!0),()=>{document.removeEventListener("mousedown",ce,!0),document.removeEventListener("mouseup",Me,!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 ${ne?"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 ${ne?"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 ce of ue){const Me=await ts.uploadFile(ce);Me&&ts.setAttachedFiles(nt=>[...nt,Me])}};return o.jsxs("div",{ref:F,className:`guake-terminal ${ot?"open":"collapsed"} ${ne&&ot?"fullscreen":""} ${X&&ot?"with-debug-panel":""} ${he&&ot?"with-git-panel":""} ${xe&&ot?"with-buildings-panel":""} ${ge&&ot?"with-workflow-panel":""} ${ft&&ot?"with-overview-panel":""} ${je?"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":`${se}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(l5,{agentId:T,onClose:()=>ae(!1)}),!y&&he&&ot&&T&&o.jsx(x5,{agentId:T,agents:s,onClose:()=>$e(!1),branchInfoMap:z,fetchRemote:$,fetchingDirs:W}),!y&&xe&&ot&&T&&o.jsx(R5,{agentId:T,onClose:()=>te(!1)}),!y&&ge&&ot&&T&&o.jsx(I5,{agentId:T,onClose:()=>Fe(!1)}),!y&&(X||he||xe||ge)&&ot&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:Q=>Ce(Q,"right")}),!y&&ft&&ot&&T&&o.jsx(E5,{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=>Ce(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(j6,{selectedAgent:S,selectedAgentId:T,sortedAgents:Hn.sortedAgents,swipeOffset:Hn.swipeOffset,viewMode:We,setViewMode:ee,searchMode:Ln.searchMode,toggleSearch:Ln.toggleSearch,closeSearch:Ln.closeSearch,debugPanelOpen:X,setDebugPanelOpen:ae,debuggerEnabled:ke,setDebuggerEnabled:J,gitPanelOpen:he,setGitPanelOpen:$e,buildingsPanelOpen:xe,setBuildingsPanelOpen:te,workflowPanelOpen:ge,setWorkflowPanelOpen:Fe,hasWorkflow:Ke,overviewPanelOpen:ft,setOverviewPanelOpen:wt,agentInfoOpen:ct,onToggleAgentInfo:fd,isFullscreen:ne,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(N6,{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&&ie.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(o5,{historyMessages:Wa,liveOutputs:Wn,agentId:T,execTasks:Uo,subagents:ud,viewMode:We,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(U5,{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(L6,{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:Te,textareaRef:Ve,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:ce})=>{const Me=z.get(ce),nt=W.has(ce);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${ue}: ${ce}${Me?` (${Me.branch}${Me.ahead?` ↑${Me.ahead}`:""}${Me.behind?` ↓${Me.behind}`:""})`:""}`,onClick:()=>U.openFileExplorerForAreaFolder(Q,ce),children:["📂 ",ce.split("/").filter(Boolean).pop()||ce,Me&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",Me.branch]}),Me.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${Me.ahead} ahead`,children:["↑",Me.ahead]}),Me.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${Me.behind} behind`,children:["↓",Me.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${nt?"fetching":""}`,title:"Git fetch",onClick:ut=>{ut.stopPropagation(),$(ce)},children:nt?"⏳":"⇣"})]})]},`${Q}:${ce}`)}),!y&&S&&(()=>{const Q=S.contextStats,ue=!!Q,ce=Q?Q.totalTokens:S.contextUsed||0,Me=Q?Q.contextWindow:S.contextLimit||2e5,nt=Q?Q.usedPercent:Math.round(ce/Me*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=(ce/1e3).toFixed(1),gn=(Me/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 ce=it.find(Me=>Me.buildingId===Q.id);ce&&Fn(ce.id)}else Q.hasUrl||U.sendBuildingCommand(Q.id,"start"),Qn(Q.id,"terminal")},onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),Un.has(Q.id)||xt({position:{x:ce.clientX,y:ce.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 ce=it.find(Me=>Me.buildingId===Q.id);ce&&Fn(ce.id)}else Qn(Q.id,"pm2-logs")},onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),Un.has(Q.id)||xt({position:{x:ce.clientX,y:ce.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 ce=it.find(Me=>Me.buildingId===Q.id);ce&&Fn(ce.id)}else Qn(Q.id,"database")},onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),Un.has(Q.id)||xt({position:{x:ce.clientX,y:ce.clientY},buildingId:Q.id,type:"database"})},children:"🗄️"},Q.id)})}),o.jsx(W5,{})]})]}),(()=>{const Q=[];return rt&&(Q.push({id:"open",label:"Open",icon:"⬇",onClick:()=>Qn(rt.buildingId,rt.type)}),nn.length>0&&(Q.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Ss(rt.buildingId,rt.type,"horizontal")}),Q.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Ss(rt.buildingId,rt.type,"vertical")}))),o.jsx(pr,{children:o.jsx(Do,{isOpen:rt!==null,position:(rt==null?void 0:rt.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 ${Le}`,style:{height:Ze},onWheel:Q=>Q.stopPropagation(),children:nn.map((Q,ue)=>{const ce=I.get(Q.buildingId);if(!ce)return null;const Me=Lt[ue]??1,nt=(()=>{var ut;if(Q.type==="terminal")return(ut=ce.terminalStatus)!=null&&ut.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ce.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(jx,{terminalUrl:ce.terminalStatus.url,visible:!0})]},Q.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",ce.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:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",ce.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 ${ce.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);Ae(sn),EO(sn)},"aria-label":`Max log retention for ${ce.name}`,children:_O.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(nW,{buildingId:Q.buildingId,filterText:Nt,maxRetention:tn})]},Q.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:Me},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",ce.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(EH,{building:ce})]},Q.id)})();return ue>0?o.jsxs(Se.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${Le}`,onMouseDown:ut=>Ls(ut,ue-1)}),nt]},Q.id):nt})})]}),it.filter(Q=>Q.areaId!==$t&&Q.type==="terminal").map(Q=>{var ce;const ue=I.get(Q.buildingId);return(ce=ue==null?void 0:ue.terminalStatus)!=null&&ce.url?o.jsx(jx,{terminalUrl:ue.terminalStatus.url,visible:!1},Q.id):null})]}),ot&&!ne&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:H,title:n("common:rightPanel.dragToResize")}),!(ot&&ne)&&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})]}),ze&&o.jsx(P6,{url:ze.url,name:ze.name,onClose:()=>st(null)}),pe&&o.jsx(B6,{state:pe,onClose:()=>Be(null)}),oe&&o.jsx(F6,{action:oe,selectedAgentId:T,subordinateCount:((mc=S==null?void 0:S.subordinateIds)==null?void 0:mc.length)||0,onClose:()=>de(null),onClearHistory:It.clearHistory}),o.jsx(z6,{}),o.jsx($6,{}),o.jsx(H6,{agent:S,isOpen:ct,onClose:()=>fe(!1)}),!y&&o.jsx(U6,{agent:S,content:He,onClose:()=>et(null)})]})});function aW(t){return t.trim().replace(/^v/i,"")}function GA(t){const n=aW(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 rW(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 iW(t,e){const n=GA(t),s=GA(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 rW(n.prerelease,s.prerelease)}function oW(t,e){const n=iW(t,e);return n===null?"unknown":n<0?"behind":n>0?"ahead":"equal"}async function lW(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 cW(t,e,n={}){const s=await lW(t,n);return s?{currentVersion:e,latestVersion:s,relation:oW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const uW="tide-commander",Db="1.40.3";function dW(){const[t,e]=x.useState({currentVersion:Db,latestVersion:null,relation:"unknown",isChecking:!1}),n=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await cW(uW,Db);e({currentVersion:Db,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return x.useEffect(()=>{n()},[n]),{...t,refresh:n}}const fW=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:Ex(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:_x(e.lastActivity)},title:Mx(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${n+1}`,children:["^",n+1]})]})}),pW=x.memo(function({onFocusAgent:e,onSpawnClick:n,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=dt(["common"]),c=ed(),d=ur(),f=Ux(),h=WO(),m=Hx(),b=Vr(),y=dr(),w=c1(),[C]=Fj(),[N,k]=x.useState(!1);Dj("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 ve=S.current;if(!ve)return;const Fe=Ke=>{ve.scrollWidth<=ve.clientWidth||(Ke.preventDefault(),Math.abs(Ke.deltaX)>Math.abs(Ke.deltaY)?ve.scrollLeft+=Ke.deltaX:ve.scrollLeft+=Ke.deltaY)};return ve.addEventListener("wheel",Fe,{passive:!1}),()=>ve.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,se=8,q=x.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),be=x.useMemo(()=>Array.from(c.values()).filter(ve=>{if(U.isAgentInArchivedArea(ve.id))return!1;if(C){const Fe=U.getAreaForAgent(ve.id);if(!zx((Fe==null?void 0:Fe.id)??null))return!1}return!0}).sort((ve,Fe)=>(ve.createdAt||0)-(Fe.createdAt||0)),[c,d,C]),{orderedAgents:Ce,moveAgent:Z}=mO(be),ie=Ce,me=x.useMemo(()=>{const ve=new Map;for(const Fe of ie)ve.set(Fe.id,U.getAreaForAgent(Fe.id));return ve},[ie,d]),Ee=x.useMemo(()=>{const ve=new Map;for(const Ke of ie){const at=me.get(Ke.id)||null,ft=(at==null?void 0:at.id)||null;ve.has(ft)||ve.set(ft,{area:at,agents:[]}),ve.get(ft).agents.push(Ke)}const Fe=Array.from(ve.values());return Fe.sort((Ke,at)=>{var ft,wt;return!Ke.area&&at.area?1:Ke.area&&!at.area?-1:!Ke.area&&!at.area?0:(((ft=Ke.area)==null?void 0:ft.name)||"").localeCompare(((wt=at.area)==null?void 0:wt.name)||"")}),Fe},[ie,me]),Te=x.useRef(e);Te.current=e;const Ve=x.useRef(M);Ve.current=M;const We=x.useRef(ie);We.current=ie;const ee=x.useRef(me);ee.current=me;const ne=x.useRef(Z);ne.current=Z,x.useEffect(()=>{const ve=new Map(O);let Fe=!1;for(const Ke of ie){const at=O.get(Ke.id);Ke.currentTool?(!at||at.tool!==Ke.currentTool)&&(ve.set(Ke.id,{tool:Ke.currentTool,key:Date.now()}),Fe=!0):at&&setTimeout(()=>{_(ft=>{const wt=new Map(ft);return wt.delete(Ke.id),wt})},1500)}Fe&&_(ve)},[ie.map(ve=>ve.currentTool).join(",")]),x.useEffect(()=>{const ve=h;if(!ve)return;const Fe=D.current.get(ve),Ke=S.current;Fe&&Ke&&requestAnimationFrame(()=>{const at=Fe.getBoundingClientRect(),ft=Ke.getBoundingClientRect(),it=at.left-ft.left+Ke.scrollLeft+at.width/2,gt=Ke.clientWidth;Ke.scrollTo({left:it-gt/2,behavior:"smooth"})})},[h]);const Ne=x.useCallback((ve,Fe)=>{if(G.current===ve.id){G.current=null,Fe.preventDefault(),Fe.stopPropagation();return}U.setLastSelectionViaDirectClick(!0),Fe.shiftKey?U.addToSelection(ve.id):U.selectAgent(ve.id),U.setTerminalOpen(!0)},[]),ze=x.useCallback(ve=>{var Fe;(Fe=Te.current)==null||Fe.call(Te,ve.id),U.setTerminalOpen(!0)},[]),st=x.useCallback(()=>I(null),[]),pe=x.useCallback((ve,Fe)=>{Fe?D.current.set(ve,Fe):D.current.delete(ve)},[]),Be=x.useCallback((ve,Fe)=>{R(Fe),F(Fe.id),ve.dataTransfer.effectAllowed="move",ve.dataTransfer.setData("text/plain",Fe.id),requestAnimationFrame(()=>{ve.target.classList.add("dragging")})},[]),oe=x.useCallback(ve=>{R(null),$(null),F(null),W.current=0,ve.target.classList.remove("dragging")},[]),de=x.useCallback((ve,Fe)=>{ve.preventDefault();const Ke=Ve.current;if(Ke){const at=ee.current.get(Ke.id),ft=We.current[Fe],wt=ft?ee.current.get(ft.id):null,it=(at==null?void 0:at.id)??null,gt=(wt==null?void 0:wt.id)??null;ve.dataTransfer.dropEffect=it===gt?"move":"none"}else ve.dataTransfer.dropEffect="move"},[]),He=x.useCallback((ve,Fe)=>{ve.preventDefault(),W.current++;const Ke=Ve.current;if(Ke){const at=ee.current.get(Ke.id),ft=We.current[Fe],wt=ft?ee.current.get(ft.id):null,it=(at==null?void 0:at.id)??null,gt=(wt==null?void 0:wt.id)??null;$(it===gt?Fe:null)}else $(Fe)},[]),et=x.useCallback(ve=>{W.current--,W.current===0&&$(null)},[]),ct=x.useCallback((ve,Fe)=>{ve.preventDefault();const Ke=Ve.current;if(!Ke)return;const at=We.current,ft=ee.current,wt=at.findIndex(it=>it.id===Ke.id);if(wt!==-1&&wt!==Fe){const it=ft.get(Ke.id),gt=at[Fe],ht=gt?ft.get(gt.id):null,Gt=(it==null?void 0:it.id)??null,tn=(ht==null?void 0:ht.id)??null;Gt===tn&&ne.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)},[]),ae=x.useCallback((ve,Fe)=>{if(!q||ve.touches.length!==1)return;fe(),X(),F(null);const Ke=ve.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]),ke=x.useCallback(ve=>{if(!q||ve.touches.length!==1)return;const Fe=V.current;if(!Fe||!H.current)return;const Ke=ve.touches[0],at=Ke.clientX-Fe.x,ft=Ke.clientY-Fe.y;Math.sqrt(at*at+ft*ft)>se&&(fe(),V.current=null)},[fe,q]),J=x.useCallback(()=>{fe(),V.current=null,Ve.current||F(null),X(),B.current=setTimeout(()=>{G.current=null,B.current=null},450)},[fe,X]);x.useEffect(()=>()=>{fe(),X()},[fe,X]);const he=ve=>{const Fe=`common:status.${ve}`;return i(Fe,{defaultValue:i("common:status.unknown")})},{currentVersion:Oe,latestVersion:$e,relation:xe,isChecking:Pe}=dW(),te=Oe;let ge=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]}),xe==="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]}):xe==="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,xe==="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)"})}):xe==="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)"})}):xe==="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")}):Pe?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:Hj,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(ve=>{var at,ft,wt,it,gt;const Fe=ve.agents,Ke=!ve.area;return o.jsxs("div",{className:`agent-bar-group ${Ke?"unassigned":""}`,style:{borderColor:((at=ve.area)==null?void 0:at.color)||void 0,background:ve.area?`${ve.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=ve.area)==null?void 0:ft.color)||"#888"},children:((wt=ve.area)==null?void 0:wt.name)||i("common:agentBar.unassigned")})}),((it=ve.area)==null?void 0:it.directories)&&ve.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:ve.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=ge++,tn=ie.findIndex(Ae=>Ae.id===ht.id);return o.jsx(fW,{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:oe,onDragOver:de,onDragEnter:He,onDragLeave:et,onDrop:ct,onAgentClick:Ne,onAgentDoubleClick:ze,onTouchStart:ae,onTouchMove:ke,onTouchEnd:J,onTouchCancel:J,onHoverEnter:I,onHoverLeave:st,onItemRef:pe},ht.id)})]},((gt=ve.area)==null?void 0:gt.id)||"unassigned")})]})]}),Array.from(O.entries()).map(([ve,Fe])=>{const Ke=D.current.get(ve);if(!Ke)return null;const at=Ke.getBoundingClientRect(),ft=fs[Fe.tool]||fs.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:Fe.tool,style:{position:"fixed",left:at.left+at.width/2,bottom:window.innerHeight-at.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-${ve}-${Fe.key}`)}),E&&(()=>{const ve=U.getAreaForAgent(E.id),Fe=m.get(E.id),Ke=fr(E.class,y),at=U.getAgentSupervisorHistory(E.id),ft=at.length>0?at[at.length-1]:void 0,wt=Date.now()-(E.createdAt||Date.now()),it=Math.floor(wt/6e4),gt=Math.floor(it/60),ht=gt>0?`${gt}h ${it%60}m`:`${it}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,Ae=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"}},Le=D.current.get(E.id),Ye={};if(Le){const Ze=Le.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":E.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:E.provider,className:"agent-bar-provider-icon",title:E.provider==="codex"?"Codex Agent":E.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),E.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Ex(E.status)},children:he(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]})]}),ve&&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:ve.color},children:ve.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:Ae(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 hW({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 mW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Rb=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),gW=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"}},bW=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:Ex(e.status)},children:a(mW[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:[Rb(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:[Rb(e.contextUsed)," / ",Rb(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:gW(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 KA(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 QA(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 XA={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 xW(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:XA[c]&&(a=XA[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 yW=x.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var F,H,V,G,B,K,se,q,be,Ce,Z,ie,me,Ee,Te,Ve,We,ee,ne,Ne;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(ze=>{ze.preventDefault();const st=C.current?C.current.x:0,pe=C.current?C.current.y:0;w.current={mouseX:ze.clientX,mouseY:ze.clientY,popupX:st,popupY:pe},y(!0),T.current=Be=>{if(!w.current)return;const oe=Be.clientX-w.current.mouseX,de=Be.clientY-w.current.mouseY;m({x:w.current.popupX+oe,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=ze=>{if(ze==="logs"){if((j||S)&&r){r();return}U.sendBuildingCommand(e.id,ze),f(!0)}else U.sendBuildingCommand(e.id,ze)},O=(ze,st)=>{if(ze){const pe=`http://localhost:${ze}`;st&&i?i(pe):window.open(pe,"_blank")}},_=((V=e.pm2Status)==null?void 0:V.ports)||[],M=((B=(G=e.dockerStatus)==null?void 0:G.ports)==null?void 0:B.map(ze=>ze.host))||[],R=j?_:S?M:[],z=j?!!((K=e.pm2)!=null&&K.script):S?!!((se=e.docker)!=null&&se.image)||((q=e.docker)==null?void 0:q.mode)==="compose"||((be=e.docker)==null?void 0:be.mode)==="existing":!!((Ce=e.commands)!=null&&Ce.start),$=j?!!((Z=e.pm2)!=null&&Z.script):S?!0:!!((ie=e.commands)!=null&&ie.stop),W=j?!!((me=e.pm2)!=null&&me.script):S?!0:!!((Ee=e.commands)!=null&&Ee.restart),L=x.useMemo(()=>{const st=d?400:250;let pe=n.x+20,Be=n.y-80;return typeof window<"u"&&!h&&(n.x+20+280>window.innerWidth&&(pe=n.x-280-20),n.y-80<0?Be=10:n.y-80+st>window.innerHeight&&(Be=window.innerHeight-st-10)),{position:"fixed",left:pe+((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:ze=>ze.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(ze=>o.jsxs("a",{href:`http://localhost:${ze}`,className:"building-popup-port-link",onClick:st=>{st.preventDefault(),st.stopPropagation(),O(ze,st.altKey)},onMouseDown:st=>st.stopPropagation(),title:`Open http://localhost:${ze} (Alt+Click for modal)`,children:[":",ze]},ze))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:Vb[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:[((Te=e.pm2Status.cpu)==null?void 0:Te.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:KA(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:QA(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:KA(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:QA(e.dockerStatus.startedAt)})]})]}),S&&((Ve=e.dockerStatus)==null?void 0:Ve.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((ze,st)=>o.jsxs("span",{className:"service-item",title:`${ze.name}: ${ze.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:ze.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:ze.name})]},st))}),(e.lastError||j&&((We=e.pm2Status)==null?void 0:We.status)==="errored"||S&&((ee=e.dockerStatus)==null?void 0:ee.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),j&&((ne=e.pm2Status)==null?void 0:ne.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),S&&((Ne=e.dockerStatus)==null?void 0:Ne.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:ze=>O(R[0],ze.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(ze=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:st=>O(ze,st.altKey),title:`Open http://localhost:${ze} (Alt+Click for modal)`,children:[":",ze]},ze))]})]}),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((ze,st)=>o.jsx("pre",{children:xW(ze)},st))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function vW(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 wW(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 kW=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:Vb[_]||"#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:Vb[_.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),"% | ",vW(_.pm2Status.memory||0)]}),((z=_.pm2Status)==null?void 0:z.uptime)&&o.jsx("span",{className:"sub-uptime",children:wW(_.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")})]})}),SW=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=Gx(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=wL[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 CW({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 ie=setInterval(Z,w?3e3:1e4);return()=>clearInterval(ie)},[t,w]),x.useEffect(()=>{if(!t)return;const Z=su.getUsage();Z&&M===null&&R(Z.usedMB);const ie=setInterval(()=>{var st,pe;Nf.update();const me=Nf.getStats();s(me.current),r(Be=>[...Be,me.current].slice(-60));const Ee=su.getUsage();Ee&&c(Ee);const Te=window.__tideScene;if(Te){const Be=(st=Te.getMemoryDiagnostics)==null?void 0:st.call(Te);Be!=null&&Be.threeJs&&m(Be.threeJs);const oe=Te.renderer;if((pe=oe==null?void 0:oe.info)!=null&&pe.memory){const de=oe.info.memory.textures||0,He=Math.round(de*1);I({count:de,estimatedMB:He})}}const Ve=document.getElementsByTagName("*"),We=document.getElementsByTagName("canvas"),ee=document.getElementsByTagName("img"),ne=document.getElementsByTagName("video");let Ne=0;for(let Be=0;Be<Math.min(Ve.length,500);Be++){const oe=Ve[Be];oe.onclick&&Ne++,oe.onmousedown&&Ne++,oe.onkeydown&&Ne++}Ne+=10,S({nodeCount:Ve.length,listenerCount:Ne,canvasCount:We.length,imageCount:ee.length,videoCount:ne.length}),Ee&&f(Be=>{const oe=L.current,de={timestamp:Date.now(),heapMB:Ee.usedMB,geometries:(oe==null?void 0:oe.geometries)??0,textures:(oe==null?void 0:oe.textures)??0};return[...Be,de].slice(-120)});const ze=W.current;if(ze.length>=10){const Be=ze[0],oe=ze[ze.length-1],de=(oe.timestamp-Be.timestamp)/1e3/60;de>.1&&y((oe.heapMB-Be.heapMB)/de)}},1e3);return()=>{clearInterval(ie)}},[t,M]),!t)return null;const F=Z=>{const ie=Math.floor(Z/3600),me=Math.floor(Z%3600/60),Ee=Z%60;return ie>0?`${ie}h ${me}m`:me>0?`${me}m ${Ee}s`:`${Ee}s`},H=Z=>Z>=55?"#4aff9e":Z>=30?"#ffcc00":"#ff4a4a",V=(Z,ie)=>{const me=Z/ie;return me<.5?"#4aff9e":me<.8?"#ffcc00":"#ff4a4a"},G=Z=>Z===null?"#888":Z<1?"#4aff9e":Z<5?"#ffcc00":"#ff4a4a",B=Nf.getStats(),se=O<=768?80:10,q={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:se,left:10},"bottom-right":{bottom:se,right:10}},be=M&&i?i.usedMB-M:0,Ce=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:Ce("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:Ce("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:Ce("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:Ce("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:Ce("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:Ce("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,ie)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,Z/60*100)}%`,background:H(Z),opacity:.8}},ie))})]})]}),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:be>50?"#ff4a4a":be>20?"#ffcc00":"#4aff9e"},children:[be>0?"+":"",be," 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,ie)=>{const me=Math.min(...d.map(We=>We.heapMB)),Te=Math.max(...d.map(We=>We.heapMB))-me||1,Ve=(Z.heapMB-me)/Te*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,Ve)}%`,background:Z.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${Z.heapMB}MB`},ie)})})]}),$.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,ie)=>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"]})]},ie))})]})]}),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,ie)=>{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`},ie)})})]}),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 ie=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&ie.push("","--- Memory ---",`Heap Used: ${i.usedMB} MB`,`Heap Total: ${i.totalMB} MB`,`Heap Limit: ${i.limitMB} MB`,`Baseline: ${M??"N/A"} MB`,`Growth: ${be>0?"+":""}${be} MB`,`Growth Rate: ${b!==null?`${b.toFixed(2)} MB/min`:"N/A"}`),h&&ie.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),$.agentCount>0&&(ie.push("","--- Agent Memory ---",`Total: ${$.totalMB} MB`,`Agents: ${$.agentCount}`),$.agents.slice(0,5).forEach(Ee=>{ie.push(` ${Ee.name}: ${Ee.memoryMB} MB (${Ee.status})`)})),j&&ie.push("","--- DOM ---",`DOM Nodes: ${j.nodeCount.toLocaleString()}`,`Canvases: ${j.canvasCount}`,`Images: ${j.imageCount}`,`Videos: ${j.videoCount}`),E&&ie.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&&(ie.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&&(ie.push("","--- Agent Processes ---",`Total: ${T.agents.total} (${T.agents.working} working, ${T.agents.idle} idle)`),T.agents.processes.forEach(Ee=>{ie.push(` ${Ee.name}: ${Ee.memoryMB!=null?`${Ee.memoryMB}MB`:"N/A"} (${Ee.status})${Ee.pid?` PID:${Ee.pid}`:""}`)})));const me=ie.join(`
|
|
152
|
+
`);navigator.clipboard.writeText(me).then(()=>{const Ee=Z.currentTarget,Te=Ee.textContent;Ee.textContent="Copied!",setTimeout(()=>{Ee.textContent=Te},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 ie=window.__tideScene;ie!=null&&ie.logMemoryDiagnostics&&ie.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(),Jb.clear(),Nf.reset(),su.reset(),r([]),f([]);const ie=su.getUsage();ie&&R(ie.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 AW(){const t=l1(),e=x.useCallback(n=>{U.setViewMode(n)},[]);return[t,e]}const jW=["3d","2d","dashboard"],NW=x.memo(function({className:e=""}){const{t:n}=dt(["common"]),[s,a]=AW(),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}}),jW.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 ZT({className:t}){const{t:e}=dt(["terminal"]),[n,s]=x.useState(!1),[a,r]=x.useState(null),i=Dy(),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=HT({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 TW=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(ZT,{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:"📸"})]})]})}),_W=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(ZT,{}),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"})]})})})]})}),EW=Se.lazy(()=>vt(()=>import("./SpawnModal-CHALHOLz.js"),__vite__mapDeps([17,3,1,4])).then(t=>({default:t.SpawnModal}))),MW=Se.lazy(()=>vt(()=>import("./BossSpawnModal-DibwTCub.js"),__vite__mapDeps([18,3,1,4])).then(t=>({default:t.BossSpawnModal}))),DW=Se.lazy(()=>vt(()=>import("./SubordinateAssignmentModal-DBZsFe-S.js"),__vite__mapDeps([19,3,1,4])).then(t=>({default:t.SubordinateAssignmentModal}))),RW=Se.lazy(()=>vt(()=>import("./index-CEZ1e3Of.js"),__vite__mapDeps([20,3,1,4,21])).then(t=>({default:t.Toolbox}))),OW=Se.lazy(()=>vt(()=>import("./index-BvYoT0dH.js"),__vite__mapDeps([22,3,1,4])).then(t=>({default:t.BuildingConfigModal}))),LW=Se.lazy(()=>vt(()=>import("./index-DAOIgllP.js"),__vite__mapDeps([23,24,3,1,4])).then(t=>({default:t.CommanderView}))),IW=Se.lazy(()=>vt(()=>import("./SupervisorPanel-NYoLg7_B.js"),__vite__mapDeps([25,3,1,4])).then(t=>({default:t.SupervisorPanel}))),PW=Se.lazy(()=>vt(()=>import("./index-CqZxf78s.js").then(t=>t.y),[]).then(t=>({default:t.FileExplorerPanel}))),BW=Se.lazy(()=>vt(()=>import("./index-CTINc_P-.js"),__vite__mapDeps([26,3,1,4])).then(t=>({default:t.Spotlight}))),FW=Se.lazy(()=>vt(()=>import("./ControlsModal-Bd5SZVzZ.js"),__vite__mapDeps([27,3,1,4])).then(t=>({default:t.ControlsModal}))),zW=Se.lazy(()=>vt(()=>import("./SkillsPanel-1Msh9dAe.js"),__vite__mapDeps([28,3,1,4])).then(t=>({default:t.SkillsPanel}))),$W=Se.lazy(()=>vt(()=>Promise.resolve().then(()=>S2),void 0).then(t=>({default:t.AgentEditModal}))),UW=Se.lazy(()=>vt(()=>import("./SnapshotManager-DQ6jkxDW.js"),__vite__mapDeps([29,3,1,4])).then(t=>({default:t.SnapshotManager}))),HW=Se.lazy(()=>vt(()=>import("./RestoreArchivedAreaModal-COSiM8Fi.js"),__vite__mapDeps([30,3,1,4])).then(t=>({default:t.RestoreArchivedAreaModal}))),WW=Se.lazy(()=>vt(()=>import("./IntegrationsPanel-C1ktSqvl.js"),__vite__mapDeps([31,3,1,4])).then(t=>({default:t.IntegrationsPanel}))),qW=Se.lazy(()=>vt(()=>import("./MonitoringModal-DOaMyrjA.js"),__vite__mapDeps([32,3,1,4])).then(t=>({default:t.MonitoringModal}))),VW=Se.lazy(()=>vt(()=>import("./WorkflowEditorPanel-BMpT0GGS.js"),__vite__mapDeps([33,3,1,4])).then(t=>({default:t.WorkflowEditorPanel}))),YW=Se.lazy(()=>vt(()=>import("./TriggerManagerPanel-CNhhmDvm.js"),__vite__mapDeps([34,3,1,4])).then(t=>({default:t.TriggerManagerPanel})));function GW({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:se,onSyncScene:q}){const be=Rs(),Ce=Array.from(be.snapshots.values()),Z=be.snapshotsLoading;be.currentSnapshot,x.useEffect(()=>{N.isOpen&&U.fetchSnapshots()},[N.isOpen]);const ie=W==="selected",me=W&&W!=="selected"?be.buildings.get(W):null,Ee=be.selectedBuildingIds.size;return o.jsxs(x.Suspense,{fallback:null,children:[o.jsx(RW,{config:_,onConfigChange:M,onToolChange:R,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:Te=>w.open(Te||null),onOpenAreaExplorer:z,onOpenIntegrationsModal:Te=>h.open(Te),onOpenMonitoringModal:()=>m.open(),onOpenWorkflowEditor:()=>b.open(),onOpenTriggerManager:()=>y.open()}),o.jsx(OW,{isOpen:w.isOpen,onClose:w.close,buildingId:w.data,initialPosition:O||void 0}),o.jsx(EW,{isOpen:t.isOpen,onClose:t.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T,spawnAreaId:D}),o.jsx(MW,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:T}),o.jsx(DW,{isOpen:n.isOpen,bossId:n.data||"",onClose:n.close}),C.isOpen&&C.data&&(()=>{const Te=be.agents.get(C.data);return Te?o.jsx($W,{agent:Te,isOpen:C.isOpen,onClose:C.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:Te=>{Te.key==="Escape"&&r.close(),Te.key==="Enter"&&$()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Te=>Te.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 ",be.selectedAgentIds.size," selected agent",be.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||ie)&&o.jsx("div",{className:"modal-overlay visible",onClick:L,onKeyDown:Te=>{Te.key==="Escape"&&L(),Te.key==="Enter"&&F()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Te=>Te.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",ie&&Ee>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[ie?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",ie&&Ee>1?"s":""," and ",ie&&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:Te=>{Te.key==="Escape"&&V()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:Te=>Te.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(LW,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(IW,{isOpen:i.isOpen,onClose:i.close}),o.jsx(PW,{isOpen:j.isOpen||E!==null||be.explorerAreaId!==null,areaId:j.id||be.explorerAreaId||null,folderPath:E,onChangeArea:Te=>j.open(Te),onClose:()=>{j.close(),U.closeFileExplorer()}}),o.jsx(BW,{isOpen:c.isOpen,onClose:c.close,onOpenSpawnModal:()=>t.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenSupervisor:()=>i.open(),onOpenFileExplorer:Te=>j.open(Te),onOpenPM2LogsModal:B,onOpenBossLogsModal:K,onOpenDatabasePanel:se,onOpenMonitoringModal:()=>m.open()}),o.jsx(FW,{isOpen:d.isOpen,onClose:d.close}),o.jsx(zW,{isOpen:f.isOpen,onClose:f.close}),o.jsx(WW,{isOpen:h.isOpen,onClose:h.close,initialTab:h.data}),o.jsx(qW,{isOpen:m.isOpen,onClose:m.close}),o.jsx(VW,{isOpen:b.isOpen,onClose:b.close}),o.jsx(YW,{isOpen:y.isOpen,onClose:y.close}),o.jsx(HW,{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:Te=>Te.stopPropagation(),children:o.jsx(UW,{snapshots:Ce,isLoading:Z,onViewSnapshot:async Te=>{await U.loadSnapshot(Te),be.selectedAgentIds.clear(),U.setTerminalOpen(!0),N.close()},onDeleteSnapshot:async Te=>{await U.deleteSnapshot(Te),await U.fetchSnapshots()},onRestoreSnapshot:async Te=>{await U.restoreFiles(Te)},onExportSnapshot:async Te=>{await U.loadSnapshot(Te),N.close()},onClose:N.close})})}),o.jsx(Do,{isOpen:S.isOpen,position:S.screenPosition,worldPosition:S.worldPosition,actions:I,onClose:S.close})]})}function KW({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 Ly(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 Iy(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 Py(t){const e=_o[t.class];return(e==null?void 0:e.icon)||"🤖"}function Ob({agent:t,onClick:e}){const n=Iy(t.status),s=Ly(t.status),a=Py(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 JA={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},ZA={systemPrompt:"System Prompt",systemTools:"System Tools",messages:"Messages",freeSpace:"Free Space",autocompactBuffer:"Autocompact Buffer"};function QW({agent:t,onBack:e}){const n=Py(t),s=Iy(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:Ly(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:JA[d]},title:`${ZA[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:JA[d]}}),o.jsxs("div",{className:"pip-category-info",children:[o.jsx("div",{className:"pip-category-name",children:ZA[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 XW({agentId:t,onBack:e}){const n=Qj(t),s=Xj(t),a=i1(),r=o1(),i=Hx(),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=qj({selectedAgentId:t,hasSessionId:w,reconnectCount:a,historyRefreshTrigger:r,lastPrompts:i,outputScrollRef:c}),N=ET({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=Py(n),z=Iy(n.status);return m?o.jsx(QW,{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:Ly(n.status)})]}),o.jsx("div",{className:"pip-context-section",children:o.jsx(v1,{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(XT,{message:$,agentId:t,simpleView:!0,onFileClick:M},`h-${W}`)),N.map(($,W)=>o.jsx(Ry,{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 JW({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(Ob,{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(Ob,{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(Ob,{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 ZW(){const[t,e]=x.useState(null),n=a=>{e(a)},s=()=>{e(null)};return t?o.jsx(XW,{agentId:t,onBack:s}):o.jsx(JW,{onSelectAgent:n})}function eq(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 tq(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 nq=4e3;function sq(){const t=Zj(),[e,n]=x.useState(!1),[s,a]=x.useState(!1),[r,i]=x.useState(!0),[c,d]=x.useState(()=>Ox()),[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(()=>YD(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=()=>nq-(Date.now()-D);b(null),w("Validating URL");const I=c.trim()||"http://localhost:6200",O=eq(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 tq(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}VD(O.normalizedUrl),w("Connecting to server"),$R();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 ej="tide-onboarding-dismissed";function aq({onCreateAgent:t}){const{t:e}=dt("common"),n=Zj(),s=Kj(),[a,r]=x.useState(()=>sessionStorage.getItem(ej)==="1"),i=n&&!a&&s===0,c=x.useCallback(()=>{r(!0),sessionStorage.setItem(ej,"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 e_(){return{"Content-Type":"application/json","X-Auth-Token":Ii()}}async function rq(t){const e=await fetch(`${Ea()}/api/areas/${t}/organize`,{method:"POST",headers:e_()});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 iq(){const t=await fetch(`${Ea()}/api/areas/organize-all`,{method:"POST",headers:e_()});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 t_(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 oq(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,position:{x:d.center.x,z:d.center.z}}}))}}),i.push({id:"divider-area-layer",label:"",divider:!0,onClick:()=>{}}),i.push({id:"bring-to-front",label:"Bring to Front",icon:"⬆️",onClick:()=>{var f;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:()=>{rq(e.id).then(f=>{t_(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 lq=Se.lazy(()=>vt(()=>import("./index-CSOx3Jk0.js"),__vite__mapDeps([35,3,1,4,36])).then(t=>({default:t.DatabasePanel}))),cq=Se.lazy(()=>vt(()=>import("./PM2LogsModal-D-Gq8l2H.js"),__vite__mapDeps([37,38,3,1,4])).then(t=>({default:t.PM2LogsModal}))),uq=Se.lazy(()=>vt(()=>import("./DockerLogsModal-DWzJq-fY.js"),__vite__mapDeps([39,38,3,1,4])).then(t=>({default:t.DockerLogsModal}))),dq=Se.lazy(()=>vt(()=>import("./BossLogsModal-5ehRTeGs.js"),__vite__mapDeps([40,38,3,1,4])).then(t=>({default:t.BossLogsModal}))),fq=Se.lazy(()=>vt(()=>import("./Scene2DCanvas-4ByVcSoi.js"),__vite__mapDeps([41,3,1,4,42])).then(t=>({default:t.Scene2DCanvas}))),pq=Se.lazy(()=>vt(()=>import("./index-CDKrcnoB.js"),__vite__mapDeps([43,3,1,4,44])).then(t=>({default:t.DashboardView}))),hq=Se.lazy(()=>vt(()=>import("./IframeModal-Cz8quXPm.js"),__vite__mapDeps([45,3,1,4,46])).then(t=>({default:t.IframeModal}))),mq=Se.lazy(()=>vt(()=>import("./SaveSnapshotModal-DxwK-i0L.js"),__vite__mapDeps([47,3,1,4])).then(t=>({default:t.SaveSnapshotModal})));function gq(){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=GD(),I=ZO(),O=KD(),_=iR(),[M,R]=x.useState(null),z=QR(),[$,W]=x.useState(!1),[L,F]=x.useState(null),[H,V]=x.useState(null),[G,B]=x.useState(null),[K,se]=x.useState(null),[q,be]=x.useState(null),[Ce,Z]=x.useState(null),[ie,me]=x.useState(null),[Ee,Te]=x.useState(null),[Ve,We]=x.useState(null),[ee,ne]=x.useState(null),Ne=x.useCallback(je=>{ne(je),je&&localStorage.setItem("tide-commander-last-database-building",je)},[]),ze=x.useCallback(()=>Ne(null),[Ne]),{handleMouseDown:st,handleClick:pe}=Ta(ze),Be=x.useCallback(()=>We(null),[]),{handleMouseDown:oe,handleClick:de}=Ta(Be),He=x.useRef(Ce);He.current=Ce;const et=x.useCallback(je=>{Z(je)},[]),ct=x.useCallback(()=>He.current,[]),fe=x.useRef(null),[X,ae]=x.useState(Uj),[ke,J]=x.useState(0),[he,Oe]=x.useState(!1),[$e,xe]=x.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[Pe,te]=x.useState(!1),[ge,ve]=x.useState(!1),Fe=n1(),Ke=l1(),at=qx(),ft=Vx(),wt=t1(),{showToast:it}=d1(),{showAgentNotification:gt}=jL(),{showBackNavModal:ht,setShowBackNavModal:Gt,handleLeave:tn}=hO();oO({showToast:it,showAgentNotification:gt});const[Ae,Le]=x.useState(!1);x.useEffect(()=>{const je=Je=>{var ot;((ot=Je.detail)==null?void 0:ot.mode)==="3d"&&Le(!0)};return window.addEventListener("tide:viewmode-switch-pressed",je),()=>{window.removeEventListener("tide:viewmode-switch-pressed",je)}},[]),x.useEffect(()=>{Ke==="3d"&&Le(!0)},[Ke]);const Ye=iO({canvasRef:e,selectionBoxRef:n,viewMode:Ke,sceneMountKey:ke,showToast:it,showAgentNotification:gt,toolboxModal:i,contextMenu:O,setHoveredAgentPopup:be,setBuildingPopup:et,getBuildingPopup:ct,openBuildingModal:je=>k.open(je),openPM2LogsModal:je=>me(je),openBossLogsModal:je=>Te(je),openDatabasePanel:je=>Ne(je),onSceneLoadingChange:Le}),Ze=Kj(),Ot=ur(),Ft=Wx(),Lt=Ux(),Vt=YO(),ln=VO(),bt=qO(),rt=Vr(),xt=KO(),$t=uL(),En=dL(),nn=x.useMemo(()=>Array.from(Lt),[Lt]),Un=x.useRef(!1);Dj("AppContent"),lO(Ye),cO(Ye),uO(Ye),bO(),dO(Ye,ln),fO(Ye,rt.powerSaving),x.useEffect(()=>{var je;document.title=((je=rt.tabTitle)==null?void 0:je.trim())||"Tide Commander"},[rt.tabTitle]),x.useEffect(()=>{var Dn,Fs;if(Un.current||typeof window>"u")return;const je=new URLSearchParams(window.location.search),Je=(Dn=je.get("agentId"))==null?void 0:Dn.trim(),Ct=(Fs=je.get("agentName"))==null?void 0:Fs.trim();if(!Je&&!Ct||Ze===0)return;const ot=U.getState().agents,jn=je.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),je.delete("agentId"),je.delete("agentName"),je.delete("openTerminal");const kn=je.toString(),ms=`${window.location.pathname}${kn?`?${kn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,ms),Un.current=!0},[Ze]),pO({sceneRef:Ye,spawnModal:s,commanderModal:c,explorerModal:E,spotlightModal:h,deleteConfirmModal:d,onRequestBuildingDelete:()=>se("selected"),onOpenDatabasePanel:Ne,onCloseDatabasePanel:ze,databasePanelOpen:ee!==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",he,()=>Oe(!1)),Xt("mobile-fab-menu",ge,()=>ve(!1)),Xt("file-viewer",at!==null,()=>U.clearFileViewerPath()),Xt("context-modal",ft!==null,()=>U.closeContextModal()),Xt("terminal",wt,()=>U.setTerminalOpen(!1)),Xt("pm2-logs-modal",ie!==null,()=>me(null)),Xt("boss-logs-modal",Ee!==null,()=>Te(null)),Xt("database-panel",ee!==null,ze),Xt("terminal-modal",Ve!==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 je=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(je)},[Fe,Ke]);const Qn=x.useCallback(je=>{var Je,Ct,ot,jn,Mt,At,kn,ms,Dn,Fs;ae(je),aO(je),(Je=Ye.current)==null||Je.setCharacterScale(je.characterScale),(Ct=Ye.current)==null||Ct.setScale3D(je.scale3d),(ot=Ye.current)==null||ot.setTimeMode(je.timeMode),(jn=Ye.current)==null||jn.setTerrainConfig(je.terrain),(Mt=Ye.current)==null||Mt.setFloorStyle(je.terrain.floorStyle),(At=Ye.current)==null||At.setGridVisible(je.gridVisible),(kn=Ye.current)==null||kn.setAgentModelStyle(je.modelStyle),(ms=Ye.current)==null||ms.setIdleAnimation(je.animations.idleAnimation),(Dn=Ye.current)==null||Dn.setWorkingAnimation(je.animations.workingAnimation),(Fs=Ye.current)==null||Fs.setFpsLimit(je.fpsLimit)},[Ye]),Ss=x.useCallback(je=>{var Je;if((Je=Ye.current)==null||Je.setDrawingTool(je),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(je),je==="rectangle"||je==="circle"){const Ct=t(je==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");it("info",Ct,t("notifications:drawing.clickAndDrag"),3e3)}},[Ye,it]),Fn=x.useCallback(je=>{var Je;(Je=Ye.current)==null||Je.focusAgent(je)},[Ye]),Ls=x.useCallback(je=>{U.killAgent(je)},[]),Is=x.useCallback(je=>{var Je;(Je=Ye.current)==null||Je.callSubordinates(je)},[Ye]),wn=x.useCallback(je=>{E.open(je)},[E]),Po=x.useCallback(()=>{k.open(null)},[k]),Bo=x.useCallback(()=>{var je;(je=Ye.current)==null||je.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),it("info",t("notifications:drawing.rectangleTool"),t("notifications:drawing.clickAndDrag"),3e3)},[Ye,it]),Ps=x.useCallback(je=>{R(je)},[]),Ua=x.useCallback(()=>{R(null)},[]),Bi=x.useCallback(()=>{const je=Array.from(U.getState().selectedAgentIds);je.forEach(Je=>{var Ct;U.removeAgentFromServer(Je),(Ct=Ye.current)==null||Ct.removeAgent(Je)}),d.close(),it("info",t("notifications:toast.agentsRemoved"),t("notifications:toast.agentsRemovedMsg",{count:je.length}))},[it,d,Ye,t]),Fi=x.useCallback(()=>{var je,Je;if(K==="selected"){const Ct=Vt.size;U.deleteSelectedBuildings(),(je=Ye.current)==null||je.syncBuildings(),it("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(),it("info",t("notifications:toast.buildingDeleted"),t("notifications:toast.buildingDeletedMsg",{name:(Ct==null?void 0:Ct.name)||"Building"}))}se(null)},[K,Ft,Vt.size,it,Ye,t]),Bs=x.useMemo(()=>oq(O.worldPosition,O.target,U.getState().agents,Ot,Ft,{showToast:it,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:je=>E.open(je),openBuildingModal:je=>k.open(je),openAgentEditModal:je=>j.open(je),requestBuildingDelete:je=>se(je),setSpawnPosition:F,openRestoreArchivedModal:je=>D.open(je),sceneRef:Ye}),[O.worldPosition,O.target,Ot,Ft,s,a,k,i,c,E,j,D,it,Ye]);x.useEffect(()=>{!s.isOpen&&!a.isOpen&&(F(null),B(null))},[s.isOpen,a.isOpen]),x.useEffect(()=>{const je=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"?Te(At.buildingId):kn.type==="database"?Ne(At.buildingId):kn.type==="folder"&&kn.folderPath?U.openFileExplorer(kn.folderPath):kn.type==="terminal"&&((Dn=kn.terminalStatus)!=null&&Dn.url)?We(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?We(At.buildingId):At!=null&&At.url&&R(At.url)};return window.addEventListener("tide:open-spawn-modal",je),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",je),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 je;(je=Ye.current)==null||je.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ye]),Ts=x.useCallback(()=>ve(je=>!je),[]),hs=x.useCallback(()=>U.setMobileView("terminal"),[]),Mn=x.useCallback(()=>Oe(!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(sq,{}),o.jsx(aq,{onCreateAgent:s.open}),o.jsx(CW,{visible:rt.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(NW,{className:"app-view-mode-toggle"}),o.jsx(XR,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:$,title:"Auto-organize all agents in their areas",onClick:()=>{W(!0),iq().then(je=>{t_(je,Ye),it("success","Organized",`Arranged ${je.organized.length} agent${je.organized.length!==1?"s":""}`)}).catch(je=>{console.error("organize all error:",je),it("error","Organize Failed",je.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(Se.Suspense,{fallback:null,children:Ke==="dashboard"?o.jsx(pq,{onSelectAgent:je=>U.selectAgent(je),onFocusAgent:je=>{U.setViewMode("3d"),Fn(je)},onKillAgent:Ls,onSelectBuilding:je=>U.selectBuilding(je),onOpenTerminal:je=>{U.selectAgent(je),U.setTerminalOpen(!0)},onFocusZone:je=>{U.setViewMode("3d");const Je=U.getState().areas.get(je);Je&&Je.assignedAgentIds.length>0&&Fn(Je.assignedAgentIds[0])}}):Ke==="2d"?o.jsx(fq,{onAgentClick:(je,Je)=>{Je?U.addToSelection(je):U.selectAgent(je)},onAgentDoubleClick:je=>{if(window.innerWidth<=768){U.openTerminalOnMobile(je);return}U.selectAgent(je),U.setTerminalOpen(!0)},onBuildingClick:(je,Je)=>{U.selectBuilding(je);const Ct=U.getState().buildings.get(je);(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:je,screenPos:Je,fromClick:!0}),fe.current=null},150))},onBuildingDoubleClick:je=>{var Ct;fe.current&&(clearTimeout(fe.current),fe.current=null),et(null);const Je=U.getState().buildings.get(je);(Je==null?void 0:Je.type)==="server"&&((Ct=Je.pm2)!=null&&Ct.enabled)?me(je):(Je==null?void 0:Je.type)==="boss"?Te(je):(Je==null?void 0:Je.type)==="database"?Ne(je):(Je==null?void 0:Je.type)==="folder"&&Je.folderPath?U.openFileExplorer(Je.folderPath):k.open(je)},onGroundClick:()=>{U.selectAgent(null),U.selectBuilding(null)},onAreaDoubleClick:je=>{U.selectArea(je),i.open()},onContextMenu:(je,Je,Ct)=>{const ot=Ct?{type:Ct.type,id:Ct.id}:{type:"ground"};O.open(je,Je,ot)},onMoveCommand:(je,Je)=>{const ot=je.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})}}je.forEach((Mt,At)=>{U.moveAgent(Mt,jn[At])})},onBuildingDragMove:(je,Je)=>{var ot;const Ct=U.getState().buildings.get(je);Ct&&(U.getState().buildings.set(je,{...Ct,position:{x:Je.x,z:Je.z}}),(ot=window.__tideScene2D)==null||ot.syncBuildings())},onBuildingDragEnd:(je,Je)=>{U.updateBuildingPosition(je,Je)},scale2d:X.scale2d,showTaskLabels:X.show2DTaskLabels,showGrid:X.gridVisible,fpsLimit:X.fpsLimit}):o.jsxs(Se.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:n,id:"selection-box"})]},ke)}),Ae&&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(TW,{isOpen:ge,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}),he&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>Oe(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${$e?"is-collapsed":""} ${Pe?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)Oe(!he);else{const Je=!$e;xe(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:Pe?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 ${he?"sidebar-open":""} ${$e?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>Oe(!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(ES,{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(_4,{agentIds:nn})})})]}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(x.Profiler,{id:"UnitPanel",onRender:yu,children:o.jsx(ES,{onFocusAgent:Fn,onKillAgent:Ls,onCallSubordinates:Is,onOpenAreaExplorer:wn})})})]}),o.jsx(x.Profiler,{id:"GuakeOutputPanel",onRender:yu,children:o.jsx(sW,{onSaveSnapshot:T.open})})]}),o.jsx(_W,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:b.open,onOpenSnapshots:S.open,isGeneratingReport:xt,pip:_}),o.jsx(hW,{activeTool:bt,onExit:Ma}),q&&(()=>{const je=U.getState().agents.get(q.agentId);return je?o.jsx(bW,{agent:je,screenPos:q.screenPos,onClose:()=>be(null)}):null})(),Ce&&(()=>{const je=Ft.get(Ce.buildingId);if(!je)return null;const Je=()=>et(null);return je.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(kW,{building:je,screenPos:Ce.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ce.buildingId)},onOpenLogsModal:()=>{Je(),Te(Ce.buildingId)},onOpenUrlInModal:Ps})]}):je.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(SW,{building:je,screenPos:Ce.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ce.buildingId)},onOpenDatabasePanel:()=>{Je(),Ne(Ce.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(yW,{building:je,screenPos:Ce.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(Ce.buildingId)},onOpenLogsModal:()=>{me(Ce.buildingId)},onOpenUrlInModal:Ps})]})})(),ie&&(()=>{var Je;const je=Ft.get(ie);return je?(Je=je.docker)!=null&&Je.enabled?o.jsx(uq,{building:je,isOpen:!0,onClose:()=>me(null)}):o.jsx(cq,{building:je,isOpen:!0,onClose:()=>me(null)}):null})(),Ee&&(()=>{const je=Ft.get(Ee);return je?o.jsx(dq,{building:je,isOpen:!0,onClose:()=>Te(null)}):null})(),ee&&(()=>{const je=Ft.get(ee);return je?o.jsx("div",{className:"modal-overlay visible",onMouseDown:st,onClick:pe,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(lq,{building:je,onClose:ze})})}):null})(),Ve&&(()=>{var Je;const je=Ft.get(Ve);return!je||!((Je=je.terminalStatus)!=null&&Je.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:oe,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 - ",je.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(jx,{terminalUrl:je.terminalStatus.url,visible:!0})]})})})(),o.jsx(KW,{pip:_,title:"Tide Commander - Agents",children:o.jsx(ZW,{})}),o.jsx(hq,{url:M||"",title:M?`Preview - ${M}`:"",isOpen:!!M,onClose:Ua}),T.isOpen&&nn.length===1&&(()=>{const je=nn[0],Je=U.getState().agents.get(je);if(!Je)return null;const Ct=U.getOutputs(je);return o.jsx(mq,{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(),it("success",t("notifications:toast.snapshotSaved"),t("notifications:toast.snapshotSavedMsg"))}catch(jn){const Mt=jn instanceof Error?jn.message:t("notifications:toast.snapshotFailedMsg");it("error",t("notifications:toast.snapshotFailed"),Mt)}},isSaving:$t,error:En||void 0})})(),o.jsx(pW,{onFocusAgent:Fn,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:Po,onNewAreaClick:Bo}),o.jsx(GW,{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:()=>se(null),onConfirmBuildingDelete:Fi,showBackNavModal:ht,onCloseBackNavModal:()=>Gt(!1),onLeave:tn,onOpenPM2LogsModal:je=>me(je),onOpenBossLogsModal:je=>Te(je),onOpenDatabasePanel:je=>Ne(je),onSyncScene:()=>{var je,Je;(je=Ye.current)==null||je.syncAreas(),(Je=Ye.current)==null||Je.syncAgents(Array.from(U.getState().agents.values()))}})]})}function bq(){return o.jsx(yL,{children:o.jsx(AL,{children:o.jsx(gq,{})})})}class xq 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}}A6();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 n_=document.getElementById("app");if(!n_)throw new Error("Could not find #app container");const yq=CM.createRoot(n_);yq.render(o.jsx(Se.StrictMode,{children:o.jsx(x.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(xq,{children:o.jsx(bq,{})})})}));console.log("[Tide] Tide Commander initialized");export{Df as $,NL as A,c1 as B,qD as C,wL as D,Mx as E,aV as F,_x as G,ed as H,Wx as I,ur as J,Ux as K,eL as L,dr as M,Iq as N,TL as O,Fa as P,oV as Q,TH as R,pt as S,fs as T,Jq as U,Bt as V,b1 as W,iV as X,k2 as Y,Mu as Z,Rf as _,Gx as a,ph as a$,Hg as a0,Wr as a1,Qp as a2,Xq as a3,Qj as a4,yp as a5,Aq as a6,vL as a7,Vb as a8,Yq as a9,WD as aA,o5 as aB,P6 as aC,B6 as aD,U6 as aE,zq as aF,Xj as aG,Uq as aH,Hq as aI,Dx as aJ,Rx as aK,np as aL,lV as aM,vt as aN,NN as aO,rV as aP,TN as aQ,_N as aR,Lu as aS,Fr as aT,zr as aU,W6 as aV,q6 as aW,d1 as aX,jb as aY,V6 as aZ,Do as a_,Ii as aa,Cq as ab,Wq as ac,Ey as ad,ia as ae,Pu as af,Up as ag,Ea as ah,pr as ai,Ox as aj,YD as ak,On as al,$R as am,VD as an,Gq as ao,Kq as ap,Qq as aq,Vq as ar,i1 as as,iS as at,Lq as au,Jj as av,Xt as aw,UH as ax,_T as ay,sh as az,oL as b,jN as b0,da as b1,RN as b2,d5 as b3,Oy as b4,gx as b5,v4 as b6,s1 as b7,_q as b8,Pq as b9,Eq as ba,Bq as bb,Fq as bc,Oq as bd,Dq as be,$q as bf,Kp as bg,PL as bh,x2 as bi,v2 as bj,Zq as bk,_o as bl,Ju as bm,_L as bn,eV as bo,sV as bp,tV as bq,Rq as br,Mq as bs,nV as bt,UR as bu,HR as bv,su as bw,Lx as bx,qq as c,lL as d,jy as e,Rs as f,_H as g,Ta as h,Kl as i,o as j,vS as k,Na as l,Tn as m,Nq as n,jq as o,Nf as p,zx as q,x as r,U as s,Tq as t,dt as u,Gb as v,Rt as w,GR as x,KR as y,Se as z};
|