tide-commander 1.48.0 → 1.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{BossLogsModal-CFwfed1-.js → BossLogsModal-buht3LyW.js} +1 -1
- package/dist/assets/{BossSpawnModal-DUQ6HEgW.js → BossSpawnModal-D7M1JocE.js} +1 -1
- package/dist/assets/{ControlsModal-BU8Ip7nq.js → ControlsModal-C3-j1E6y.js} +1 -1
- package/dist/assets/{DockerLogsModal-CbYYg1sc.js → DockerLogsModal-CA2j24QX.js} +1 -1
- package/dist/assets/{EmbeddedEditor-C_REDOwe.js → EmbeddedEditor-CrLtAaIO.js} +1 -1
- package/dist/assets/GmailOAuthSetup-CG2BmCyg.js +303 -0
- package/dist/assets/GoogleOAuthSetup-DlaXAoyq.js +236 -0
- package/dist/assets/{IframeModal-Ca7ZWrHU.js → IframeModal-CvJ6LEIu.js} +1 -1
- package/dist/assets/IntegrationsPanel-iTByepHj.js +2 -0
- package/dist/assets/{LogViewerModal-DnCVSAMs.js → LogViewerModal-C75Yyse9.js} +1 -1
- package/dist/assets/{MonitoringModal-Cu8Kz_D_.js → MonitoringModal-C3NapNrP.js} +1 -1
- package/dist/assets/{PM2LogsModal-DTBPwViK.js → PM2LogsModal-CaacRI13.js} +1 -1
- package/dist/assets/{RestoreArchivedAreaModal-C7ym_R1q.js → RestoreArchivedAreaModal-mwQqJ4qp.js} +1 -1
- package/dist/assets/{SaveSnapshotModal-Byqak-Tf.js → SaveSnapshotModal-Didvj3hf.js} +1 -1
- package/dist/assets/{Scene2DCanvas-Bzggyv_C.js → Scene2DCanvas-chSGLBlj.js} +1 -1
- package/dist/assets/{SceneManager-CzgjrwbM.js → SceneManager-G0H-cWU4.js} +1 -1
- package/dist/assets/{SkillsPanel-Djr7DSvf.js → SkillsPanel-nKzb0E59.js} +1 -1
- package/dist/assets/{SnapshotManager-BfGQUnsS.js → SnapshotManager-DoQRZCNb.js} +1 -1
- package/dist/assets/{SpawnModal-BbKpL82w.js → SpawnModal-CPTZGYNR.js} +1 -1
- package/dist/assets/{SubordinateAssignmentModal-B1TZX27W.js → SubordinateAssignmentModal-B2XP8wZU.js} +1 -1
- package/dist/assets/{SupervisorPanel-PK5vEWzs.js → SupervisorPanel-LlgMdGCQ.js} +1 -1
- package/dist/assets/{TriggerManagerPanel-DVK-bbLW.js → TriggerManagerPanel-DMiK0_y5.js} +1 -1
- package/dist/assets/{WorkflowEditorPanel-Brdqd-Ad.js → WorkflowEditorPanel-DPwmjV2f.js} +1 -1
- package/dist/assets/{index-B5tIXl_r.js → index-BCuYxI5F.js} +2 -2
- package/dist/assets/{index-BExjQf95.js → index-BIt0Cgpm.js} +1 -1
- package/dist/assets/{index-BF9QVox6.js → index-BM1s5vTS.js} +3 -3
- package/dist/assets/{index--5OtsLD2.js → index-CG-I_YeN.js} +1 -1
- package/dist/assets/{index-wIjtXnz9.js → index-CxEHgPe3.js} +1 -1
- package/dist/assets/{index-BgUdbPaM.js → index-D33VRpYX.js} +1 -1
- package/dist/assets/{index-BP3hr2mC.js → index-DYwDeYnm.js} +1 -1
- package/dist/assets/{index-RJgcrQXD.js → index-XXW1ctrV.js} +1 -1
- package/dist/assets/{main-CMpDB4wb.js → main-D-o_EGqJ.js} +4 -4
- package/dist/assets/{web-N6EXBTZp.js → web-Blb26Kj7.js} +1 -1
- package/dist/assets/{web-BN1vvWmX.js → web-hHpxvpTK.js} +1 -1
- package/dist/index.html +1 -1
- package/dist/src/packages/server/data/event-queries.js +15 -0
- package/dist/src/packages/server/data/migrations/005_drive_actions.sql +19 -0
- package/dist/src/packages/server/index.js +1 -0
- package/dist/src/packages/server/integrations/gmail/index.js +8 -6
- package/dist/src/packages/server/integrations/google-drive/drive-client.js +605 -0
- package/dist/src/packages/server/integrations/google-drive/drive-config.js +127 -0
- package/dist/src/packages/server/integrations/google-drive/drive-routes.js +365 -0
- package/dist/src/packages/server/integrations/google-drive/drive-skill.js +248 -0
- package/dist/src/packages/server/integrations/google-drive/index.js +60 -0
- package/dist/src/packages/server/integrations/integration-registry.js +2 -0
- package/package.json +1 -1
- package/dist/assets/GmailOAuthSetup-DjgTvBxC.js +0 -270
- package/dist/assets/GoogleOAuthSetup-Cg9TpR8P.js +0 -203
- package/dist/assets/IntegrationsPanel-8a2TGZA7.js +0 -2
|
@@ -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-BCuYxI5F.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-Chj50gSY.js","assets/web-Blb26Kj7.js","assets/SceneManager-G0H-cWU4.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-CPTZGYNR.js","assets/BossSpawnModal-D7M1JocE.js","assets/SubordinateAssignmentModal-B2XP8wZU.js","assets/index-BIt0Cgpm.js","assets/index-Bykeknjl.css","assets/index-DYwDeYnm.js","assets/index-D33VRpYX.js","assets/index-BM1s5vTS.js","assets/SupervisorPanel-LlgMdGCQ.js","assets/index-CG-I_YeN.js","assets/ControlsModal-C3-j1E6y.js","assets/SkillsPanel-nKzb0E59.js","assets/SnapshotManager-DoQRZCNb.js","assets/RestoreArchivedAreaModal-mwQqJ4qp.js","assets/IntegrationsPanel-iTByepHj.js","assets/MonitoringModal-C3NapNrP.js","assets/WorkflowEditorPanel-DPwmjV2f.js","assets/TriggerManagerPanel-DMiK0_y5.js","assets/index-XXW1ctrV.js","assets/index-CprCD9du.css","assets/PM2LogsModal-CaacRI13.js","assets/LogViewerModal-C75Yyse9.js","assets/DockerLogsModal-CA2j24QX.js","assets/BossLogsModal-buht3LyW.js","assets/Scene2DCanvas-chSGLBlj.js","assets/Scene2DCanvas-DwXbvB-b.css","assets/index-CxEHgPe3.js","assets/index-BZyCMBzi.css","assets/IframeModal-CvJ6LEIu.js","assets/IframeModal-DJkCGwT6.css","assets/SaveSnapshotModal-Didvj3hf.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var M_=Object.defineProperty;var D_=(t,e,n)=>e in t?M_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var et=(t,e,n)=>D_(t,typeof e!="symbol"?e+"":e,n);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as Qb,g as Nu,a as BA,c as L0}from"./vendor-react--Eh9ivFN.js";import{T as R_,a as ab,b as FA,L as zA,c as eu,F as Of,M as ar,V as $A,C as Ir,d as sr,S as Dr,e as O_,P as L_,D as rb,f as Lf,g as ro,I as P_,Q as HA,h as I_,O as UA,i as B_,j as F_,B as tu,k as z_,l as WA,N as $_,m as H_,n as U_,o as ib,p as qA,R as ob,q as W_,r as q_,s as V_,t as kf,u as G_,v as Xb,w as VA,x as pl,y as Y_,z as GA,A as K_,E as ul,G as Q_,H as X_,J as J_,K as Z_,U as $m,W as YA,X as eM,Y as tM,Z as nM,_ as sM,$ as aM,a0 as rM,a1 as KA,a2 as iM,a3 as P0,a4 as I0,a5 as B0,a6 as F0,a7 as lb,a8 as oM,a9 as lM,aa as cM,ab as uM,ac as dM,ad as fM,ae as pM,af as hM,ag as mM,ah as gM,ai as bM,aj as xM}from"./vendor-three-Chj50gSY.js";function yM(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 Hm={exports:{}},Nc={};/**
|
|
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 ik;function iD(){if(ik)return Qm;ik=1;var t=Qb();function e(m,x){return m===x&&(m!==0||1/m===1/x)||m!==m&&x!==x}var n=typeof Object.is=="function"?Object.is:e,s=t.useState,a=t.useEffect,r=t.useLayoutEffect,i=t.useDebugValue;function c(m,x){var y=x(),v=s({inst:{value:y,getSnapshot:x}}),S=v[0].inst,C=v[1];return r(function(){S.value=y,S.getSnapshot=x,d(S)&&C({inst:S})},[m,y,x]),a(function(){return d(S)&&C({inst:S}),m(function(){d(S)&&C({inst:S})})},[m]),i(y),y}function d(m){var x=m.getSnapshot;m=m.value;try{var y=x();return!n(m,y)}catch{return!0}}function f(m,x){return x()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return Qm.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h,Qm}var ok;function oD(){return ok||(ok=1,Km.exports=iD()),Km.exports}var lD=oD();const cD=(t,e)=>{if(fo(e))return e;if(YM(e)&&fo(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},uD={t:cD,ready:!1},dD=()=>()=>{},pt=(t,e={})=>{var T,M,R;const{i18n:n}=e,{i18n:s,defaultNS:a}=b.useContext(aD)||{},r=n||s||nD();r&&!r.reportNamespaces&&(r.reportNamespaces=new rD),r||ub(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=b.useMemo(()=>{var P;return{...eD(),...(P=r==null?void 0:r.options)==null?void 0:P.react,...e}},[r,e]),{useSuspense:c,keyPrefix:d}=i,f=t||a||((T=r==null?void 0:r.options)==null?void 0:T.defaultNS),h=fo(f)?[f]:f||["translation"],m=b.useMemo(()=>h,h);(R=(M=r==null?void 0:r.reportNamespaces)==null?void 0:M.addUsedNamespaces)==null||R.call(M,m);const x=b.useRef(0),y=b.useCallback(P=>{if(!r)return dD;const{bindI18n:U,bindI18nStore:q}=i,z=()=>{x.current+=1,P()};return U&&r.on(U,z),q&&r.store.on(q,z),()=>{U&&U.split(" ").forEach(F=>r.off(F,z)),q&&q.split(" ").forEach(F=>r.store.off(F,z))}},[r,i]),v=b.useRef(),S=b.useCallback(()=>{if(!r)return uD;const P=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(V=>GM(V,r,i)),U=e.lng||r.language,q=x.current,z=v.current;if(z&&z.ready===P&&z.lng===U&&z.keyPrefix===d&&z.revision===q)return z;const $={t:r.getFixedT(U,i.nsMode==="fallback"?m:m[0],d),ready:P,lng:U,keyPrefix:d,revision:q};return v.current=$,$},[r,m,d,i,e.lng]),[C,k]=b.useState(0),{t:N,ready:A}=lD.useSyncExternalStore(y,S,S);b.useEffect(()=>{if(r&&!A&&!c){const P=()=>k(U=>U+1);e.lng?rk(r,e.lng,m,P):db(r,m,P)}},[r,e.lng,m,A,c,C]);const E=r||{},D=b.useRef(null),_=b.useRef(),I=P=>{const U=Object.getOwnPropertyDescriptors(P);U.__original&&delete U.__original;const q=Object.create(Object.getPrototypeOf(P),U);if(!Object.prototype.hasOwnProperty.call(q,"__original"))try{Object.defineProperty(q,"__original",{value:P,writable:!1,enumerable:!1,configurable:!1})}catch{}return q},O=b.useMemo(()=>{const P=E,U=P==null?void 0:P.language;let q=P;P&&(D.current&&D.current.__original===P?_.current!==U?(q=I(P),D.current=q,_.current=U):q=D.current:(q=I(P),D.current=q,_.current=U));const z=!A&&!c?(...$)=>(ub(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."),N(...$)):N,F=[z,q,A];return F.t=z,F.i18n=q,F.ready=A,F},[N,E,A,E.resolvedLanguage,E.language,E.languages]);if(r&&c&&!A)throw new Promise(P=>{const U=()=>P();e.lng?rk(r,e.lng,m,U):db(r,m,U)});return O};function pb(t){"@babel/helpers - typeof";return pb=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},pb(t)}function nj(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":pb(XMLHttpRequest))==="object"}function fD(t){return!!t&&typeof t.then=="function"}function pD(t){return fD(t)?t:Promise.resolve(t)}var hD=/\{\{(.+?)\}\}/g;function lk(t,e){return t.replace(hD,function(n,s){var a=e[s.trim()];return a??n})}const mD="modulepreload",gD=function(t){return"/"+t},ck={},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=gD(f),f in ck)return;ck[f]=!0;const h=f.endsWith(".css"),m=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const x=document.createElement("link");if(x.rel=h?"stylesheet":mD,h||(x.as="script"),x.crossOrigin="",x.href=f,d&&x.setAttribute("nonce",d),document.head.appendChild(x),h)return new Promise((y,v)=>{x.addEventListener("load",y),x.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${f}`)))})}))}function r(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&r(c.reason);return e().catch(r)})};function uk(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 dk(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?uk(Object(n),!0).forEach(function(s){bD(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):uk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function bD(t,e,n){return(e=xD(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function xD(t){var e=yD(t,"string");return po(e)=="symbol"?e:e+""}function yD(t,e){if(po(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var s=n.call(t,e);if(po(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function po(t){"@babel/helpers - typeof";return po=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},po(t)}var Ci=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Ci=global.fetch:typeof window<"u"&&window.fetch&&(Ci=window.fetch);var gu;nj()&&(typeof global<"u"&&global.XMLHttpRequest?gu=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(gu=window.XMLHttpRequest));var Ff;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Ff=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Ff=window.ActiveXObject));typeof Ci!="function"&&(Ci=void 0);if(!Ci&&!gu&&!Ff)try{vt(()=>import("./browser-ponyfill-DZOWXZ4K.js").then(t=>t.b),__vite__mapDeps([0,1])).then(function(t){Ci=t.default}).catch(function(){})}catch{}var hb=function(e,n){if(n&&po(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},fk=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):Ci(e,n).then(r).catch(s)},pk=!1,vD=function(e,n,s,a){e.queryStringParams&&(n=hb(n,e.queryStringParams));var r=dk({},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=dk({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},pk?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{fk(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]}),fk(n,c,a,d),pk=!0}catch(h){a(h)}}},wD=function(e,n,s,a){s&&po(s)==="object"&&(s=hb("",s).slice(1)),e.queryStringParams&&(n=hb(n,e.queryStringParams));try{var r=gu?new gu:new Ff("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)}},kD=function(e,n,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Ci&&n.indexOf("file:")!==0)return vD(e,n,s,a);if(nj()||typeof ActiveXObject=="function")return wD(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 hk(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 Xm(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?hk(Object(n),!0).forEach(function(s){sj(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):hk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function SD(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function CD(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,aj(s.key),s)}}function AD(t,e,n){return e&&CD(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function sj(t,e,n){return(e=aj(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function aj(t){var e=jD(t,"string");return vl(e)=="symbol"?e:e+""}function jD(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 ND=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 sj({},s,a||"")},parseLoadPayload:function(n,s){},request:kD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},rj=(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]:{};SD(this,t),this.services=e,this.options=n,this.allOptions=s,this.type="backend",this.init(e,n,s)}return AD(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=Xm(Xm(Xm({},ND()),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=pD(d),d.then(function(f){if(!f)return i(null,{});var h=lk(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 x=h.message.toLowerCase(),y=["failed","fetch","network","load"].find(function(C){return x.indexOf(C)>-1});if(y)return s("failed loading "+n+": "+h.message,!0)}if(h)return s(h,!1);var v,S;try{typeof m.data=="string"?v=i.options.parse(m.data,a,r):v=m.data}catch{S="failed parsing "+n+" to json"}if(S)return s(S,!1);s(null,v)})}},{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(x){var y=c.options.addPath;typeof c.options.addPath=="function"&&(y=c.options.addPath(x,s));var v=lk(y,{lng:x,ns:s});c.options.request(c.options,v,d,function(S,C){f+=1,h.push(S),m.push(C),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 x=r.toResolveHierarchy(m);x.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(x,y){x&&i.warn("loading namespace ".concat(m," for language ").concat(h," failed"),x),!x&&y&&i.log("loaded namespace ".concat(m," for language ").concat(h),y),a.loaded("".concat(h,"|").concat(m),x,y)})})})}}}])})();rj.type="backend";const{slice:TD,forEach:ED}=[];function _D(t){return ED.call(TD.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function MD(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 mk=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,DD=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(!mk.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!mk.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},gk={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=DD(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 RD={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return gk.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;n&&typeof document<"u"&&gk.create(n,t,s,a,r)}},OD={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}},LD={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 tl=null;const bk=()=>{if(tl!==null)return tl;try{if(tl=typeof window<"u"&&window.localStorage!==null,!tl)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{tl=!1}return tl};var PD={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&bk())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&bk()&&window.localStorage.setItem(n,t)}};let nl=null;const xk=()=>{if(nl!==null)return nl;try{if(nl=typeof window<"u"&&window.sessionStorage!==null,!nl)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{nl=!1}return nl};var ID={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&xk())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&xk()&&window.sessionStorage.setItem(n,t)}},BD={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}},FD={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}},zD={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}},$D={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 ij=!1;try{document.cookie,ij=!0}catch{}const oj=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];ij||oj.splice(1,1);const HD=()=>({order:oj,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class lj{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=_D(n,this.options||{},HD()),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(RD),this.addDetector(OD),this.addDetector(PD),this.addDetector(ID),this.addDetector(BD),this.addDetector(FD),this.addDetector(zD),this.addDetector($D),this.addDetector(LD)}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&&!MD(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)}))}}lj.type="languageDetector";const zf={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},mb={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},UD={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},Yq=["#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"],Kd={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function Jb(t){const n=Math.floor((Date.now()-t)/1e3)/60;return n<1?Kd.recent:n<5?Kd.short:n<30?Kd.medium:Kd.long}function Zb(t){return zf[t]??zf.default}let Sf=null;function cj(){if(!Sf)try{Sf=globalThis.__i18n}catch{}return Sf}function WD(t){Sf=t}function qD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function VD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function GD(t){var a;const e=cj(),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 xp(t){var f;const e=cj(),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 au(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:""}En.use(rj).use(lj).use(sD).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(()=>{WD(En)});const ft={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",AOP_TRACKING_BOARD_VISIBLE:"tide-aop-tracking-board-visible",MOBILE_OVERVIEW_HEIGHT:"tide-mobile-overview-height",SPLIT_PANE_AGENT_IDS:"tide-split-pane-agent-ids",SPLIT_PANE_ORIENTATION:"tide-split-pane-orientation",GIT_PANEL_OPEN:"guake-git-panel-open",GIT_PANEL_MODE:"guake-git-panel-mode",GIT_PANEL_VIEW_MODE:"guake-git-view-mode",GIT_PANEL_FOLDER_IDX:"guake-git-folder-idx",BUILDINGS_PANEL_OPEN:"guake-buildings-panel-open",WORKFLOW_PANEL_OPEN:"guake-workflow-panel-open",SIDE_PANEL_WIDTH:"guake-side-panel-width",UNSEEN_AGENTS:"tide-unseen-agents",PENDING_MESSAGES:"tide-pending-messages"},gb="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 wa(t,e=""){try{return localStorage.getItem(t)??e}catch{return e}}function _r(t,e=!1){try{const n=localStorage.getItem(t);return n===null?e:n==="true"}catch{return e}}function ex(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 va(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function er(t,e){try{localStorage.setItem(t,e)}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Qa(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function tx(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function yk(t){try{localStorage.removeItem(t)}catch(e){console.error(`Failed to remove from localStorage: ${t}`,e)}}function Ca(){const t=nx();return t?t.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ti(){return wa(ft.AUTH_TOKEN,"")}function nx(){return wa(ft.BACKEND_URL,"")}function YD(t){const e=t.trim();er(ft.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(gb,{detail:e}))}function KD(t){if(typeof window>"u")return()=>{};const e=s=>{t(s.detail)},n=s=>{s.key===ft.BACKEND_URL&&t(s.newValue??"")};return window.addEventListener(gb,e),window.addEventListener("storage",n),()=>{window.removeEventListener(gb,e),window.removeEventListener("storage",n)}}function _t(t){return`${Ca()}${t}`}async function Lt(t,e){const n=Ti(),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 $f(t){const e=Ti();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 ss(t=!1,e){const[n,s]=b.useState(t),[a,r]=b.useState(e),i=b.useCallback(f=>{f!==void 0&&r(f),s(!0)},[]),c=b.useCallback(()=>{s(!1)},[]),d=b.useCallback(()=>{s(f=>!f)},[]);return{isOpen:n,data:a,open:i,close:c,toggle:d,setData:r}}function QD(){const[t,e]=b.useState(null),n=b.useCallback(a=>{e(a)},[]),s=b.useCallback(()=>{e(null)},[]);return{isOpen:t!==null,id:t,open:n,close:s}}function XD(){const[t,e]=b.useState(!1),[n,s]=b.useState({x:0,y:0}),[a,r]=b.useState({x:0,z:0}),[i,c]=b.useState({type:"ground"}),d=b.useCallback((h,m,x)=>{s(h),r(m),c(x),e(!0)},[]),f=b.useCallback(()=>{e(!1)},[]);return{isOpen:t,screenPosition:n,worldPosition:a,target:i,open:d,close:f}}const sa=[],JD=new Set;function Hf(){JD.forEach(t=>t())}function ZD(t,e){const n=sa.findIndex(s=>s.id===t);return n!==-1&&sa.splice(n,1),sa.push({id:t,close:e}),Hf(),()=>{const s=sa.findIndex(a=>a.id===t);s!==-1&&(sa.splice(s,1),Hf())}}function Cf(){return sa.length===0?!1:(sa.pop().close(),Hf(),!0)}function eR(t){const e=sa.findIndex(n=>n.id===t);return e===-1?!1:e<sa.length-1}function tR(...t){const e=new Set(t);for(;sa.length>0;){const n=sa[sa.length-1];if(e.has(n.id))break;sa.pop().close()}Hf()}function Qt(t,e,n){const s=b.useRef(n);s.current=n,b.useEffect(()=>e?ZD(t,()=>s.current()):void 0,[t,e])}const bu=5,Jm={0:0,1:4,2:8,3:14,4:25,5:50};let ru=null,vk=!1;async function nR(){if(vk)return ru;vk=!0;try{const t=await vt(()=>import("./index-B5tIXl_r.js"),__vite__mapDeps([2,3,1,4]));ru={Haptics:t.Haptics,ImpactStyle:t.ImpactStyle}}catch{}return ru}nR();function Uf(t){const e=Math.round(t),n=e<=0?0:e>=bu?bu:e;if(n!==0){if(ru){const{Haptics:s,ImpactStyle:a}=ru;if(n<=2&&typeof s.selectionChanged=="function"){s.selectionChanged().catch(()=>{navigator.vibrate&&navigator.vibrate(Jm[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(Jm[n])});return}}navigator.vibrate&&navigator.vibrate(Jm[n])}}function wk(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=b.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=b.useCallback(S=>{if(S.touches.length!==1)return;const C=S.touches[0];h.current={startX:C.clientX,startY:C.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),x=b.useCallback(S=>{if(!h.current.isTracking||S.touches.length!==1)return;const C=S.touches[0],k=C.clientX-h.current.startX;if(Math.abs(C.clientY-h.current.startY)>s){h.current.isTracking=!1,h.current.hasMovedEnough&&(d==null||d());return}const E=window.innerWidth*.4,D=Math.max(-1,Math.min(1,k/E));Math.abs(k)>=12&&(h.current.hasMovedEnough=!0,c==null||c(D))},[s,c,d]),y=b.useCallback(S=>{const C=h.current.isTracking,k=h.current.hasMovedEnough;if(!C)return;const N=S.changedTouches[0],A=N.clientX-h.current.startX,E=Math.abs(N.clientY-h.current.startY),D=Date.now()-h.current.startTime;h.current.isTracking=!1,h.current.hasMovedEnough=!1,Math.abs(A)>=n&&E<=s&&D<500?(Uf(f),A>0?i==null||i():r==null||r()):k&&(d==null||d())},[n,s,f,r,i,d]),v=b.useCallback(()=>{const S=h.current.hasMovedEnough;h.current.isTracking=!1,h.current.hasMovedEnough=!1,S&&(d==null||d())},[d]);b.useEffect(()=>{const S=t.current;if(!(!S||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return S.addEventListener("touchstart",m,{passive:!0}),S.addEventListener("touchmove",x,{passive:!0}),S.addEventListener("touchend",y,{passive:!0}),S.addEventListener("touchcancel",v,{passive:!0}),()=>{S.removeEventListener("touchstart",m),S.removeEventListener("touchmove",x),S.removeEventListener("touchend",y),S.removeEventListener("touchcancel",v)}},[t,a,m,x,y,v])}const kk=8,sR=.93,Sk=.4;function aR(t){const{gestureRef:e,agentListRef:n,enabled:s,onSelect:a}=t,[r,i]=b.useState(!1),[c,d]=b.useState(null),f=b.useRef(!1),h=b.useRef(null),m=b.useRef(a);m.current=a;const x=b.useCallback(()=>{if(f.current)return;f.current=!0,i(!0);const C=n.current;if(C){const k=Math.round(C.clientHeight/2);C.style.paddingTop=`${k}px`,C.style.paddingBottom=`${k}px`}},[n]),y=b.useCallback(()=>{f.current=!1,h.current=null,i(!1),d(null);const C=n.current;C&&(C.style.paddingTop="",C.style.paddingBottom="")},[n]),v=b.useCallback(C=>{const k=n.current;if(!k)return;k.scrollTop+=C;const N=k.getBoundingClientRect(),A=N.top+N.height/2,E=N.left+N.width/2,D=document.elementFromPoint(E,A);let _=null;if(D){const I=D.closest("[data-agent-id]");I&&k.contains(I)&&(_=I.dataset.agentId)}if(_!==h.current&&(h.current=_,d(_),_)){const I=H.getState().settings.vibrationIntensity??1;Uf(I)}},[n]),S=b.useCallback(()=>{const C=h.current;if(C){const k=H.getState().settings.vibrationIntensity??1,N=k<=0?0:Math.min(k+1,bu);Uf(N),m.current(C)}y()},[y]);return b.useEffect(()=>{const C=e.current;if(!C||!s)return;const k=C.style.touchAction;C.style.touchAction="none";let N=!1,A=!1,E=0,D=0,_=0,I=0,O=0,T=0,M=0,R=0;const P=()=>{M&&(cancelAnimationFrame(M),M=0)},U=()=>{if(Math.abs(T)<Sk){T=0;return}C.scrollTop+=T,T*=sR,M=requestAnimationFrame(U)},q=V=>{if(P(),V.touches.length>=2){V.preventDefault(),N=!1,A=!1,R=(V.touches[0].clientY+V.touches[1].clientY)/2,x(),v(0);return}N=!0,A=!1,E=V.touches[0].clientX,D=V.touches[0].clientY,_=C.scrollTop,I=D,O=performance.now(),T=0},z=V=>{if(V.touches.length>=2){if(V.preventDefault(),(A||N)&&(A=!1,N=!1),!f.current){R=(V.touches[0].clientY+V.touches[1].clientY)/2,x(),v(0);return}const Q=(V.touches[0].clientY+V.touches[1].clientY)/2,K=R-Q;R=Q,v(K);return}if(f.current&&V.touches.length===1){V.preventDefault();const Q=V.touches[0].clientY,K=R-Q;R=Q,v(K);return}if(!N&&!A)return;const G=V.touches[0].clientX,B=V.touches[0].clientY;if(N&&!A){const Q=Math.abs(G-E),K=Math.abs(B-D);if(Q<kk&&K<kk)return;if(K>=Q)A=!0,N=!1,V.preventDefault();else{N=!1;return}}if(A){V.preventDefault();const Q=performance.now(),K=Q-O;C.scrollTop=_+(D-B),K>0&&(T=(I-B)/K*16),I=B,O=Q}},F=V=>{if(f.current&&V.touches.length===0){S();return}f.current||(A||N)&&V.touches.length===0&&(A&&Math.abs(T)>Sk&&(M=requestAnimationFrame(U)),A=!1,N=!1)},$=()=>{A=!1,N=!1,P(),f.current&&y()};return C.addEventListener("touchstart",q,{passive:!1}),C.addEventListener("touchmove",z,{passive:!1}),C.addEventListener("touchend",F,{passive:!0}),C.addEventListener("touchcancel",$,{passive:!0}),()=>{C.removeEventListener("touchstart",q),C.removeEventListener("touchmove",z),C.removeEventListener("touchend",F),C.removeEventListener("touchcancel",$),C.style.touchAction=k,P();const V=n.current;V&&(V.style.paddingTop="",V.style.paddingBottom="")}},[e,n,s,x,y,v,S]),{isActive:r,hoveredAgentId:c}}const rR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function iR(){return"documentPictureInPicture"in window}function oR(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 lR(){const[t,e]=b.useState(!1),[n,s]=b.useState(null),[a,r]=b.useState(null),i=b.useRef(null),c=iR(),d=b.useCallback(()=>{if(i.current){const m=i.current.__cleanupFns;m&&m.forEach(x=>x()),i.current.close(),i.current=null}s(null),r(null),e(!1)},[]),f=b.useCallback(async m=>{if(!c)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;i.current&&d();const x={...rR,...m};try{const v=await window.documentPictureInPicture.requestWindow({width:x.width,height:x.height,disallowReturnToOpener:!0});i.current=v,x.copyStyleSheets&&oR(document,v.document);const S=v.document.createElement("div");S.id="pip-root",S.style.width="100%",S.style.height="100%",v.document.body.appendChild(S),v.document.body.style.margin="0",v.document.body.style.padding="0",v.document.body.style.overflow="hidden",v.addEventListener("pagehide",()=>{i.current=null,s(null),r(null),e(!1)});const C=[];if(x.keepOnTop&&x.keepOnTop!=="none"){const k=x.keepOnTop==="raise",N=()=>{i.current&&!i.current.closed&&setTimeout(()=>{i.current&&!i.current.closed&&(i.current.focus(),k&&setTimeout(()=>window.focus(),10))},50)},A=()=>{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",N),document.addEventListener("visibilitychange",A),C.push(()=>window.removeEventListener("focus",N),()=>document.removeEventListener("visibilitychange",A))}return v.__cleanupFns=C,s(v),r(S),e(!0),!0}catch(y){return console.error("Failed to open Picture-in-Picture window:",y),!1}},[c,d]),h=b.useCallback(async m=>{t?d():await f(m)},[t,f,d]);return b.useEffect(()=>()=>{i.current&&i.current.close()},[]),b.useMemo(()=>({isOpen:t,pipWindow:n,pipContainer:a,isSupported:c,open:f,close:d,toggle:h}),[t,n,a,c,f,d,h])}function _c(){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 cR{constructor(){et(this,"messages",new Map);et(this,"logs",[]);et(this,"maxMessagesPerAgent",200);et(this,"maxLogs",500);et(this,"enabled",!0);et(this,"listeners",new Set);et(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,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:_c(),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:_c(),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:_c(),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:_c(),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:_c(),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 ms=new cR,xu={debug:(t,e,n)=>ms.debug(t,e,n),info:(t,e,n)=>ms.info(t,e,n),warn:(t,e,n)=>ms.warn(t,e,n),error:(t,e,n)=>ms.error(t,e,n)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var wl;(function(t){t.Unimplemented="UNIMPLEMENTED",t.Unavailable="UNAVAILABLE"})(wl||(wl={}));class Zm extends Error{constructor(e,n,s){super(e),this.message=e,this.code=n,this.data=s}}const uR=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"},dR=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},s=n.Plugins=n.Plugins||{},a=()=>e!==null?e.name:uR(t),r=()=>a()!=="web",i=m=>{const x=f.get(m);return!!(x!=null&&x.platforms.has(a())||c(m))},c=m=>{var x;return(x=n.PluginHeaders)===null||x===void 0?void 0:x.find(y=>y.name===m)},d=m=>t.console.error(m),f=new Map,h=(m,x={})=>{const y=f.get(m);if(y)return console.warn(`Capacitor plugin "${m}" already registered. Cannot register plugins twice.`),y.proxy;const v=a(),S=c(m);let C;const k=async()=>(!C&&v in x?C=typeof x[v]=="function"?C=await x[v]():C=x[v]:e!==null&&!C&&"web"in x&&(C=typeof x.web=="function"?C=await x.web():C=x.web),C),N=(O,T)=>{var M,R;if(S){const P=S==null?void 0:S.methods.find(U=>T===U.name);if(P)return P.rtype==="promise"?U=>n.nativePromise(m,T.toString(),U):(U,q)=>n.nativeCallback(m,T.toString(),U,q);if(O)return(M=O[T])===null||M===void 0?void 0:M.bind(O)}else{if(O)return(R=O[T])===null||R===void 0?void 0:R.bind(O);throw new Zm(`"${m}" plugin is not implemented on ${v}`,wl.Unimplemented)}},A=O=>{let T;const M=(...R)=>{const P=k().then(U=>{const q=N(U,O);if(q){const z=q(...R);return T=z==null?void 0:z.remove,z}else throw new Zm(`"${m}.${O}()" is not implemented on ${v}`,wl.Unimplemented)});return O==="addListener"&&(P.remove=async()=>T()),P};return M.toString=()=>`${O.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:O,writable:!1,configurable:!1}),M},E=A("addListener"),D=A("removeListener"),_=(O,T)=>{const M=E({eventName:O},T),R=async()=>{const U=await M;D({eventName:O,callbackId:U},T)},P=new Promise(U=>M.then(()=>U({remove:R})));return P.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},P},I=new Proxy({},{get(O,T){switch(T){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return S?_:E;case"removeListener":return D;default:return A(T)}}});return s[m]=I,f.set(m,{name:m,proxy:I,platforms:new Set([...Object.keys(x),...S?[v]:[]])}),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=Zm,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},fR=t=>t.Capacitor=dR(t),Wf=fR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Tu=Wf.registerPlugin;class sx{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 Wf.Exception(e,wl.Unimplemented)}unavailable(e="not available"){return new Wf.Exception(e,wl.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 Ck=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Ak=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class pR extends sx{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=Ak(a).trim(),r=Ak(r).trim(),n[a]=r}),n}async setCookie(e){try{const n=Ck(e.key),s=Ck(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)}}}Tu("CapacitorCookies",{web:()=>new pR});const hR=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)}),mR=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=t[e[i]],a),{})},gR=(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,bR=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),a=mR(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 xR extends sx{async request(e){const n=bR(e,e.webFetchExtra),s=gR(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 hR(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,x)=>{h[x]=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 Kq=Tu("CapacitorHttp",{web:()=>new xR});var jk;(function(t){t.Dark="DARK",t.Light="LIGHT",t.Default="DEFAULT"})(jk||(jk={}));var Nk;(function(t){t.StatusBar="StatusBar",t.NavigationBar="NavigationBar"})(Nk||(Nk={}));class yR extends sx{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")}}Tu("SystemBars",{web:()=>new yR});var Tk;(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"})(Tk||(Tk={}));const ax=Tu("LocalNotifications",{web:()=>vt(()=>import("./web-N6EXBTZp.js"),__vite__mapDeps([5,3,1,4])).then(t=>new t.LocalNotificationsWeb)}),vR=Tu("ServerConfig");let wR=100;const kR="agent_alerts",bb="tide-notification-tap";function SR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function uj(t){if(SR()){H.openTerminalOnMobile(t);return}if(document.querySelector(".commander-overlay")){H.requestCommanderExpand(t);return}H.selectAgent(t),H.setTerminalOpen(!0)}function Eu(){try{return Wf.isNativePlatform()}catch{return!1}}async function CR(){if(Eu())try{const t=await ax.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 AR(t){const{title:e,body:n,icon:s,data:a}=t;if(Eu())try{const r=wR++;console.log("[Notifications] Scheduling native notification id="+r,e),await ax.schedule({notifications:[{id:r,title:e,body:n,extra:a,channelId:kR,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(bb,{detail:a}))}}}let eg=!1;async function jR(t){const e=[];if(eg)return()=>{};if(eg=!0,t){const n=s=>{const a=s;a.detail&&t(a.detail)};window.addEventListener(bb,n),e.push(()=>window.removeEventListener(bb,n))}if(Eu())try{const n=await ax.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()),eg=!1}}function NR(t,e){Eu()&&vR.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,Ek=t=>{window.__tideWsState.ws=t},TR=()=>window.__tideWsState.isConnecting,Mc=t=>{window.__tideWsState.isConnecting=t},xb=()=>window.__tideWsState.reconnectAttempts,yb=t=>{window.__tideWsState.reconnectAttempts=t},dj=()=>window.__tideWsState.reconnectTimeout,fj=t=>{window.__tideWsState.reconnectTimeout=t},_k=10,rx="tide_ws_has_connected";function Mk(){return sessionStorage.getItem(rx)==="true"}function ER(t){sessionStorage.setItem(rx,"true")}function _R(){sessionStorage.removeItem(rx)}let pj=null;const MR=t=>{pj=t},Dk=()=>pj,Pe={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function hj(t){t.onToast&&(Pe.onToast=t.onToast),t.onAgentCreated&&(Pe.onAgentCreated=t.onAgentCreated),t.onAgentUpdated&&(Pe.onAgentUpdated=t.onAgentUpdated),t.onAgentDeleted&&(Pe.onAgentDeleted=t.onAgentDeleted),t.onAgentsSync&&(Pe.onAgentsSync=t.onAgentsSync),t.onAreasSync&&(Pe.onAreasSync=t.onAreasSync),t.onSpawnError&&(Pe.onSpawnError=t.onSpawnError),t.onSpawnSuccess&&(Pe.onSpawnSuccess=t.onSpawnSuccess),t.onToolUse&&(Pe.onToolUse=t.onToolUse),t.onDirectoryNotFound&&(Pe.onDirectoryNotFound=t.onDirectoryNotFound),t.onDelegation&&(Pe.onDelegation=t.onDelegation),t.onCustomClassesSync&&(Pe.onCustomClassesSync=t.onCustomClassesSync),t.onReconnect&&(Pe.onReconnect=t.onReconnect),t.onAgentNotification&&(Pe.onAgentNotification=t.onAgentNotification),t.onBuildingUpdated&&(Pe.onBuildingUpdated=t.onBuildingUpdated),t.onSubagentStarted&&(Pe.onSubagentStarted=t.onSubagentStarted),t.onSubagentCompleted&&(Pe.onSubagentCompleted=t.onSubagentCompleted)}function DR(){Pe.onToast=null,Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onSpawnError=null,Pe.onSpawnSuccess=null,Pe.onToolUse=null,Pe.onDirectoryNotFound=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onReconnect=null,Pe.onAgentNotification=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}function RR(){Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onToolUse=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onBuildingUpdated=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}const Qd=new Map,OR=new Map,vb={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?Qd.has(t)?[[t,Qd.get(t)]]:[]:Array.from(Qd.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(){Qd.clear(),OR.clear()},report(){}};class LR{constructor(){et(this,"frames",[]);et(this,"lastFrameTime",0);et(this,"frameCount",0);et(this,"fps",0);et(this,"minFps",1/0);et(this,"maxFps",0);et(this,"fpsHistory",[]);et(this,"maxHistorySize",60)}tick(e=200){const 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 Xd=new LR;class PR{constructor(){et(this,"snapshots",[]);et(this,"maxSnapshots",120);et(this,"intervalId",null);et(this,"leakThresholdMB",50);et(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const 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 Dc=new PR;function Kc(t,e,n,s,a,r){}function mj(t,e){b.useRef(0),b.useEffect(()=>{},[t,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}const wb=ft.PENDING_MESSAGES,IR=300*1e3;function gj(){try{const t=localStorage.getItem(wb);if(!t)return[];const e=JSON.parse(t),n=Date.now();return e.filter(s=>n-s.queuedAt<IR)}catch{return[]}}function bj(t){try{t.length===0?localStorage.removeItem(wb):localStorage.setItem(wb,JSON.stringify(t))}catch{}}function Jd(t){const e=gj();e.push({message:t,queuedAt:Date.now()}),bj(e)}function BR(){var s;const t=gj();if(t.length===0)return 0;let e=0;const n=[];for(const a of t)FR(a.message)?e++:n.push(a);if(bj(n),e>0){const a=e===1?"queued message":"queued messages";(s=Pe.onToast)==null||s.call(Pe,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function ix(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 FR(t){const e=yp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const n=JSON.stringify(t),s=ix(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",s,"payload:",t.payload),s&&ms.captureSent(s,n),e.send(n),!0}catch{return!1}}function ox(t){var n,s,a,r,i,c,d,f,h,m;const e=yp();if(!e)return(n=Dk())==null||n(),t.type==="send_command"?(Jd(t),(s=Pe.onToast)==null||s.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=Pe.onToast)==null||a.call(Pe,"error","Not Connected","Connecting to server... Please try again in a moment."),!1;if(e.readyState!==WebSocket.OPEN)return e.readyState===WebSocket.CONNECTING?t.type==="send_command"?(Jd(t),(r=Pe.onToast)==null||r.call(Pe,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=Pe.onToast)==null||i.call(Pe,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Dk())==null||c(),t.type==="send_command"?(Jd(t),(d=Pe.onToast)==null||d.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=Pe.onToast)==null||f.call(Pe,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const x=JSON.stringify(t),y=ix(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",y,"payload:",t.payload),y&&ms.captureSent(y,x),e.send(x),!0}catch(x){return t.type==="send_command"?(Jd(t),(h=Pe.onToast)==null||h.call(Pe,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=Pe.onToast)==null||m.call(Pe,"error","Send Failed",`Failed to send message: ${x}`),!1}}const Qc=new Set,zR=5e3;function Rk(t){if(!t.isDetached||!t.sessionId){Qc.delete(t.id);return}Qc.has(t.id)||(Qc.add(t.id),ox({type:"reattach_agent",payload:{agentId:t.id}}),setTimeout(()=>{Qc.delete(t.id)},zR))}function $R(t){var e,n,s,a,r,i,c,d,f,h,m,x,y,v,S,C,k,N,A,E,D,_,I,O;switch(vb.start(`ws:${t.type}`),t.type){case"agents_update":{const T=t.payload,M=T.filter(R=>R.class==="boss"||R.isBoss);M.length>0&&console.log("[WS agents_update] Boss agents received:",M.map(R=>({id:R.id,name:R.name,subordinateIds:R.subordinateIds}))),H.setAgents(T),(e=Pe.onAgentsSync)==null||e.call(Pe,T),H.loadToolHistory();for(const R of T)Rk(R);break}case"agent_created":{const T=t.payload;console.log("[WebSocket] Agent created:",T),H.addAgent(T);const M=(n=window.__spawnModalAreaContext)==null?void 0:n.areaId;M&&(H.assignAgentToArea(T.id,M),window.__spawnModalAreaContext=null),H.selectAgent(T.id),(s=Pe.onAgentCreated)==null||s.call(Pe,T),(a=Pe.onSpawnSuccess)==null||a.call(Pe),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=Pe.onToast)==null||r.call(Pe,"success","Agent Deployed",`${T.name} is ready for commands`);break}case"agent_updated":{const T=t.payload,R=H.getState().agents.get(T.id),P=(R==null?void 0:R.status)!==T.status;console.log(`[Tide] Agent updated: ${T.name} (${T.id}) status=${T.status} (was ${R==null?void 0:R.status})${P?" ⚡ STATUS CHANGED":""}`),P&&console.log(`[Tide] 🔔 Status change for ${T.name}: ${R==null?void 0:R.status} → ${T.status}`),P&&(R==null?void 0:R.status)==="working"&&T.status==="idle"&&H.triggerHistoryRefresh(T.id);const U=R?R.position.x!==T.position.x||R.position.z!==T.position.z:!1;H.updateAgent(T),Rk(T),(i=Pe.onAgentUpdated)==null||i.call(Pe,T,U);break}case"agent_deleted":{const{id:T}=t.payload;Qc.delete(T),H.removeAgent(T),(c=Pe.onAgentDeleted)==null||c.call(Pe,T);break}case"activity":{const T=t.payload;H.addActivity(T);break}case"event":{const T=t.payload;if(xu.debug(`Event: ${T.type}`,{agentId:T.agentId,toolName:T.toolName},"ws:event"),T.type==="tool_start"&&T.toolName&&((d=Pe.onToolUse)==null||d.call(Pe,T.agentId,T.toolName,T.toolInput),H.addToolExecution(T.agentId,T.toolName,T.toolInput),T.toolInput)){const M=T.toolInput.file_path||T.toolInput.path;M&&(T.toolName==="Write"?H.addFileChange(T.agentId,"created",M):T.toolName==="Edit"?H.addFileChange(T.agentId,"modified",M):T.toolName==="Read"&&H.addFileChange(T.agentId,"read",M))}break}case"output":{const T=t.payload;xu.debug(`Output: "${T.text.slice(0,80)}..."`,{agentId:T.agentId,isStreaming:T.isStreaming,length:T.text.length,hasSkillUpdate:!!T.skillUpdate,uuid:T.uuid,toolName:T.toolName},"ws:output"),H.addOutput(T.agentId,{text:T.text,isStreaming:T.isStreaming,timestamp:T.timestamp,isDelegation:T.isDelegation,skillUpdate:T.skillUpdate,subagentName:T.subagentName,uuid:T.uuid,toolName:T.toolName,toolInput:T.toolInput,toolOutput:T.toolOutput});break}case"context_stats":{const{agentId:T,stats:M}=t.payload;console.log(`[Tide] Received context stats for agent ${T}: ${M.usedPercent}% used`),H.updateAgentContextStats(T,M);break}case"context_update":{const{agentId:T,contextUsed:M,contextLimit:R}=t.payload;H.updateAgentContext(T,M,R);break}case"compacting_status":{const{agentId:T,active:M}=t.payload;H.setAgentCompacting(T,M);break}case"error":{const T=t.payload;console.error("[WebSocket] Error from server:",T.message),(f=Pe.onToast)==null||f.call(Pe,"error","Error",T.message),(h=Pe.onSpawnError)==null||h.call(Pe),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:T}=t.payload;console.log("[WebSocket] Directory not found:",T),(m=Pe.onDirectoryNotFound)==null||m.call(Pe,T),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(T));break}case"command_started":{const{agentId:T,command:M}=t.payload,R=M.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;H.addUserPromptToOutput(T,M);break}case"session_updated":{const{agentId:T}=t.payload;H.loadToolHistory(),H.triggerHistoryRefresh(T);const M=H.getState().agents.get(T);M&&H.updateAgent({...M});break}case"supervisor_report":{const T=t.payload;H.setSupervisorReport(T);break}case"narrative_update":{const{agentId:T,narrative:M}=t.payload;H.addNarrative(T,M);break}case"supervisor_status":{const T=t.payload;H.setSupervisorStatus(T);break}case"agent_supervisor_history":{const T=t.payload;H.setAgentSupervisorHistory(T);break}case"agent_analysis":{const{agentId:T,analysis:M}=t.payload;H.addAgentAnalysis(T,M);break}case"areas_update":{const T=t.payload;H.setAreasFromServer(T),(x=Pe.onAreasSync)==null||x.call(Pe);break}case"buildings_update":{const T=t.payload;H.setBuildingsFromServer(T);break}case"building_created":{const T=t.payload;H.addBuilding(T);break}case"building_updated":{const T=t.payload;H.updateBuildingFromServer(T),(y=Pe.onBuildingUpdated)==null||y.call(Pe,T);break}case"building_deleted":{const{id:T}=t.payload;H.removeBuildingFromServer(T);break}case"building_logs":{const{buildingId:T,logs:M}=t.payload;H.addBuildingLogs(T,M);break}case"pm2_logs_chunk":{const{buildingId:T,chunk:M}=t.payload;H.appendStreamingLogChunk(T,M);break}case"pm2_logs_streaming":{const{buildingId:T,streaming:M}=t.payload;H.setStreamingStatus(T,M);break}case"docker_logs_chunk":{const{buildingId:T,chunk:M}=t.payload;H.appendStreamingLogChunk(T,M);break}case"docker_logs_streaming":{const{buildingId:T,streaming:M}=t.payload;H.setStreamingStatus(T,M);break}case"docker_containers_list":{const{containers:T,composeProjects:M}=t.payload;console.log(`[WebSocket] Received ${T.length} containers, ${M.length} compose projects`),H.setDockerContainersList(T,M);break}case"boss_building_logs_chunk":{const{bossBuildingId:T,subordinateBuildingId:M,subordinateBuildingName:R,chunk:P,isError:U}=t.payload;H.appendBossStreamingLogChunk(T,M,R,P,U);break}case"boss_building_subordinates_updated":{const{bossBuildingId:T,subordinateBuildingIds:M}=t.payload;H.updateBuilding(T,{subordinateBuildingIds:M});break}case"permission_request":{const T=t.payload;H.addPermissionRequest(T);break}case"permission_resolved":{const{requestId:T,approved:M}=t.payload;H.resolvePermissionRequest(T,M);break}case"delegation_decision":{const T=t.payload;H.handleDelegationDecision(T),T.status==="sent"&&((v=Pe.onToast)==null||v.call(Pe,"info","Task Delegated",`Delegated to ${T.selectedAgentName}: ${T.reasoning.slice(0,80)}...`),T.bossId&&T.selectedAgentId&&((S=Pe.onDelegation)==null||S.call(Pe,T.bossId,T.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:T,subordinateIds:M}=t.payload;H.updateBossSubordinates(T,M);break}case"delegation_history":{const{bossId:T,decisions:M}=t.payload;H.setDelegationHistory(T,M);break}case"session_history":{const{agentId:T,entries:M}=t.payload;H.setSessionHistory(T,M);break}case"boss_spawned_agent":{const{agent:T,bossPosition:M}=t.payload;console.log("[WebSocket] Boss spawned agent:",T.name,"- walking to boss at",M),H.addAgent(T),(C=Pe.onAgentCreated)==null||C.call(Pe,T),ox({type:"move_agent",payload:{agentId:T.id,position:M}}),(k=Pe.onToast)==null||k.call(Pe,"success","Agent Deployed",`${T.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:T,subordinateId:M,subordinateName:R,taskDescription:P}=t.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${T}: ${P.slice(0,50)}...`),H.handleAgentTaskStarted(T,M,R,P);break}case"agent_task_output":{const{bossId:T,subordinateId:M,output:R,isStreaming:P,timestamp:U,subagentName:q,toolName:z,toolInput:F,toolOutput:$}=t.payload;H.handleAgentTaskOutput(T,M,{text:R,isStreaming:P||!1,timestamp:U||Date.now(),subagentName:q,toolName:z,toolInput:F,toolOutput:$});break}case"agent_task_completed":{const{bossId:T,subordinateId:M,success:R}=t.payload;console.log(`[WebSocket] Agent task completed for boss ${T}, subordinate ${M}, success: ${R}`),H.handleAgentTaskCompleted(T,M,R);break}case"skills_update":{const T=t.payload;H.setSkillsFromServer(T);break}case"skill_created":{const T=t.payload;H.addSkillFromServer(T),console.log(`[WebSocket] Skill created: ${T.name}`);break}case"skill_updated":{const T=t.payload;H.updateSkillFromServer(T),console.log(`[WebSocket] Skill updated: ${T.name}`);break}case"skill_deleted":{const{id:T}=t.payload;H.removeSkillFromServer(T),console.log(`[WebSocket] Skill deleted: ${T}`);break}case"agent_skills":{const{agentId:T,skills:M}=t.payload;console.log(`[WebSocket] Agent ${T} has ${M.length} skills`);break}case"custom_agent_classes_update":{const T=t.payload;H.setCustomAgentClassesFromServer(T),console.log(`[WebSocket] Received ${T.length} custom agent classes`);const M=new Map;for(const R of T)M.set(R.id,R);(N=Pe.onCustomClassesSync)==null||N.call(Pe,M);break}case"custom_agent_class_created":{const T=t.payload;H.addCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class created: ${T.name}`),(A=Pe.onCustomClassesSync)==null||A.call(Pe,H.getState().customAgentClasses);break}case"custom_agent_class_updated":{const T=t.payload;H.updateCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class updated: ${T.name}`),(E=Pe.onCustomClassesSync)==null||E.call(Pe,H.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:T}=t.payload;H.removeCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class deleted: ${T}`),(D=Pe.onCustomClassesSync)==null||D.call(Pe,H.getState().customAgentClasses);break}case"global_usage":{const T=t.payload;console.log("[WebSocket] Global usage update:",T),H.setGlobalUsage(T);break}case"agent_notification":{const T=t.payload;console.log(`[WebSocket] Agent notification from ${T.agentName}: ${T.title}`),(_=Pe.onAgentNotification)==null||_.call(Pe,T);break}case"focus_agent":{const{agentId:T,openTerminal:M}=t.payload;if(!H.getState().agents.get(T)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${T}`);break}H.selectAgent(T),M&&H.setTerminalOpen(!0);const P=[0,80,220,500,1e3];for(const U of P)window.setTimeout(()=>{window.focus()},U);break}case"exec_task_started":{const{taskId:T,agentId:M,agentName:R,command:P,cwd:U}=t.payload;console.log(`[WebSocket] Exec task started: ${T} for agent ${R}: ${P.slice(0,50)}...`),H.handleExecTaskStarted(T,M,R,P,U);break}case"exec_task_output":{const{taskId:T,agentId:M,output:R,isError:P}=t.payload;H.handleExecTaskOutput(T,M,R,P);break}case"exec_task_completed":{const{taskId:T,agentId:M,exitCode:R,success:P}=t.payload;console.log(`[WebSocket] Exec task completed: ${T} for agent ${M}, success: ${P}`),H.handleExecTaskCompleted(T,M,R,P);break}case"subagent_started":{const T=t.payload;console.log(`[WebSocket] Subagent started: ${T.name} (${T.id}) for agent ${T.parentAgentId}`),H.addSubagent(T),(I=Pe.onSubagentStarted)==null||I.call(Pe,T);break}case"subagent_output":{const{subagentId:T,parentAgentId:M,text:R,timestamp:P}=t.payload,U=R.indexOf(":");if(U>0){const q=R.slice(0,U).trim(),z=R.slice(U+1).trim();H.addSubagentActivity(T,M,{toolName:q,description:z,timestamp:P})}else R.startsWith("Using ")&&H.addSubagentActivity(T,M,{toolName:R.slice(6).trim(),description:"",timestamp:P});break}case"subagent_completed":{const{subagentId:T,parentAgentId:M,success:R,resultPreview:P,subagentName:U,durationMs:q,tokensUsed:z,toolUseCount:F}=t.payload;console.log(`[WebSocket] Subagent completed: ${T} for agent ${M}, success: ${R}`),(q||z||F)&&H.updateSubagentStats(T,M,{durationMs:q||0,tokensUsed:z||0,toolUseCount:F||0}),H.completeSubagent(T,M,R),(O=Pe.onSubagentCompleted)==null||O.call(Pe,T);const $=H.getSubagent(T)||H.getSubagentByToolUseId(T),V=U||($==null?void 0:$.name)||T,G=R?"✅":"❌",B=q?` (${(q/1e3).toFixed(0)}s · ${((z||0)/1e3).toFixed(1)}K tokens · ${F||0} tools)`:"";H.addOutput(M,{text:`${G} Subagent ${V} ${R?"completed":"failed"}${B}`,isStreaming:!1,timestamp:Date.now(),subagentName:V,toolOutput:P});break}case"subagent_stream":{const{toolUseId:T,parentAgentId:M,entries:R}=t.payload;H.addSubagentStreamEntries(T,M,R);break}case"secrets_update":{const T=t.payload;H.setSecretsFromServer(T),console.log(`[WebSocket] Received ${T.length} secrets`);break}case"secret_created":{const T=t.payload;H.addSecretFromServer(T),console.log(`[WebSocket] Secret created: ${T.name}`);break}case"secret_updated":{const T=t.payload;H.updateSecretFromServer(T),console.log(`[WebSocket] Secret updated: ${T.name}`);break}case"secret_deleted":{const{id:T}=t.payload;H.removeSecretFromServer(T),console.log(`[WebSocket] Secret deleted: ${T}`);break}case"database_connection_result":{const{buildingId:T,connectionId:M,success:R,error:P,serverVersion:U}=t.payload;H.setConnectionStatus(T,M,{connected:R,error:P,serverVersion:U}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${M}`);break}case"databases_list":{const{buildingId:T,connectionId:M,databases:R}=t.payload;H.setDatabases(T,M,R),console.log(`[WebSocket] Received ${R.length} databases for ${M}`);break}case"tables_list":{const{buildingId:T,connectionId:M,database:R,tables:P}=t.payload;H.setTables(T,M,R,P),console.log(`[WebSocket] Received ${P.length} tables for ${R}`);break}case"table_schema":{const{buildingId:T,connectionId:M,database:R,table:P,columns:U,indexes:q,foreignKeys:z}=t.payload;H.setTableSchema(T,M,R,P,{columns:U,indexes:q||[],foreignKeys:z||[]}),console.log(`[WebSocket] Received schema for ${P}`);break}case"query_result":{const{buildingId:T,result:M}=t.payload;H.setQueryResult(T,M),console.log(`[WebSocket] Query ${M.status}: ${M.rowCount??M.affectedRows??0} rows in ${M.duration}ms`);break}case"silent_query_result":{const{buildingId:T,query:M,requestId:R,success:P,affectedRows:U,error:q}=t.payload;H.setSilentQueryResult(T,{query:M,requestId:R,success:P,affectedRows:U,error:q}),console.log(`[WebSocket] Silent query ${P?"succeeded":"failed"}: ${U??0} affected rows`);break}case"query_history_update":{const{buildingId:T,history:M}=t.payload;H.setQueryHistory(T,M),console.log(`[WebSocket] Received ${M.length} query history entries for ${T}`);break}}vb.end(`ws:${t.type}`)}MR(()=>yu());let Ok=!1;function xj(){const t=yp();t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Page unloading");const e=dj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),_R()}function HR(){Ok||(window.addEventListener("beforeunload",xj),Ok=!0)}function yj(){xj(),H.setConnected(!1),H.stopStatusPolling()}function UR(){yj(),yb(0),setTimeout(()=>yu(),100)}function yu(){HR();const t=dj();t&&(clearTimeout(t),fj(null));const e=yp();if(TR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Mk()&&Pe.onReconnect&&Pe.onReconnect();return}yb(xb()+1),Mc(!0);const n=nx(),s=Ti(),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{Mc(!1),Lk();return}Ek(i),i.onopen=()=>{var d,f,h;const c=Mk();Mc(!1),yb(0),ER(),H.setConnected(!0),H.startStatusPolling(),H.clearAllPermissions(),c?((d=Pe.onToast)==null||d.call(Pe,"success","Reconnected","Connection restored - refreshing data..."),(f=Pe.onReconnect)==null||f.call(Pe)):(h=Pe.onToast)==null||h.call(Pe,"success","Connected","Connected to Tide Commander server"),NR(n,s),BR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=ix(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&ms.captureReceived(f,c.data),$R(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;Mc(!1),Ek(null),H.setConnected(!1),H.stopStatusPolling();const c=xb();c<_k?((d=Pe.onToast)==null||d.call(Pe,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${_k})`),Lk()):(f=Pe.onToast)==null||f.call(Pe,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{Mc(!1)},H.setSendMessage(ox)}function Lk(){const t=xb(),e=Math.min(1e3*Math.pow(2,t-1),3e4);fj(setTimeout(yu,e))}function WR(t,e){const n={position:t,target:e};va(ft.CAMERA_STATE,n)}function qR(){return na(ft.CAMERA_STATE,null)}function Qq(t,e,n){const s={posX:t,posZ:e,zoom:n};va(ft.CAMERA_STATE_2D,s)}function Xq(){return na(ft.CAMERA_STATE_2D,null)}function Ml(){return{Authorization:`Bearer ${Ti()}`,"Content-Type":"application/json"}}async function VR(){const t=await fetch(`${Ca()}/api/workspaces`,{headers:Ml()});if(!t.ok)throw new Error(`Failed to fetch workspaces: ${t.statusText}`);return t.json()}async function GR(t,e){const n=await fetch(`${Ca()}/api/workspaces`,{method:"POST",headers:Ml(),body:JSON.stringify({name:t,areaIds:e})});if(!n.ok)throw new Error(`Failed to create workspace: ${n.statusText}`);return n.json()}async function Pk(t,e){const n=await fetch(`${Ca()}/api/workspaces/${t}`,{method:"PUT",headers:Ml(),body:JSON.stringify(e)});if(!n.ok)throw new Error(`Failed to update workspace: ${n.statusText}`);return n.json()}async function YR(t){const e=await fetch(`${Ca()}/api/workspaces/${t}`,{method:"DELETE",headers:Ml()});if(!e.ok)throw new Error(`Failed to delete workspace: ${e.statusText}`)}async function KR(){const t=await fetch(`${Ca()}/api/workspaces/active`,{headers:Ml()});if(!t.ok)throw new Error(`Failed to get active workspace: ${t.statusText}`);return(await t.json()).activeWorkspaceId??null}async function Ik(t){const e=await fetch(`${Ca()}/api/workspaces/active`,{method:"PUT",headers:Ml(),body:JSON.stringify({workspaceId:t})});if(!e.ok)throw new Error(`Failed to set active workspace: ${e.statusText}`)}const vu=new Set;let Xa=null,no=[],vj=!1;const kb=new Set;function tg(t){vj=t,kb.forEach(e=>e(t))}const wj="tide-commander-active-workspace";function Bk(){return typeof window>"u"?null:localStorage.getItem(wj)||null}function ng(t){typeof window>"u"||localStorage.setItem(wj,t||"")}function Rc(){vu.forEach(t=>t())}function QR(){return Xa}function vp(t){return Xa?t?Xa.areaIds.includes(t):!1:!0}function Jq(t){return Xa?Xa.areaIds.includes(t):!0}function lx(){const[,t]=b.useState(0);return b.useEffect(()=>{const e=()=>t(n=>n+1);return vu.add(e),()=>{vu.delete(e)}},[]),[Xa,no]}function XR(t){return vu.add(t),()=>{vu.delete(t)}}function JR(){const[t,e]=b.useState(vj);return b.useEffect(()=>{const n=s=>e(s);return kb.add(n),()=>{kb.delete(n)}},[]),t}const sg=new Map,kj=Ce.memo(function(){const{t:e}=pt("common"),n=rr(),[s,a]=b.useState([]),[r,i]=b.useState(()=>Bk()),[c,d]=b.useState(!1),[f,h]=b.useState(!1),[m,x]=b.useState(!0),[y,v]=b.useState(null),[S,C]=b.useState(""),[k,N]=b.useState([]),[A,E]=b.useState(!1),D=b.useRef(null);b.useEffect(()=>{let z=!1;return(async()=>{try{const F=Bk(),[$,V]=await Promise.all([VR(),KR()]);if(z)return;const G=F&&$.some(B=>B.id===F)?F:V&&$.some(B=>B.id===V)?V:null;a($),no=$,i(G),ng(G),Xa=$.find(B=>B.id===G)??null,Rc()}catch(F){console.error("workspace error:",F)}finally{z||x(!1)}})(),()=>{z=!0}},[]),b.useEffect(()=>{if(!c&&!f)return;const z=F=>{D.current&&!D.current.contains(F.target)&&(d(!1),h(!1))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[c,f]);const _=b.useMemo(()=>s.find(z=>z.id===r)??null,[s,r]),I=b.useCallback(async z=>{tg(!0);const F=Date.now();if(r){const B=qR();B&&(sg.set(r,B),Pk(r,{cameraState:B}).then(Q=>{a(K=>{const W=K.map(be=>be.id===r?Q:be);return no=W,W})}).catch(Q=>console.error("workspace error:",Q)))}i(z),ng(z),d(!1);const $=z?s.find(B=>B.id===z)??null:null;if(Xa=$,no=s,Rc(),z){const Q=($==null?void 0:$.cameraState)??sg.get(z);Q&&(WR(Q.position,Q.target),sg.set(z,Q))}Ik(z).catch(B=>console.error("workspace error:",B));const V=Date.now()-F,G=400;V<G?setTimeout(()=>tg(!1),G-V):tg(!1)},[r,s]),O=b.useMemo(()=>Array.from(n.values()).filter(z=>!z.archived),[n]),T=b.useCallback(async()=>{if(S.trim())try{const z=await GR(S.trim(),k),F=[...s,z];a(F),no=F,Rc(),C(""),N([]),E(!1)}catch(z){console.error("workspace error:",z)}},[S,k,s]),M=b.useCallback(async()=>{if(!(!y||!S.trim()))try{const z=await Pk(y,{name:S.trim(),areaIds:k}),F=s.map($=>$.id===y?z:$);a(F),no=F,y===r&&(Xa=z),Rc(),v(null),C(""),N([])}catch(z){console.error("workspace error:",z)}},[y,S,k,s,r]),R=b.useCallback(async z=>{try{await YR(z);const F=s.filter($=>$.id!==z);a(F),no=F,r===z&&(i(null),ng(null),Xa=null,await Ik(null).catch($=>console.error("workspace error:",$))),Rc()}catch(F){console.error("workspace error:",F)}},[s,r]),P=b.useCallback(z=>{v(z.id),C(z.name),N([...z.areaIds]),E(!1)},[]),U=b.useCallback(()=>{v(null),C(""),N([]),E(!0)},[]),q=b.useCallback(z=>{N(F=>F.includes(z)?F.filter($=>$!==z):[...F,z])},[]);return m?null:o.jsxs("div",{className:"workspace-switcher",ref:D,children:[o.jsxs("button",{className:"workspace-switcher-trigger",onClick:()=>{d(!c),h(!1)},title:"Workspaces",children:[o.jsx("span",{className:"workspace-switcher-icon",children:"📂"}),o.jsx("span",{className:"workspace-switcher-label",children:_?_.name:e("agentBar.allWorkspaces",{defaultValue:"All"})}),o.jsx("span",{className:"workspace-switcher-arrow",children:c?"▲":"▼"})]}),c&&!f&&o.jsxs("div",{className:"workspace-switcher-dropdown",children:[o.jsx("button",{className:`workspace-switcher-option ${r?"":"active"}`,onClick:()=>I(null),children:e("agentBar.allWorkspaces",{defaultValue:"All"})}),s.map(z=>o.jsxs("button",{className:`workspace-switcher-option ${z.id===r?"active":""}`,onClick:()=>I(z.id),children:[z.name,o.jsx("span",{className:"workspace-switcher-option-count",children:z.areaIds.length})]},z.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(z=>o.jsx("div",{className:"workspace-switcher-manager-item",children:y===z.id?o.jsxs("div",{className:"workspace-switcher-editor",children:[o.jsx("input",{type:"text",value:S,onChange:F=>C(F.target.value),className:"workspace-switcher-input",placeholder:"Workspace name",autoFocus:!0,onKeyDown:F=>{F.key==="Enter"&&M(),F.key==="Escape"&&v(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:()=>q(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:()=>v(null),children:"Cancel"})]})]}):o.jsxs("div",{className:"workspace-switcher-manager-row",children:[o.jsx("span",{className:"workspace-switcher-manager-name",children:z.name}),o.jsxs("span",{className:"workspace-switcher-manager-count",children:[z.areaIds.length," areas"]}),o.jsx("button",{className:"workspace-switcher-btn-edit",onClick:()=>P(z),title:"Edit",children:"✏"}),o.jsx("button",{className:"workspace-switcher-btn-delete",onClick:()=>R(z.id),title:"Delete",children:"🗑"})]})},z.id))}),A?o.jsxs("div",{className:"workspace-switcher-editor workspace-switcher-create-form",children:[o.jsx("input",{type:"text",value:S,onChange:z=>C(z.target.value),className:"workspace-switcher-input",placeholder:"New workspace name",autoFocus:!0,onKeyDown:z=>{z.key==="Enter"&&T(),z.key==="Escape"&&E(!1)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[O.map(z=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(z.id),onChange:()=>q(z.id)}),o.jsx("span",{style:{color:z.color},children:z.name})]},z.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:T,children:"Create"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>E(!1),children:"Cancel"})]})]}):o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-add",onClick:U,children:["+ ",e("agentBar.newWorkspace",{defaultValue:"New Workspace"})]})]})]})}),qf="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 wp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function Sj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function ZR(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function wu(t){typeof window<"u"&&(window.__tidePersistedScene=t)}function iu(t){typeof window<"u"&&(window.__tidePersistedCanvas=t)}function Cj(t){typeof window<"u"&&(window.__tideWsConnected=t)}function eO(t){typeof window<"u"&&(window.__tideIsPageUnloading=t)}function tO(){sessionStorage.setItem(qf,"true")}function Zd(t){eO(!0),sessionStorage.removeItem(qf),yj(),DR(),window.__tideScene&&(window.__tideScene=null);const e=wp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),wu(null)):console.log("[App] No persistedScene to dispose"),iu(null),Cj(!1);const n=document.getElementById("battlefield");n&&n.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function nO(){var a,r;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(qf)==="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=wp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}wu(null)}const n=document.getElementById("battlefield"),s=Sj();n&&n!==s&&n.remove(),sessionStorage.removeItem(qf)}function sO(){typeof window>"u"||(nO(),window.addEventListener("pageshow",t=>{t.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Zd(),window.location.reload())}),window.onunload=()=>Zd(),window.onbeforeunload=t=>{Zd()},window.addEventListener("pagehide",t=>{Zd(`pagehide (persisted=${t.persisted})`)}))}sO();const Fk={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},zk={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},$k={idleAnimation:"sit",workingAnimation:"sprint"},aO=0;function Aj(){const t={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:Fk,modelStyle:zk,animations:$k,fpsLimit:aO},e=na(ft.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:{...Fk,...e.terrain},modelStyle:{...zk,...e.modelStyle},animations:{...$k,...e.animations},fpsLimit:e.fpsLimit??t.fpsLimit}}return t}function rO(t){va(ft.CONFIG,t)}function iO(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function jj(){console.log("[Tide HMR] Manual scene refresh triggered");const t=wp();if(t){try{t.dispose()}catch(n){console.warn("[Tide HMR] Error disposing scene:",n)}wu(null)}iu(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=jj);function oO({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:x,openBossLogsModal:y,openDatabasePanel:v,onSceneLoadingChange:S}){const C=b.useRef(null),k=b.useRef(null),N=b.useRef(null),A=b.useRef(null),E=b.useRef(null);return b.useEffect(()=>{if(n!=="3d"){S==null||S(!1);return}if(!t.current||!e.current)return;let D=!1;S==null||S(!0);const _=wp(),O=Sj()===t.current;function T(){var R,P,U,q,z,F,$,V;(R=C.current)==null||R.setOnToast(a),(P=C.current)==null||P.setOnBuildingClick((G,B)=>{H.selectBuilding(G);const Q=H.getState().buildings.get(G);(Q==null?void 0:Q.type)==="folder"&&Q.folderPath?H.openFileExplorer(Q.folderPath):(Q==null?void 0:Q.type)==="server"||(Q==null?void 0:Q.type)==="boss"||(Q==null?void 0:Q.type)==="database"?(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{f({buildingId:G,screenPos:B,fromClick:!0}),k.current=null},150)):m(G)}),(U=C.current)==null||U.setOnContextMenu((G,B,Q)=>{c.open(G,B,Q)}),(q=C.current)==null||q.setOnAgentHover(()=>{}),(z=C.current)==null||z.setOnBuildingHover((G,B)=>{const Q=h();if(G&&B){const K=H.getState().buildings.get(G);((K==null?void 0:K.type)==="server"||(K==null?void 0:K.type)==="boss"||(K==null?void 0:K.type)==="database")&&!(Q!=null&&Q.fromClick)&&f({buildingId:G,screenPos:B,fromClick:!1})}else Q!=null&&Q.fromClick||f(null)}),(F=C.current)==null||F.setOnGroundClick(()=>{f(null)}),($=C.current)==null||$.setOnAreaDoubleClick(G=>{H.selectArea(G),i.open()}),(V=C.current)==null||V.setOnBuildingDoubleClick(G=>{var Q;k.current&&(clearTimeout(k.current),k.current=null),f(null);const B=H.getState().buildings.get(G);(B==null?void 0:B.type)==="server"&&((Q=B.pm2)!=null&&Q.enabled)?x==null||x(G):(B==null?void 0:B.type)==="boss"?y==null||y(G):(B==null?void 0:B.type)==="database"?v==null||v(G):(B==null?void 0:B.type)==="folder"&&B.folderPath?H.openFileExplorer(B.folderPath):m(G)})}if(_)try{C.current=_,O?(console.log("[Tide] Reusing existing scene (StrictMode remount)"),_.ensureRenderLoopRunning()):(console.log("[Tide] Reattaching persisted scene to new canvas"),_.reattach(t.current,e.current),iu(t.current));const R=H.getState();_.syncAreas(),_.syncBuildings(),R.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",R.agents.size),_.syncAgents(Array.from(R.agents.values()))),T()}catch(R){console.error("[Tide] Failed to reattach persisted 3D scene:",R),S==null||S(!1)}finally{A.current=requestAnimationFrame(()=>{E.current=requestAnimationFrame(()=>{S==null||S(!1),E.current=null}),A.current=null})}else{const R=t.current,P=e.current,U=async()=>{if(D){console.log("[Tide] Effect cleaned up before scene init, skipping"),S==null||S(!1);return}if(!R.isConnected||!P.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),S==null||S(!1);return}(!R.clientWidth||!R.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),R.style.width="100%",R.style.height="100%",R.offsetHeight),(!R.clientWidth||!R.clientHeight)&&(R.width=window.innerWidth,R.height=window.innerHeight),tO();try{const{SceneManager:q}=await vt(async()=>{const{SceneManager:$}=await import("./SceneManager-CzgjrwbM.js");return{SceneManager:$}},__vite__mapDeps([6,4,3,1]));if(D){S==null||S(!1);return}const z=new q(R,P);C.current=z,wu(z),iu(R);const F=Aj();z.setCharacterScale(F.characterScale),z.setScale3D(F.scale3d),z.setTimeMode(F.timeMode),z.setTerrainConfig(F.terrain),z.setFloorStyle(F.terrain.floorStyle,!0),z.setGridVisible(F.gridVisible),z.setAgentModelStyle(F.modelStyle),z.setIdleAnimation(F.animations.idleAnimation),z.setWorkingAnimation(F.animations.workingAnimation),z.setFpsLimit(F.fpsLimit),z.syncAreas(),z.syncBuildings(),z.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const $=H.getState();$.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",$.customAgentClasses.size),z.setCustomAgentClasses($.customAgentClasses)),$.agents.size>0&&(console.log("[Tide] Syncing agents from store:",$.agents.size),z.syncAgents(Array.from($.agents.values()))),z.upgradeAgentModels()}).catch($=>{console.warn("[Tide] Some models failed to load, using fallback:",$)}).finally(()=>{S==null||S(!1)}),T()}catch(q){console.error("[Tide] Failed to initialize 3D scene:",q),S==null||S(!1)}};N.current=requestAnimationFrame(()=>void U())}hj({onAgentCreated:R=>{var P,U,q;(P=C.current)==null||P.addAgent(R),(U=C.current)==null||U.refreshSelectionVisuals(),(q=window.__spawnModalSuccess)==null||q.call(window)},onAgentUpdated:(R,P)=>{var q;const U=H.getState().agents.get(R.id)||R;(q=C.current)==null||q.updateAgent(U,P)},onAgentDeleted:R=>{var P;(P=C.current)==null||P.removeAgent(R)},onAgentsSync:R=>{var U;const P=Array.from(H.getState().agents.values());(U=C.current)==null||U.syncAgents(P)},onAreasSync:()=>{var P,U;(P=C.current)==null||P.syncAreas();const R=Array.from(H.getState().agents.values());(U=C.current)==null||U.syncAgents(R)},onSpawnError:()=>{var R;(R=window.__spawnModalError)==null||R.call(window)},onSpawnSuccess:()=>{var R;(R=window.__spawnModalSuccess)==null||R.call(window)},onDirectoryNotFound:R=>{var P;(P=window.__spawnModalDirNotFound)==null||P.call(window,R)},onToolUse:(R,P,U)=>{var q;(q=C.current)==null||q.showToolBubble(R,P,U)},onDelegation:(R,P)=>{var U;(U=C.current)==null||U.showDelegationEffect(R,P)},onCustomClassesSync:R=>{var P,U;(P=C.current)==null||P.setCustomAgentClasses(R),(U=C.current)==null||U.upgradeAgentModels()},onBuildingUpdated:R=>{var P;(P=C.current)==null||P.updateBuilding(R)},onSubagentStarted:R=>{var P;(P=C.current)==null||P.addSubagentEffect(R.id,R.parentAgentId,R.name,R.subagentType)},onSubagentCompleted:R=>{var q;const P=H.getSubagent(R)||H.getSubagentByToolUseId(R),U=(P==null?void 0:P.id)||R;(q=C.current)==null||q.completeSubagentEffect(U),setTimeout(()=>{var z;(z=C.current)==null||z.removeSubagentEffect(U)},3e4)}});const M=XR(()=>{if(C.current){C.current.syncAreas(),C.current.syncBuildings();const R=Array.from(H.getState().agents.values());C.current.syncAgents(R)}});return()=>{M(),D=!0,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),H.getState().viewMode!=="3d"&&iO()&&C.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),RR(),C.current.dispose(),C.current=null,wu(null),iu(null))}},[n,s]),C}function lO({showToast:t,showAgentNotification:e}){b.useEffect(()=>{hj({onToast:t,onReconnect:()=>{H.triggerReconnect()},onAgentNotification:a=>{e(a)}}),ZR()||(yu(),Cj(!0)),CR();let n;jR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&uj(a.agentId)}).then(a=>{n=a});const s=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>yu(),100)};return window.addEventListener("tideAppResume",s),()=>{window.removeEventListener("tideAppResume",s),n==null||n()}},[t,e])}function cO(t){b.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 x=`${h.position.x.toFixed(2)},${h.position.z.toFixed(2)},${h.status},${h.class},${h.isBoss},${((d=h.subordinateIds)==null?void 0:d.length)??0}`.split("").reduce((y,v)=>(y<<5)-y+v.charCodeAt(0),0);c.set(f,x),s.get(f)!==x&&(i=!0)}return c.size!==s.size&&(i=!0),{newVersion:c,changed:i}};return H.subscribe(()=>{var x;const r=H.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,(x=t.current)==null||x.refreshSelectionVisuals())})},[t])}function uO(t){b.useEffect(()=>{var s;(s=t.current)==null||s.syncAreas();let e=0,n=0;return H.subscribe(()=>{var c,d;const r=H.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 x=0;x<h.name.length;x++)m+=h.name.charCodeAt(x);for(let x=0;x<h.color.length;x++)m+=h.color.charCodeAt(x);if(h.directoryGitCounts)for(const x of h.directoryGitCounts)m+=(x+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 x=0;x<h.logo.position.length;x++)m+=h.logo.position.charCodeAt(x);if(h.logo.filename)for(let x=0;x<h.logo.filename.length;x++)m+=h.logo.filename.charCodeAt(x)}i^=m|0}i!==n&&(n=i,(d=t.current)==null||d.syncAreas())})},[t])}function dO(t){b.useEffect(()=>{var s;(s=t.current)==null||s.syncBuildings();let e=0,n=0;return H.subscribe(()=>{var c,d;const r=H.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 x=0;x<m.length;x++)i=(i<<5)-i+m.charCodeAt(x)|0}i!==n&&(n=i,(d=t.current)==null||d.syncBuildings())})},[t])}function fO(t,e){b.useEffect(()=>{var n;(n=t.current)==null||n.highlightArea(e)},[t,e])}function pO(t,e){b.useEffect(()=>{var n;(n=t.current)==null||n.setPowerSaving(e)},[t,e])}function Bt(t,e,n,s,a={},r="global"){return{id:t,name:e,description:n,key:s,modifiers:a,enabled:!0,context:r}}const ag=[Bt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Bt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Bt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Bt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Bt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Bt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Bt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Bt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Bt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Bt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Bt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Bt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Bt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Bt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Bt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Bt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Bt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Bt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Bt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Bt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Bt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Bt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Bt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Bt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Bt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Bt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Bt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Bt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Bt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Bt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Bt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Bt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Bt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Bt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Bt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Bt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Bt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Bt("clear-context","Clear Context","Clear context of the selected agent","c",{alt:!0,shift:!0}),Bt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Bt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Bt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Bt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Bt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Bt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Bt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Bt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Bt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Bt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function kn(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 hO(t){return t===" "||t==="Space"?"space":(t.length===1,t.toLowerCase())}function mO(t){const e=t.trim().toLowerCase();if(e==="space")return"Space";if(e==="esc")return"Escape";if(e==="return")return"Enter";const n={escape:"Escape",enter:"Enter",tab:"Tab",backspace:"Backspace",delete:"Delete",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown"};return n[e]?n[e]:e}function gO(t){if(!(t!=null&&t.key))return"";const e=[];return t.modifiers.ctrl&&e.push("ctrl"),t.modifiers.alt&&e.push("alt"),t.modifiers.shift&&e.push("shift"),t.modifiers.meta&&e.push("meta"),e.push(hO(t.key)),e.join("+")}function cx(t){if(!t)return null;const e=t.split("+").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return null;const n=e[e.length-1],s={};for(const r of e.slice(0,-1))r==="ctrl"||r==="control"?s.ctrl=!0:r==="alt"||r==="option"?s.alt=!0:r==="shift"?s.shift=!0:(r==="meta"||r==="cmd"||r==="command")&&(s.meta=!0);const a=mO(n);return a?{key:a,modifiers:s}:null}function bO(t){const e=cx(t);return e?Sb({key:e.key,modifiers:e.modifiers}):""}function xO(t,e){const n=cx(e);return n?kn(t,{key:n.key,modifiers:n.modifiers,enabled:!0}):!1}function Sb(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 yO(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 vO({sceneRef:t,spawnModal:e,commanderModal:n,explorerModal:s,spotlightModal:a,deleteConfirmModal:r,onRequestBuildingDelete:i,onOpenDatabasePanel:c,onCloseDatabasePanel:d,databasePanelOpen:f}){b.useEffect(()=>{const h=m=>{var P,U,q,z,F;const x=H.getShortcuts(),y=m.target,v=y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true"||!!y.closest(".cm-editor"),S=H.getState(),C=x.find($=>$.id==="deselect-all");if(kn(m,C)){if(y.closest(".guake-bottom-terminal-embed"))return;if(Cf()){m.preventDefault();return}if(S.activeTool==="rectangle"||S.activeTool==="circle"){(P=t.current)==null||P.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():S.terminalOpen?(H.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(H.deselectAll(),(U=t.current)==null||U.refreshSelectionVisuals())}for(let $=1;$<=9;$++){const V=x.find(G=>G.id===`select-agent-${$}`);if(kn(m,V)){m.preventDefault();const G=H.getState(),B=$-1,Q=Array.from(G.agents.keys());B<Q.length&&(H.selectAgent(Q[B]),(q=t.current)==null||q.refreshSelectionVisuals());return}}const k=x.find($=>$.id==="spawn-agent");if(kn(m,k)){m.preventDefault(),e.open();return}const N=x.find($=>$.id==="toggle-commander-tab");if(kn(m,N)&&!v){m.preventDefault(),n.toggle();return}const A=x.find($=>$.id==="toggle-commander");if(kn(m,A)){m.preventDefault(),n.toggle();return}const E=x.find($=>$.id==="toggle-file-explorer");if(kn(m,E)){m.preventDefault();const $=H.getState();if(s.isOpen||$.explorerFolderPath!==null||$.explorerAreaId!==null)s.close(),H.closeFileExplorer();else{const G=H.getLastExplorerState();if((G==null?void 0:G.type)==="folder")H.openFileExplorer(G.path);else if((G==null?void 0:G.type)==="area")if($.areas.has(G.areaId))s.open(G.areaId);else{const B=Array.from($.areas.values()).filter(Q=>Q.directories&&Q.directories.length>0);B.length>0&&s.open(B[0].id)}else{const B=Array.from($.areas.values()).filter(Q=>Q.directories&&Q.directories.length>0);B.length>0&&s.open(B[0].id)}}return}if(m.altKey&&!m.ctrlKey&&!m.shiftKey&&!m.metaKey&&m.code==="KeyD"){if(m.preventDefault(),m.stopPropagation(),f){d();return}const $=localStorage.getItem("tide-commander-last-database-building"),V=H.getState();if($){const G=V.buildings.get($);if((G==null?void 0:G.type)==="database"){c($);return}}for(const[G,B]of V.buildings)if(B.type==="database"){c(G);return}return}const D=x.find($=>$.id==="toggle-spotlight");if(kn(m,D)||m.altKey&&!m.ctrlKey&&!m.metaKey&&m.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:D,altKey:m.altKey,code:m.code}),m.preventDefault(),a.toggle();return}const _=x.find($=>$.id==="toggle-2d-view");if(kn(m,_)){m.preventDefault();const $=H.getState().viewMode,V=$==="3d"?"2d":$==="2d"?"dashboard":"3d";H.setViewMode(V);return}const I=x.find($=>$.id==="clear-context");if(kn(m,I)){m.preventDefault();const $=H.getState(),V=$.selectedAgentIds.size===1?Array.from($.selectedAgentIds)[0]:null;V&&H.clearContext(V);return}const O=x.find($=>$.id==="next-working-agent"),T=x.find($=>$.id==="prev-working-agent");if((kn(m,O)||kn(m,T))&&!v){const $=H.getState();if($.terminalOpen)return;const V=Array.from($.agents.values());let G=V.filter(W=>$.agentsWithUnseenOutput.has(W.id));if(G.length===0&&(G=V.filter(W=>W.status==="working")),G.length===0)return;m.preventDefault();const B=$.selectedAgentIds.size===1?Array.from($.selectedAgentIds)[0]:null,Q=B?G.findIndex(W=>W.id===B):-1;let K;kn(m,O)?K=Q===-1?0:(Q+1)%G.length:K=Q===-1?G.length-1:(Q-1+G.length)%G.length,H.selectAgent(G[K].id),(z=t.current)==null||z.refreshSelectionVisuals();return}const M=x.find($=>$.id==="delete-selected"),R=x.find($=>$.id==="delete-selected-backspace");if((kn(m,M)||kn(m,R))&&!v){const $=H.getState();if($.selectedAgentIds.size>0){m.preventDefault(),r.open();return}if($.selectedBuildingIds.size>0){m.preventDefault(),i();return}return}if(!v){const $=Array.from(S.agents.values()).find(V=>{var B;const G=(B=V.shortcut)==null?void 0:B.trim();return G?xO(m,G):!1});if($){m.preventDefault(),m.stopPropagation(),H.selectAgent($.id),H.setTerminalOpen(!0),(F=t.current)==null||F.refreshSelectionVisuals();return}}};return document.addEventListener("keydown",h,!0),()=>document.removeEventListener("keydown",h,!0)},[t,e,n,s,a,r,i,c,d,f])}function wO(){const[t,e]=b.useState(!1);return window.__tideSetBackNavModal=e,b.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()&&(Cf()||(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()?Cf()?a=Date.now():(c=window.__tideSetBackNavModal)==null||c.call(window,!0):(Cf(),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 rg="agent-order-change";function kO(t){const e=b.useMemo(()=>new Set(t.map(d=>d.id)),[t]),[n,s]=b.useState(()=>na(ft.AGENT_ORDER,[]));b.useEffect(()=>{const d=f=>{s(f.detail)};return window.addEventListener(rg,d),()=>{window.removeEventListener(rg,d)}},[]);const a=b.useMemo(()=>{const d=n.filter(x=>e.has(x)),f=t.filter(x=>!d.includes(x.id)).map(x=>x.id),h=[...d,...f],m=new Map(t.map(x=>[x.id,x]));return h.map(x=>m.get(x)).filter(x=>x!==void 0)},[t,n,e]),r=b.useCallback(d=>{s(d),va(ft.AGENT_ORDER,d),window.dispatchEvent(new CustomEvent(rg,{detail:d}))},[]),i=b.useCallback((d,f)=>{const h=a.map(x=>x.id),[m]=h.splice(d,1);h.splice(f,0,m),r(h)},[a,r]),c=b.useCallback(()=>{s([]),va(ft.AGENT_ORDER,[])},[]);return b.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 ka(t){const e=b.useRef(null),n=b.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),s=b.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),t()),e.current=null},[t]);return{handleMouseDown:n,handleClick:s}}const SO=3e4;function CO(){const t=b.useRef(null);b.useEffect(()=>{const e=async()=>{var i,c;const n=H.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 Lt(_t(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!h.ok)continue;const x=((i=(await h.json()).files)==null?void 0:i.length)||0;s.set(d,x);for(const y of f){const v=H.getState().buildings.get(y);v&&v.gitChangesCount!==x&&H.updateBuildingLocal(y,{gitChangesCount:x})}}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 x=await Lt(_t(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!x.ok)continue;h=((c=(await x.json()).files)==null?void 0:c.length)||0,s.set(d,h)}const m=new Map;for(const x of f)m.has(x.areaId)||m.set(x.areaId,[]),m.get(x.areaId).push({dirIndex:x.dirIndex,count:h});for(const[x,y]of m){const v=H.getState().areas.get(x);if(!v)continue;const S=v.directoryGitCounts?[...v.directoryGitCounts]:new Array(v.directories.length).fill(0);let C=!1;for(const{dirIndex:k,count:N}of y)S[k]!==N&&(S[k]=N,C=!0);C&&H.updateAreaLocal(x,{directoryGitCounts:S})}}catch{}};return e(),t.current=setInterval(e,SO),()=>{t.current&&(clearInterval(t.current),t.current=null)}},[])}const ig={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:"",vibrationIntensity:1,tabTitle:"",tmuxMode:!1},Hk=90,og=["simple","chat","advanced"],Uk=55,Wk=20,qk=95,AO=200,jO=12e4,NO=5,ta=new Map;function TO(t){const e=ta.get(t);e&&(ta.delete(t),ta.set(t,e))}function EO(){for(;ta.size>NO;){const t=ta.keys().next().value;if(t!==void 0)ta.delete(t);else break}}function _O(t){ta.delete(t)}function MO(t){return t.trim().replace(/\r\n/g,`
|
|
42
|
+
*/var ik;function iD(){if(ik)return Qm;ik=1;var t=Qb();function e(m,x){return m===x&&(m!==0||1/m===1/x)||m!==m&&x!==x}var n=typeof Object.is=="function"?Object.is:e,s=t.useState,a=t.useEffect,r=t.useLayoutEffect,i=t.useDebugValue;function c(m,x){var y=x(),v=s({inst:{value:y,getSnapshot:x}}),S=v[0].inst,C=v[1];return r(function(){S.value=y,S.getSnapshot=x,d(S)&&C({inst:S})},[m,y,x]),a(function(){return d(S)&&C({inst:S}),m(function(){d(S)&&C({inst:S})})},[m]),i(y),y}function d(m){var x=m.getSnapshot;m=m.value;try{var y=x();return!n(m,y)}catch{return!0}}function f(m,x){return x()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return Qm.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h,Qm}var ok;function oD(){return ok||(ok=1,Km.exports=iD()),Km.exports}var lD=oD();const cD=(t,e)=>{if(fo(e))return e;if(YM(e)&&fo(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},uD={t:cD,ready:!1},dD=()=>()=>{},pt=(t,e={})=>{var T,M,R;const{i18n:n}=e,{i18n:s,defaultNS:a}=b.useContext(aD)||{},r=n||s||nD();r&&!r.reportNamespaces&&(r.reportNamespaces=new rD),r||ub(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=b.useMemo(()=>{var P;return{...eD(),...(P=r==null?void 0:r.options)==null?void 0:P.react,...e}},[r,e]),{useSuspense:c,keyPrefix:d}=i,f=t||a||((T=r==null?void 0:r.options)==null?void 0:T.defaultNS),h=fo(f)?[f]:f||["translation"],m=b.useMemo(()=>h,h);(R=(M=r==null?void 0:r.reportNamespaces)==null?void 0:M.addUsedNamespaces)==null||R.call(M,m);const x=b.useRef(0),y=b.useCallback(P=>{if(!r)return dD;const{bindI18n:U,bindI18nStore:q}=i,z=()=>{x.current+=1,P()};return U&&r.on(U,z),q&&r.store.on(q,z),()=>{U&&U.split(" ").forEach(F=>r.off(F,z)),q&&q.split(" ").forEach(F=>r.store.off(F,z))}},[r,i]),v=b.useRef(),S=b.useCallback(()=>{if(!r)return uD;const P=!!(r.isInitialized||r.initializedStoreOnce)&&m.every(V=>GM(V,r,i)),U=e.lng||r.language,q=x.current,z=v.current;if(z&&z.ready===P&&z.lng===U&&z.keyPrefix===d&&z.revision===q)return z;const $={t:r.getFixedT(U,i.nsMode==="fallback"?m:m[0],d),ready:P,lng:U,keyPrefix:d,revision:q};return v.current=$,$},[r,m,d,i,e.lng]),[C,k]=b.useState(0),{t:N,ready:A}=lD.useSyncExternalStore(y,S,S);b.useEffect(()=>{if(r&&!A&&!c){const P=()=>k(U=>U+1);e.lng?rk(r,e.lng,m,P):db(r,m,P)}},[r,e.lng,m,A,c,C]);const E=r||{},D=b.useRef(null),_=b.useRef(),I=P=>{const U=Object.getOwnPropertyDescriptors(P);U.__original&&delete U.__original;const q=Object.create(Object.getPrototypeOf(P),U);if(!Object.prototype.hasOwnProperty.call(q,"__original"))try{Object.defineProperty(q,"__original",{value:P,writable:!1,enumerable:!1,configurable:!1})}catch{}return q},O=b.useMemo(()=>{const P=E,U=P==null?void 0:P.language;let q=P;P&&(D.current&&D.current.__original===P?_.current!==U?(q=I(P),D.current=q,_.current=U):q=D.current:(q=I(P),D.current=q,_.current=U));const z=!A&&!c?(...$)=>(ub(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."),N(...$)):N,F=[z,q,A];return F.t=z,F.i18n=q,F.ready=A,F},[N,E,A,E.resolvedLanguage,E.language,E.languages]);if(r&&c&&!A)throw new Promise(P=>{const U=()=>P();e.lng?rk(r,e.lng,m,U):db(r,m,U)});return O};function pb(t){"@babel/helpers - typeof";return pb=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},pb(t)}function nj(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":pb(XMLHttpRequest))==="object"}function fD(t){return!!t&&typeof t.then=="function"}function pD(t){return fD(t)?t:Promise.resolve(t)}var hD=/\{\{(.+?)\}\}/g;function lk(t,e){return t.replace(hD,function(n,s){var a=e[s.trim()];return a??n})}const mD="modulepreload",gD=function(t){return"/"+t},ck={},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=gD(f),f in ck)return;ck[f]=!0;const h=f.endsWith(".css"),m=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const x=document.createElement("link");if(x.rel=h?"stylesheet":mD,h||(x.as="script"),x.crossOrigin="",x.href=f,d&&x.setAttribute("nonce",d),document.head.appendChild(x),h)return new Promise((y,v)=>{x.addEventListener("load",y),x.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${f}`)))})}))}function r(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&r(c.reason);return e().catch(r)})};function uk(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 dk(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?uk(Object(n),!0).forEach(function(s){bD(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):uk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function bD(t,e,n){return(e=xD(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function xD(t){var e=yD(t,"string");return po(e)=="symbol"?e:e+""}function yD(t,e){if(po(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var s=n.call(t,e);if(po(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function po(t){"@babel/helpers - typeof";return po=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},po(t)}var Ci=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Ci=global.fetch:typeof window<"u"&&window.fetch&&(Ci=window.fetch);var gu;nj()&&(typeof global<"u"&&global.XMLHttpRequest?gu=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(gu=window.XMLHttpRequest));var Ff;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Ff=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Ff=window.ActiveXObject));typeof Ci!="function"&&(Ci=void 0);if(!Ci&&!gu&&!Ff)try{vt(()=>import("./browser-ponyfill-DZOWXZ4K.js").then(t=>t.b),__vite__mapDeps([0,1])).then(function(t){Ci=t.default}).catch(function(){})}catch{}var hb=function(e,n){if(n&&po(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},fk=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):Ci(e,n).then(r).catch(s)},pk=!1,vD=function(e,n,s,a){e.queryStringParams&&(n=hb(n,e.queryStringParams));var r=dk({},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=dk({method:s?"POST":"GET",body:s?e.stringify(s):void 0,headers:r},pk?{}:i),d=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{fk(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]}),fk(n,c,a,d),pk=!0}catch(h){a(h)}}},wD=function(e,n,s,a){s&&po(s)==="object"&&(s=hb("",s).slice(1)),e.queryStringParams&&(n=hb(n,e.queryStringParams));try{var r=gu?new gu:new Ff("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)}},kD=function(e,n,s,a){if(typeof s=="function"&&(a=s,s=void 0),a=a||function(){},Ci&&n.indexOf("file:")!==0)return vD(e,n,s,a);if(nj()||typeof ActiveXObject=="function")return wD(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 hk(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 Xm(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?hk(Object(n),!0).forEach(function(s){sj(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):hk(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function SD(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function CD(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,aj(s.key),s)}}function AD(t,e,n){return e&&CD(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function sj(t,e,n){return(e=aj(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function aj(t){var e=jD(t,"string");return vl(e)=="symbol"?e:e+""}function jD(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 ND=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 sj({},s,a||"")},parseLoadPayload:function(n,s){},request:kD,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},rj=(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]:{};SD(this,t),this.services=e,this.options=n,this.allOptions=s,this.type="backend",this.init(e,n,s)}return AD(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=Xm(Xm(Xm({},ND()),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=pD(d),d.then(function(f){if(!f)return i(null,{});var h=lk(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 x=h.message.toLowerCase(),y=["failed","fetch","network","load"].find(function(C){return x.indexOf(C)>-1});if(y)return s("failed loading "+n+": "+h.message,!0)}if(h)return s(h,!1);var v,S;try{typeof m.data=="string"?v=i.options.parse(m.data,a,r):v=m.data}catch{S="failed parsing "+n+" to json"}if(S)return s(S,!1);s(null,v)})}},{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(x){var y=c.options.addPath;typeof c.options.addPath=="function"&&(y=c.options.addPath(x,s));var v=lk(y,{lng:x,ns:s});c.options.request(c.options,v,d,function(S,C){f+=1,h.push(S),m.push(C),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 x=r.toResolveHierarchy(m);x.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(x,y){x&&i.warn("loading namespace ".concat(m," for language ").concat(h," failed"),x),!x&&y&&i.log("loaded namespace ".concat(m," for language ").concat(h),y),a.loaded("".concat(h,"|").concat(m),x,y)})})})}}}])})();rj.type="backend";const{slice:TD,forEach:ED}=[];function _D(t){return ED.call(TD.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function MD(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 mk=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,DD=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(!mk.test(s.domain))throw new TypeError("option domain is invalid");r+=`; Domain=${s.domain}`}if(s.path){if(!mk.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},gk={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=DD(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 RD={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return gk.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:a,cookieOptions:r}=e;n&&typeof document<"u"&&gk.create(n,t,s,a,r)}},OD={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}},LD={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 tl=null;const bk=()=>{if(tl!==null)return tl;try{if(tl=typeof window<"u"&&window.localStorage!==null,!tl)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{tl=!1}return tl};var PD={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&bk())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&bk()&&window.localStorage.setItem(n,t)}};let nl=null;const xk=()=>{if(nl!==null)return nl;try{if(nl=typeof window<"u"&&window.sessionStorage!==null,!nl)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{nl=!1}return nl};var ID={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&xk())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&xk()&&window.sessionStorage.setItem(n,t)}},BD={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}},FD={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}},zD={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}},$D={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 ij=!1;try{document.cookie,ij=!0}catch{}const oj=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];ij||oj.splice(1,1);const HD=()=>({order:oj,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class lj{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=_D(n,this.options||{},HD()),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(RD),this.addDetector(OD),this.addDetector(PD),this.addDetector(ID),this.addDetector(BD),this.addDetector(FD),this.addDetector(zD),this.addDetector($D),this.addDetector(LD)}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&&!MD(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)}))}}lj.type="languageDetector";const zf={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},mb={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},UD={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},Yq=["#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"],Kd={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function Jb(t){const n=Math.floor((Date.now()-t)/1e3)/60;return n<1?Kd.recent:n<5?Kd.short:n<30?Kd.medium:Kd.long}function Zb(t){return zf[t]??zf.default}let Sf=null;function cj(){if(!Sf)try{Sf=globalThis.__i18n}catch{}return Sf}function WD(t){Sf=t}function qD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function VD(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":t.toString()}function GD(t){var a;const e=cj(),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 xp(t){var f;const e=cj(),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 au(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:""}En.use(rj).use(lj).use(sD).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(()=>{WD(En)});const ft={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",AOP_TRACKING_BOARD_VISIBLE:"tide-aop-tracking-board-visible",MOBILE_OVERVIEW_HEIGHT:"tide-mobile-overview-height",SPLIT_PANE_AGENT_IDS:"tide-split-pane-agent-ids",SPLIT_PANE_ORIENTATION:"tide-split-pane-orientation",GIT_PANEL_OPEN:"guake-git-panel-open",GIT_PANEL_MODE:"guake-git-panel-mode",GIT_PANEL_VIEW_MODE:"guake-git-view-mode",GIT_PANEL_FOLDER_IDX:"guake-git-folder-idx",BUILDINGS_PANEL_OPEN:"guake-buildings-panel-open",WORKFLOW_PANEL_OPEN:"guake-workflow-panel-open",SIDE_PANEL_WIDTH:"guake-side-panel-width",UNSEEN_AGENTS:"tide-unseen-agents",PENDING_MESSAGES:"tide-pending-messages"},gb="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 wa(t,e=""){try{return localStorage.getItem(t)??e}catch{return e}}function _r(t,e=!1){try{const n=localStorage.getItem(t);return n===null?e:n==="true"}catch{return e}}function ex(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 va(t,e){try{localStorage.setItem(t,JSON.stringify(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function er(t,e){try{localStorage.setItem(t,e)}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function Qa(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function tx(t,e){try{localStorage.setItem(t,String(e))}catch(n){console.error(`Failed to save to localStorage: ${t}`,n)}}function yk(t){try{localStorage.removeItem(t)}catch(e){console.error(`Failed to remove from localStorage: ${t}`,e)}}function Ca(){const t=nx();return t?t.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function Ti(){return wa(ft.AUTH_TOKEN,"")}function nx(){return wa(ft.BACKEND_URL,"")}function YD(t){const e=t.trim();er(ft.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(gb,{detail:e}))}function KD(t){if(typeof window>"u")return()=>{};const e=s=>{t(s.detail)},n=s=>{s.key===ft.BACKEND_URL&&t(s.newValue??"")};return window.addEventListener(gb,e),window.addEventListener("storage",n),()=>{window.removeEventListener(gb,e),window.removeEventListener("storage",n)}}function _t(t){return`${Ca()}${t}`}async function Lt(t,e){const n=Ti(),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 $f(t){const e=Ti();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 ss(t=!1,e){const[n,s]=b.useState(t),[a,r]=b.useState(e),i=b.useCallback(f=>{f!==void 0&&r(f),s(!0)},[]),c=b.useCallback(()=>{s(!1)},[]),d=b.useCallback(()=>{s(f=>!f)},[]);return{isOpen:n,data:a,open:i,close:c,toggle:d,setData:r}}function QD(){const[t,e]=b.useState(null),n=b.useCallback(a=>{e(a)},[]),s=b.useCallback(()=>{e(null)},[]);return{isOpen:t!==null,id:t,open:n,close:s}}function XD(){const[t,e]=b.useState(!1),[n,s]=b.useState({x:0,y:0}),[a,r]=b.useState({x:0,z:0}),[i,c]=b.useState({type:"ground"}),d=b.useCallback((h,m,x)=>{s(h),r(m),c(x),e(!0)},[]),f=b.useCallback(()=>{e(!1)},[]);return{isOpen:t,screenPosition:n,worldPosition:a,target:i,open:d,close:f}}const sa=[],JD=new Set;function Hf(){JD.forEach(t=>t())}function ZD(t,e){const n=sa.findIndex(s=>s.id===t);return n!==-1&&sa.splice(n,1),sa.push({id:t,close:e}),Hf(),()=>{const s=sa.findIndex(a=>a.id===t);s!==-1&&(sa.splice(s,1),Hf())}}function Cf(){return sa.length===0?!1:(sa.pop().close(),Hf(),!0)}function eR(t){const e=sa.findIndex(n=>n.id===t);return e===-1?!1:e<sa.length-1}function tR(...t){const e=new Set(t);for(;sa.length>0;){const n=sa[sa.length-1];if(e.has(n.id))break;sa.pop().close()}Hf()}function Qt(t,e,n){const s=b.useRef(n);s.current=n,b.useEffect(()=>e?ZD(t,()=>s.current()):void 0,[t,e])}const bu=5,Jm={0:0,1:4,2:8,3:14,4:25,5:50};let ru=null,vk=!1;async function nR(){if(vk)return ru;vk=!0;try{const t=await vt(()=>import("./index-BCuYxI5F.js"),__vite__mapDeps([2,3,1,4]));ru={Haptics:t.Haptics,ImpactStyle:t.ImpactStyle}}catch{}return ru}nR();function Uf(t){const e=Math.round(t),n=e<=0?0:e>=bu?bu:e;if(n!==0){if(ru){const{Haptics:s,ImpactStyle:a}=ru;if(n<=2&&typeof s.selectionChanged=="function"){s.selectionChanged().catch(()=>{navigator.vibrate&&navigator.vibrate(Jm[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(Jm[n])});return}}navigator.vibrate&&navigator.vibrate(Jm[n])}}function wk(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=b.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=b.useCallback(S=>{if(S.touches.length!==1)return;const C=S.touches[0];h.current={startX:C.clientX,startY:C.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),x=b.useCallback(S=>{if(!h.current.isTracking||S.touches.length!==1)return;const C=S.touches[0],k=C.clientX-h.current.startX;if(Math.abs(C.clientY-h.current.startY)>s){h.current.isTracking=!1,h.current.hasMovedEnough&&(d==null||d());return}const E=window.innerWidth*.4,D=Math.max(-1,Math.min(1,k/E));Math.abs(k)>=12&&(h.current.hasMovedEnough=!0,c==null||c(D))},[s,c,d]),y=b.useCallback(S=>{const C=h.current.isTracking,k=h.current.hasMovedEnough;if(!C)return;const N=S.changedTouches[0],A=N.clientX-h.current.startX,E=Math.abs(N.clientY-h.current.startY),D=Date.now()-h.current.startTime;h.current.isTracking=!1,h.current.hasMovedEnough=!1,Math.abs(A)>=n&&E<=s&&D<500?(Uf(f),A>0?i==null||i():r==null||r()):k&&(d==null||d())},[n,s,f,r,i,d]),v=b.useCallback(()=>{const S=h.current.hasMovedEnough;h.current.isTracking=!1,h.current.hasMovedEnough=!1,S&&(d==null||d())},[d]);b.useEffect(()=>{const S=t.current;if(!(!S||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return S.addEventListener("touchstart",m,{passive:!0}),S.addEventListener("touchmove",x,{passive:!0}),S.addEventListener("touchend",y,{passive:!0}),S.addEventListener("touchcancel",v,{passive:!0}),()=>{S.removeEventListener("touchstart",m),S.removeEventListener("touchmove",x),S.removeEventListener("touchend",y),S.removeEventListener("touchcancel",v)}},[t,a,m,x,y,v])}const kk=8,sR=.93,Sk=.4;function aR(t){const{gestureRef:e,agentListRef:n,enabled:s,onSelect:a}=t,[r,i]=b.useState(!1),[c,d]=b.useState(null),f=b.useRef(!1),h=b.useRef(null),m=b.useRef(a);m.current=a;const x=b.useCallback(()=>{if(f.current)return;f.current=!0,i(!0);const C=n.current;if(C){const k=Math.round(C.clientHeight/2);C.style.paddingTop=`${k}px`,C.style.paddingBottom=`${k}px`}},[n]),y=b.useCallback(()=>{f.current=!1,h.current=null,i(!1),d(null);const C=n.current;C&&(C.style.paddingTop="",C.style.paddingBottom="")},[n]),v=b.useCallback(C=>{const k=n.current;if(!k)return;k.scrollTop+=C;const N=k.getBoundingClientRect(),A=N.top+N.height/2,E=N.left+N.width/2,D=document.elementFromPoint(E,A);let _=null;if(D){const I=D.closest("[data-agent-id]");I&&k.contains(I)&&(_=I.dataset.agentId)}if(_!==h.current&&(h.current=_,d(_),_)){const I=H.getState().settings.vibrationIntensity??1;Uf(I)}},[n]),S=b.useCallback(()=>{const C=h.current;if(C){const k=H.getState().settings.vibrationIntensity??1,N=k<=0?0:Math.min(k+1,bu);Uf(N),m.current(C)}y()},[y]);return b.useEffect(()=>{const C=e.current;if(!C||!s)return;const k=C.style.touchAction;C.style.touchAction="none";let N=!1,A=!1,E=0,D=0,_=0,I=0,O=0,T=0,M=0,R=0;const P=()=>{M&&(cancelAnimationFrame(M),M=0)},U=()=>{if(Math.abs(T)<Sk){T=0;return}C.scrollTop+=T,T*=sR,M=requestAnimationFrame(U)},q=V=>{if(P(),V.touches.length>=2){V.preventDefault(),N=!1,A=!1,R=(V.touches[0].clientY+V.touches[1].clientY)/2,x(),v(0);return}N=!0,A=!1,E=V.touches[0].clientX,D=V.touches[0].clientY,_=C.scrollTop,I=D,O=performance.now(),T=0},z=V=>{if(V.touches.length>=2){if(V.preventDefault(),(A||N)&&(A=!1,N=!1),!f.current){R=(V.touches[0].clientY+V.touches[1].clientY)/2,x(),v(0);return}const Q=(V.touches[0].clientY+V.touches[1].clientY)/2,K=R-Q;R=Q,v(K);return}if(f.current&&V.touches.length===1){V.preventDefault();const Q=V.touches[0].clientY,K=R-Q;R=Q,v(K);return}if(!N&&!A)return;const G=V.touches[0].clientX,B=V.touches[0].clientY;if(N&&!A){const Q=Math.abs(G-E),K=Math.abs(B-D);if(Q<kk&&K<kk)return;if(K>=Q)A=!0,N=!1,V.preventDefault();else{N=!1;return}}if(A){V.preventDefault();const Q=performance.now(),K=Q-O;C.scrollTop=_+(D-B),K>0&&(T=(I-B)/K*16),I=B,O=Q}},F=V=>{if(f.current&&V.touches.length===0){S();return}f.current||(A||N)&&V.touches.length===0&&(A&&Math.abs(T)>Sk&&(M=requestAnimationFrame(U)),A=!1,N=!1)},$=()=>{A=!1,N=!1,P(),f.current&&y()};return C.addEventListener("touchstart",q,{passive:!1}),C.addEventListener("touchmove",z,{passive:!1}),C.addEventListener("touchend",F,{passive:!0}),C.addEventListener("touchcancel",$,{passive:!0}),()=>{C.removeEventListener("touchstart",q),C.removeEventListener("touchmove",z),C.removeEventListener("touchend",F),C.removeEventListener("touchcancel",$),C.style.touchAction=k,P();const V=n.current;V&&(V.style.paddingTop="",V.style.paddingBottom="")}},[e,n,s,x,y,v,S]),{isActive:r,hoveredAgentId:c}}const rR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function iR(){return"documentPictureInPicture"in window}function oR(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 lR(){const[t,e]=b.useState(!1),[n,s]=b.useState(null),[a,r]=b.useState(null),i=b.useRef(null),c=iR(),d=b.useCallback(()=>{if(i.current){const m=i.current.__cleanupFns;m&&m.forEach(x=>x()),i.current.close(),i.current=null}s(null),r(null),e(!1)},[]),f=b.useCallback(async m=>{if(!c)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;i.current&&d();const x={...rR,...m};try{const v=await window.documentPictureInPicture.requestWindow({width:x.width,height:x.height,disallowReturnToOpener:!0});i.current=v,x.copyStyleSheets&&oR(document,v.document);const S=v.document.createElement("div");S.id="pip-root",S.style.width="100%",S.style.height="100%",v.document.body.appendChild(S),v.document.body.style.margin="0",v.document.body.style.padding="0",v.document.body.style.overflow="hidden",v.addEventListener("pagehide",()=>{i.current=null,s(null),r(null),e(!1)});const C=[];if(x.keepOnTop&&x.keepOnTop!=="none"){const k=x.keepOnTop==="raise",N=()=>{i.current&&!i.current.closed&&setTimeout(()=>{i.current&&!i.current.closed&&(i.current.focus(),k&&setTimeout(()=>window.focus(),10))},50)},A=()=>{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",N),document.addEventListener("visibilitychange",A),C.push(()=>window.removeEventListener("focus",N),()=>document.removeEventListener("visibilitychange",A))}return v.__cleanupFns=C,s(v),r(S),e(!0),!0}catch(y){return console.error("Failed to open Picture-in-Picture window:",y),!1}},[c,d]),h=b.useCallback(async m=>{t?d():await f(m)},[t,f,d]);return b.useEffect(()=>()=>{i.current&&i.current.close()},[]),b.useMemo(()=>({isOpen:t,pipWindow:n,pipContainer:a,isSupported:c,open:f,close:d,toggle:h}),[t,n,a,c,f,d,h])}function _c(){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 cR{constructor(){et(this,"messages",new Map);et(this,"logs",[]);et(this,"maxMessagesPerAgent",200);et(this,"maxLogs",500);et(this,"enabled",!0);et(this,"listeners",new Set);et(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,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:_c(),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:_c(),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:_c(),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:_c(),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:_c(),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 ms=new cR,xu={debug:(t,e,n)=>ms.debug(t,e,n),info:(t,e,n)=>ms.info(t,e,n),warn:(t,e,n)=>ms.warn(t,e,n),error:(t,e,n)=>ms.error(t,e,n)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var wl;(function(t){t.Unimplemented="UNIMPLEMENTED",t.Unavailable="UNAVAILABLE"})(wl||(wl={}));class Zm extends Error{constructor(e,n,s){super(e),this.message=e,this.code=n,this.data=s}}const uR=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"},dR=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},s=n.Plugins=n.Plugins||{},a=()=>e!==null?e.name:uR(t),r=()=>a()!=="web",i=m=>{const x=f.get(m);return!!(x!=null&&x.platforms.has(a())||c(m))},c=m=>{var x;return(x=n.PluginHeaders)===null||x===void 0?void 0:x.find(y=>y.name===m)},d=m=>t.console.error(m),f=new Map,h=(m,x={})=>{const y=f.get(m);if(y)return console.warn(`Capacitor plugin "${m}" already registered. Cannot register plugins twice.`),y.proxy;const v=a(),S=c(m);let C;const k=async()=>(!C&&v in x?C=typeof x[v]=="function"?C=await x[v]():C=x[v]:e!==null&&!C&&"web"in x&&(C=typeof x.web=="function"?C=await x.web():C=x.web),C),N=(O,T)=>{var M,R;if(S){const P=S==null?void 0:S.methods.find(U=>T===U.name);if(P)return P.rtype==="promise"?U=>n.nativePromise(m,T.toString(),U):(U,q)=>n.nativeCallback(m,T.toString(),U,q);if(O)return(M=O[T])===null||M===void 0?void 0:M.bind(O)}else{if(O)return(R=O[T])===null||R===void 0?void 0:R.bind(O);throw new Zm(`"${m}" plugin is not implemented on ${v}`,wl.Unimplemented)}},A=O=>{let T;const M=(...R)=>{const P=k().then(U=>{const q=N(U,O);if(q){const z=q(...R);return T=z==null?void 0:z.remove,z}else throw new Zm(`"${m}.${O}()" is not implemented on ${v}`,wl.Unimplemented)});return O==="addListener"&&(P.remove=async()=>T()),P};return M.toString=()=>`${O.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:O,writable:!1,configurable:!1}),M},E=A("addListener"),D=A("removeListener"),_=(O,T)=>{const M=E({eventName:O},T),R=async()=>{const U=await M;D({eventName:O,callbackId:U},T)},P=new Promise(U=>M.then(()=>U({remove:R})));return P.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},P},I=new Proxy({},{get(O,T){switch(T){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return S?_:E;case"removeListener":return D;default:return A(T)}}});return s[m]=I,f.set(m,{name:m,proxy:I,platforms:new Set([...Object.keys(x),...S?[v]:[]])}),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=Zm,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},fR=t=>t.Capacitor=dR(t),Wf=fR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Tu=Wf.registerPlugin;class sx{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 Wf.Exception(e,wl.Unimplemented)}unavailable(e="not available"){return new Wf.Exception(e,wl.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 Ck=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Ak=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class pR extends sx{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=Ak(a).trim(),r=Ak(r).trim(),n[a]=r}),n}async setCookie(e){try{const n=Ck(e.key),s=Ck(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)}}}Tu("CapacitorCookies",{web:()=>new pR});const hR=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)}),mR=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(a=>a.toLocaleLowerCase()).reduce((a,r,i)=>(a[r]=t[e[i]],a),{})},gR=(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,bR=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),a=mR(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 xR extends sx{async request(e){const n=bR(e,e.webFetchExtra),s=gR(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 hR(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,x)=>{h[x]=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 Kq=Tu("CapacitorHttp",{web:()=>new xR});var jk;(function(t){t.Dark="DARK",t.Light="LIGHT",t.Default="DEFAULT"})(jk||(jk={}));var Nk;(function(t){t.StatusBar="StatusBar",t.NavigationBar="NavigationBar"})(Nk||(Nk={}));class yR extends sx{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")}}Tu("SystemBars",{web:()=>new yR});var Tk;(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"})(Tk||(Tk={}));const ax=Tu("LocalNotifications",{web:()=>vt(()=>import("./web-Blb26Kj7.js"),__vite__mapDeps([5,3,1,4])).then(t=>new t.LocalNotificationsWeb)}),vR=Tu("ServerConfig");let wR=100;const kR="agent_alerts",bb="tide-notification-tap";function SR(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function uj(t){if(SR()){H.openTerminalOnMobile(t);return}if(document.querySelector(".commander-overlay")){H.requestCommanderExpand(t);return}H.selectAgent(t),H.setTerminalOpen(!0)}function Eu(){try{return Wf.isNativePlatform()}catch{return!1}}async function CR(){if(Eu())try{const t=await ax.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 AR(t){const{title:e,body:n,icon:s,data:a}=t;if(Eu())try{const r=wR++;console.log("[Notifications] Scheduling native notification id="+r,e),await ax.schedule({notifications:[{id:r,title:e,body:n,extra:a,channelId:kR,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(bb,{detail:a}))}}}let eg=!1;async function jR(t){const e=[];if(eg)return()=>{};if(eg=!0,t){const n=s=>{const a=s;a.detail&&t(a.detail)};window.addEventListener(bb,n),e.push(()=>window.removeEventListener(bb,n))}if(Eu())try{const n=await ax.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()),eg=!1}}function NR(t,e){Eu()&&vR.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,Ek=t=>{window.__tideWsState.ws=t},TR=()=>window.__tideWsState.isConnecting,Mc=t=>{window.__tideWsState.isConnecting=t},xb=()=>window.__tideWsState.reconnectAttempts,yb=t=>{window.__tideWsState.reconnectAttempts=t},dj=()=>window.__tideWsState.reconnectTimeout,fj=t=>{window.__tideWsState.reconnectTimeout=t},_k=10,rx="tide_ws_has_connected";function Mk(){return sessionStorage.getItem(rx)==="true"}function ER(t){sessionStorage.setItem(rx,"true")}function _R(){sessionStorage.removeItem(rx)}let pj=null;const MR=t=>{pj=t},Dk=()=>pj,Pe={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function hj(t){t.onToast&&(Pe.onToast=t.onToast),t.onAgentCreated&&(Pe.onAgentCreated=t.onAgentCreated),t.onAgentUpdated&&(Pe.onAgentUpdated=t.onAgentUpdated),t.onAgentDeleted&&(Pe.onAgentDeleted=t.onAgentDeleted),t.onAgentsSync&&(Pe.onAgentsSync=t.onAgentsSync),t.onAreasSync&&(Pe.onAreasSync=t.onAreasSync),t.onSpawnError&&(Pe.onSpawnError=t.onSpawnError),t.onSpawnSuccess&&(Pe.onSpawnSuccess=t.onSpawnSuccess),t.onToolUse&&(Pe.onToolUse=t.onToolUse),t.onDirectoryNotFound&&(Pe.onDirectoryNotFound=t.onDirectoryNotFound),t.onDelegation&&(Pe.onDelegation=t.onDelegation),t.onCustomClassesSync&&(Pe.onCustomClassesSync=t.onCustomClassesSync),t.onReconnect&&(Pe.onReconnect=t.onReconnect),t.onAgentNotification&&(Pe.onAgentNotification=t.onAgentNotification),t.onBuildingUpdated&&(Pe.onBuildingUpdated=t.onBuildingUpdated),t.onSubagentStarted&&(Pe.onSubagentStarted=t.onSubagentStarted),t.onSubagentCompleted&&(Pe.onSubagentCompleted=t.onSubagentCompleted)}function DR(){Pe.onToast=null,Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onSpawnError=null,Pe.onSpawnSuccess=null,Pe.onToolUse=null,Pe.onDirectoryNotFound=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onReconnect=null,Pe.onAgentNotification=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}function RR(){Pe.onAgentCreated=null,Pe.onAgentUpdated=null,Pe.onAgentDeleted=null,Pe.onAgentsSync=null,Pe.onAreasSync=null,Pe.onToolUse=null,Pe.onDelegation=null,Pe.onCustomClassesSync=null,Pe.onBuildingUpdated=null,Pe.onSubagentStarted=null,Pe.onSubagentCompleted=null}const Qd=new Map,OR=new Map,vb={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?Qd.has(t)?[[t,Qd.get(t)]]:[]:Array.from(Qd.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(){Qd.clear(),OR.clear()},report(){}};class LR{constructor(){et(this,"frames",[]);et(this,"lastFrameTime",0);et(this,"frameCount",0);et(this,"fps",0);et(this,"minFps",1/0);et(this,"maxFps",0);et(this,"fpsHistory",[]);et(this,"maxHistorySize",60)}tick(e=200){const 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 Xd=new LR;class PR{constructor(){et(this,"snapshots",[]);et(this,"maxSnapshots",120);et(this,"intervalId",null);et(this,"leakThresholdMB",50);et(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const 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 Dc=new PR;function Kc(t,e,n,s,a,r){}function mj(t,e){b.useRef(0),b.useEffect(()=>{},[t,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}const wb=ft.PENDING_MESSAGES,IR=300*1e3;function gj(){try{const t=localStorage.getItem(wb);if(!t)return[];const e=JSON.parse(t),n=Date.now();return e.filter(s=>n-s.queuedAt<IR)}catch{return[]}}function bj(t){try{t.length===0?localStorage.removeItem(wb):localStorage.setItem(wb,JSON.stringify(t))}catch{}}function Jd(t){const e=gj();e.push({message:t,queuedAt:Date.now()}),bj(e)}function BR(){var s;const t=gj();if(t.length===0)return 0;let e=0;const n=[];for(const a of t)FR(a.message)?e++:n.push(a);if(bj(n),e>0){const a=e===1?"queued message":"queued messages";(s=Pe.onToast)==null||s.call(Pe,"success","Messages Sent",`${e} ${a} delivered after reconnecting.`)}return e}function ix(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 FR(t){const e=yp();if(!e||e.readyState!==WebSocket.OPEN)return!1;try{const n=JSON.stringify(t),s=ix(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",s,"payload:",t.payload),s&&ms.captureSent(s,n),e.send(n),!0}catch{return!1}}function ox(t){var n,s,a,r,i,c,d,f,h,m;const e=yp();if(!e)return(n=Dk())==null||n(),t.type==="send_command"?(Jd(t),(s=Pe.onToast)==null||s.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(a=Pe.onToast)==null||a.call(Pe,"error","Not Connected","Connecting to server... Please try again in a moment."),!1;if(e.readyState!==WebSocket.OPEN)return e.readyState===WebSocket.CONNECTING?t.type==="send_command"?(Jd(t),(r=Pe.onToast)==null||r.call(Pe,"warning","Message Queued","Still connecting. Your message will be sent automatically.")):(i=Pe.onToast)==null||i.call(Pe,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((c=Dk())==null||c(),t.type==="send_command"?(Jd(t),(d=Pe.onToast)==null||d.call(Pe,"warning","Message Queued","Connection lost. Your message will be sent when reconnected.")):(f=Pe.onToast)==null||f.call(Pe,"warning","Reconnecting...","Connection lost. Reconnecting to server...")),!1;try{const x=JSON.stringify(t),y=ix(t);return console.log("[AgentDebugger] SENT - type:",t.type,"agentId:",y,"payload:",t.payload),y&&ms.captureSent(y,x),e.send(x),!0}catch(x){return t.type==="send_command"?(Jd(t),(h=Pe.onToast)==null||h.call(Pe,"warning","Message Queued","Send failed. Your message will be retried when reconnected.")):(m=Pe.onToast)==null||m.call(Pe,"error","Send Failed",`Failed to send message: ${x}`),!1}}const Qc=new Set,zR=5e3;function Rk(t){if(!t.isDetached||!t.sessionId){Qc.delete(t.id);return}Qc.has(t.id)||(Qc.add(t.id),ox({type:"reattach_agent",payload:{agentId:t.id}}),setTimeout(()=>{Qc.delete(t.id)},zR))}function $R(t){var e,n,s,a,r,i,c,d,f,h,m,x,y,v,S,C,k,N,A,E,D,_,I,O;switch(vb.start(`ws:${t.type}`),t.type){case"agents_update":{const T=t.payload,M=T.filter(R=>R.class==="boss"||R.isBoss);M.length>0&&console.log("[WS agents_update] Boss agents received:",M.map(R=>({id:R.id,name:R.name,subordinateIds:R.subordinateIds}))),H.setAgents(T),(e=Pe.onAgentsSync)==null||e.call(Pe,T),H.loadToolHistory();for(const R of T)Rk(R);break}case"agent_created":{const T=t.payload;console.log("[WebSocket] Agent created:",T),H.addAgent(T);const M=(n=window.__spawnModalAreaContext)==null?void 0:n.areaId;M&&(H.assignAgentToArea(T.id,M),window.__spawnModalAreaContext=null),H.selectAgent(T.id),(s=Pe.onAgentCreated)==null||s.call(Pe,T),(a=Pe.onSpawnSuccess)==null||a.call(Pe),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(r=Pe.onToast)==null||r.call(Pe,"success","Agent Deployed",`${T.name} is ready for commands`);break}case"agent_updated":{const T=t.payload,R=H.getState().agents.get(T.id),P=(R==null?void 0:R.status)!==T.status;console.log(`[Tide] Agent updated: ${T.name} (${T.id}) status=${T.status} (was ${R==null?void 0:R.status})${P?" ⚡ STATUS CHANGED":""}`),P&&console.log(`[Tide] 🔔 Status change for ${T.name}: ${R==null?void 0:R.status} → ${T.status}`),P&&(R==null?void 0:R.status)==="working"&&T.status==="idle"&&H.triggerHistoryRefresh(T.id);const U=R?R.position.x!==T.position.x||R.position.z!==T.position.z:!1;H.updateAgent(T),Rk(T),(i=Pe.onAgentUpdated)==null||i.call(Pe,T,U);break}case"agent_deleted":{const{id:T}=t.payload;Qc.delete(T),H.removeAgent(T),(c=Pe.onAgentDeleted)==null||c.call(Pe,T);break}case"activity":{const T=t.payload;H.addActivity(T);break}case"event":{const T=t.payload;if(xu.debug(`Event: ${T.type}`,{agentId:T.agentId,toolName:T.toolName},"ws:event"),T.type==="tool_start"&&T.toolName&&((d=Pe.onToolUse)==null||d.call(Pe,T.agentId,T.toolName,T.toolInput),H.addToolExecution(T.agentId,T.toolName,T.toolInput),T.toolInput)){const M=T.toolInput.file_path||T.toolInput.path;M&&(T.toolName==="Write"?H.addFileChange(T.agentId,"created",M):T.toolName==="Edit"?H.addFileChange(T.agentId,"modified",M):T.toolName==="Read"&&H.addFileChange(T.agentId,"read",M))}break}case"output":{const T=t.payload;xu.debug(`Output: "${T.text.slice(0,80)}..."`,{agentId:T.agentId,isStreaming:T.isStreaming,length:T.text.length,hasSkillUpdate:!!T.skillUpdate,uuid:T.uuid,toolName:T.toolName},"ws:output"),H.addOutput(T.agentId,{text:T.text,isStreaming:T.isStreaming,timestamp:T.timestamp,isDelegation:T.isDelegation,skillUpdate:T.skillUpdate,subagentName:T.subagentName,uuid:T.uuid,toolName:T.toolName,toolInput:T.toolInput,toolOutput:T.toolOutput});break}case"context_stats":{const{agentId:T,stats:M}=t.payload;console.log(`[Tide] Received context stats for agent ${T}: ${M.usedPercent}% used`),H.updateAgentContextStats(T,M);break}case"context_update":{const{agentId:T,contextUsed:M,contextLimit:R}=t.payload;H.updateAgentContext(T,M,R);break}case"compacting_status":{const{agentId:T,active:M}=t.payload;H.setAgentCompacting(T,M);break}case"error":{const T=t.payload;console.error("[WebSocket] Error from server:",T.message),(f=Pe.onToast)==null||f.call(Pe,"error","Error",T.message),(h=Pe.onSpawnError)==null||h.call(Pe),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:T}=t.payload;console.log("[WebSocket] Directory not found:",T),(m=Pe.onDirectoryNotFound)==null||m.call(Pe,T),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(T));break}case"command_started":{const{agentId:T,command:M}=t.payload,R=M.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;H.addUserPromptToOutput(T,M);break}case"session_updated":{const{agentId:T}=t.payload;H.loadToolHistory(),H.triggerHistoryRefresh(T);const M=H.getState().agents.get(T);M&&H.updateAgent({...M});break}case"supervisor_report":{const T=t.payload;H.setSupervisorReport(T);break}case"narrative_update":{const{agentId:T,narrative:M}=t.payload;H.addNarrative(T,M);break}case"supervisor_status":{const T=t.payload;H.setSupervisorStatus(T);break}case"agent_supervisor_history":{const T=t.payload;H.setAgentSupervisorHistory(T);break}case"agent_analysis":{const{agentId:T,analysis:M}=t.payload;H.addAgentAnalysis(T,M);break}case"areas_update":{const T=t.payload;H.setAreasFromServer(T),(x=Pe.onAreasSync)==null||x.call(Pe);break}case"buildings_update":{const T=t.payload;H.setBuildingsFromServer(T);break}case"building_created":{const T=t.payload;H.addBuilding(T);break}case"building_updated":{const T=t.payload;H.updateBuildingFromServer(T),(y=Pe.onBuildingUpdated)==null||y.call(Pe,T);break}case"building_deleted":{const{id:T}=t.payload;H.removeBuildingFromServer(T);break}case"building_logs":{const{buildingId:T,logs:M}=t.payload;H.addBuildingLogs(T,M);break}case"pm2_logs_chunk":{const{buildingId:T,chunk:M}=t.payload;H.appendStreamingLogChunk(T,M);break}case"pm2_logs_streaming":{const{buildingId:T,streaming:M}=t.payload;H.setStreamingStatus(T,M);break}case"docker_logs_chunk":{const{buildingId:T,chunk:M}=t.payload;H.appendStreamingLogChunk(T,M);break}case"docker_logs_streaming":{const{buildingId:T,streaming:M}=t.payload;H.setStreamingStatus(T,M);break}case"docker_containers_list":{const{containers:T,composeProjects:M}=t.payload;console.log(`[WebSocket] Received ${T.length} containers, ${M.length} compose projects`),H.setDockerContainersList(T,M);break}case"boss_building_logs_chunk":{const{bossBuildingId:T,subordinateBuildingId:M,subordinateBuildingName:R,chunk:P,isError:U}=t.payload;H.appendBossStreamingLogChunk(T,M,R,P,U);break}case"boss_building_subordinates_updated":{const{bossBuildingId:T,subordinateBuildingIds:M}=t.payload;H.updateBuilding(T,{subordinateBuildingIds:M});break}case"permission_request":{const T=t.payload;H.addPermissionRequest(T);break}case"permission_resolved":{const{requestId:T,approved:M}=t.payload;H.resolvePermissionRequest(T,M);break}case"delegation_decision":{const T=t.payload;H.handleDelegationDecision(T),T.status==="sent"&&((v=Pe.onToast)==null||v.call(Pe,"info","Task Delegated",`Delegated to ${T.selectedAgentName}: ${T.reasoning.slice(0,80)}...`),T.bossId&&T.selectedAgentId&&((S=Pe.onDelegation)==null||S.call(Pe,T.bossId,T.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:T,subordinateIds:M}=t.payload;H.updateBossSubordinates(T,M);break}case"delegation_history":{const{bossId:T,decisions:M}=t.payload;H.setDelegationHistory(T,M);break}case"session_history":{const{agentId:T,entries:M}=t.payload;H.setSessionHistory(T,M);break}case"boss_spawned_agent":{const{agent:T,bossPosition:M}=t.payload;console.log("[WebSocket] Boss spawned agent:",T.name,"- walking to boss at",M),H.addAgent(T),(C=Pe.onAgentCreated)==null||C.call(Pe,T),ox({type:"move_agent",payload:{agentId:T.id,position:M}}),(k=Pe.onToast)==null||k.call(Pe,"success","Agent Deployed",`${T.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:T,subordinateId:M,subordinateName:R,taskDescription:P}=t.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${T}: ${P.slice(0,50)}...`),H.handleAgentTaskStarted(T,M,R,P);break}case"agent_task_output":{const{bossId:T,subordinateId:M,output:R,isStreaming:P,timestamp:U,subagentName:q,toolName:z,toolInput:F,toolOutput:$}=t.payload;H.handleAgentTaskOutput(T,M,{text:R,isStreaming:P||!1,timestamp:U||Date.now(),subagentName:q,toolName:z,toolInput:F,toolOutput:$});break}case"agent_task_completed":{const{bossId:T,subordinateId:M,success:R}=t.payload;console.log(`[WebSocket] Agent task completed for boss ${T}, subordinate ${M}, success: ${R}`),H.handleAgentTaskCompleted(T,M,R);break}case"skills_update":{const T=t.payload;H.setSkillsFromServer(T);break}case"skill_created":{const T=t.payload;H.addSkillFromServer(T),console.log(`[WebSocket] Skill created: ${T.name}`);break}case"skill_updated":{const T=t.payload;H.updateSkillFromServer(T),console.log(`[WebSocket] Skill updated: ${T.name}`);break}case"skill_deleted":{const{id:T}=t.payload;H.removeSkillFromServer(T),console.log(`[WebSocket] Skill deleted: ${T}`);break}case"agent_skills":{const{agentId:T,skills:M}=t.payload;console.log(`[WebSocket] Agent ${T} has ${M.length} skills`);break}case"custom_agent_classes_update":{const T=t.payload;H.setCustomAgentClassesFromServer(T),console.log(`[WebSocket] Received ${T.length} custom agent classes`);const M=new Map;for(const R of T)M.set(R.id,R);(N=Pe.onCustomClassesSync)==null||N.call(Pe,M);break}case"custom_agent_class_created":{const T=t.payload;H.addCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class created: ${T.name}`),(A=Pe.onCustomClassesSync)==null||A.call(Pe,H.getState().customAgentClasses);break}case"custom_agent_class_updated":{const T=t.payload;H.updateCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class updated: ${T.name}`),(E=Pe.onCustomClassesSync)==null||E.call(Pe,H.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:T}=t.payload;H.removeCustomAgentClassFromServer(T),console.log(`[WebSocket] Custom agent class deleted: ${T}`),(D=Pe.onCustomClassesSync)==null||D.call(Pe,H.getState().customAgentClasses);break}case"global_usage":{const T=t.payload;console.log("[WebSocket] Global usage update:",T),H.setGlobalUsage(T);break}case"agent_notification":{const T=t.payload;console.log(`[WebSocket] Agent notification from ${T.agentName}: ${T.title}`),(_=Pe.onAgentNotification)==null||_.call(Pe,T);break}case"focus_agent":{const{agentId:T,openTerminal:M}=t.payload;if(!H.getState().agents.get(T)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${T}`);break}H.selectAgent(T),M&&H.setTerminalOpen(!0);const P=[0,80,220,500,1e3];for(const U of P)window.setTimeout(()=>{window.focus()},U);break}case"exec_task_started":{const{taskId:T,agentId:M,agentName:R,command:P,cwd:U}=t.payload;console.log(`[WebSocket] Exec task started: ${T} for agent ${R}: ${P.slice(0,50)}...`),H.handleExecTaskStarted(T,M,R,P,U);break}case"exec_task_output":{const{taskId:T,agentId:M,output:R,isError:P}=t.payload;H.handleExecTaskOutput(T,M,R,P);break}case"exec_task_completed":{const{taskId:T,agentId:M,exitCode:R,success:P}=t.payload;console.log(`[WebSocket] Exec task completed: ${T} for agent ${M}, success: ${P}`),H.handleExecTaskCompleted(T,M,R,P);break}case"subagent_started":{const T=t.payload;console.log(`[WebSocket] Subagent started: ${T.name} (${T.id}) for agent ${T.parentAgentId}`),H.addSubagent(T),(I=Pe.onSubagentStarted)==null||I.call(Pe,T);break}case"subagent_output":{const{subagentId:T,parentAgentId:M,text:R,timestamp:P}=t.payload,U=R.indexOf(":");if(U>0){const q=R.slice(0,U).trim(),z=R.slice(U+1).trim();H.addSubagentActivity(T,M,{toolName:q,description:z,timestamp:P})}else R.startsWith("Using ")&&H.addSubagentActivity(T,M,{toolName:R.slice(6).trim(),description:"",timestamp:P});break}case"subagent_completed":{const{subagentId:T,parentAgentId:M,success:R,resultPreview:P,subagentName:U,durationMs:q,tokensUsed:z,toolUseCount:F}=t.payload;console.log(`[WebSocket] Subagent completed: ${T} for agent ${M}, success: ${R}`),(q||z||F)&&H.updateSubagentStats(T,M,{durationMs:q||0,tokensUsed:z||0,toolUseCount:F||0}),H.completeSubagent(T,M,R),(O=Pe.onSubagentCompleted)==null||O.call(Pe,T);const $=H.getSubagent(T)||H.getSubagentByToolUseId(T),V=U||($==null?void 0:$.name)||T,G=R?"✅":"❌",B=q?` (${(q/1e3).toFixed(0)}s · ${((z||0)/1e3).toFixed(1)}K tokens · ${F||0} tools)`:"";H.addOutput(M,{text:`${G} Subagent ${V} ${R?"completed":"failed"}${B}`,isStreaming:!1,timestamp:Date.now(),subagentName:V,toolOutput:P});break}case"subagent_stream":{const{toolUseId:T,parentAgentId:M,entries:R}=t.payload;H.addSubagentStreamEntries(T,M,R);break}case"secrets_update":{const T=t.payload;H.setSecretsFromServer(T),console.log(`[WebSocket] Received ${T.length} secrets`);break}case"secret_created":{const T=t.payload;H.addSecretFromServer(T),console.log(`[WebSocket] Secret created: ${T.name}`);break}case"secret_updated":{const T=t.payload;H.updateSecretFromServer(T),console.log(`[WebSocket] Secret updated: ${T.name}`);break}case"secret_deleted":{const{id:T}=t.payload;H.removeSecretFromServer(T),console.log(`[WebSocket] Secret deleted: ${T}`);break}case"database_connection_result":{const{buildingId:T,connectionId:M,success:R,error:P,serverVersion:U}=t.payload;H.setConnectionStatus(T,M,{connected:R,error:P,serverVersion:U}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${M}`);break}case"databases_list":{const{buildingId:T,connectionId:M,databases:R}=t.payload;H.setDatabases(T,M,R),console.log(`[WebSocket] Received ${R.length} databases for ${M}`);break}case"tables_list":{const{buildingId:T,connectionId:M,database:R,tables:P}=t.payload;H.setTables(T,M,R,P),console.log(`[WebSocket] Received ${P.length} tables for ${R}`);break}case"table_schema":{const{buildingId:T,connectionId:M,database:R,table:P,columns:U,indexes:q,foreignKeys:z}=t.payload;H.setTableSchema(T,M,R,P,{columns:U,indexes:q||[],foreignKeys:z||[]}),console.log(`[WebSocket] Received schema for ${P}`);break}case"query_result":{const{buildingId:T,result:M}=t.payload;H.setQueryResult(T,M),console.log(`[WebSocket] Query ${M.status}: ${M.rowCount??M.affectedRows??0} rows in ${M.duration}ms`);break}case"silent_query_result":{const{buildingId:T,query:M,requestId:R,success:P,affectedRows:U,error:q}=t.payload;H.setSilentQueryResult(T,{query:M,requestId:R,success:P,affectedRows:U,error:q}),console.log(`[WebSocket] Silent query ${P?"succeeded":"failed"}: ${U??0} affected rows`);break}case"query_history_update":{const{buildingId:T,history:M}=t.payload;H.setQueryHistory(T,M),console.log(`[WebSocket] Received ${M.length} query history entries for ${T}`);break}}vb.end(`ws:${t.type}`)}MR(()=>yu());let Ok=!1;function xj(){const t=yp();t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Page unloading");const e=dj();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),_R()}function HR(){Ok||(window.addEventListener("beforeunload",xj),Ok=!0)}function yj(){xj(),H.setConnected(!1),H.stopStatusPolling()}function UR(){yj(),yb(0),setTimeout(()=>yu(),100)}function yu(){HR();const t=dj();t&&(clearTimeout(t),fj(null));const e=yp();if(TR()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){Mk()&&Pe.onReconnect&&Pe.onReconnect();return}yb(xb()+1),Mc(!0);const n=nx(),s=Ti(),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{Mc(!1),Lk();return}Ek(i),i.onopen=()=>{var d,f,h;const c=Mk();Mc(!1),yb(0),ER(),H.setConnected(!0),H.startStatusPolling(),H.clearAllPermissions(),c?((d=Pe.onToast)==null||d.call(Pe,"success","Reconnected","Connection restored - refreshing data..."),(f=Pe.onReconnect)==null||f.call(Pe)):(h=Pe.onToast)==null||h.call(Pe,"success","Connected","Connected to Tide Commander server"),NR(n,s),BR()},i.onmessage=c=>{try{const d=JSON.parse(c.data),f=ix(d);console.log("[AgentDebugger] RECEIVED - type:",d.type,"agentId:",f,"payload:",d.payload),f&&ms.captureReceived(f,c.data),$R(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;Mc(!1),Ek(null),H.setConnected(!1),H.stopStatusPolling();const c=xb();c<_k?((d=Pe.onToast)==null||d.call(Pe,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${c+1}/${_k})`),Lk()):(f=Pe.onToast)==null||f.call(Pe,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},i.onerror=()=>{Mc(!1)},H.setSendMessage(ox)}function Lk(){const t=xb(),e=Math.min(1e3*Math.pow(2,t-1),3e4);fj(setTimeout(yu,e))}function WR(t,e){const n={position:t,target:e};va(ft.CAMERA_STATE,n)}function qR(){return na(ft.CAMERA_STATE,null)}function Qq(t,e,n){const s={posX:t,posZ:e,zoom:n};va(ft.CAMERA_STATE_2D,s)}function Xq(){return na(ft.CAMERA_STATE_2D,null)}function Ml(){return{Authorization:`Bearer ${Ti()}`,"Content-Type":"application/json"}}async function VR(){const t=await fetch(`${Ca()}/api/workspaces`,{headers:Ml()});if(!t.ok)throw new Error(`Failed to fetch workspaces: ${t.statusText}`);return t.json()}async function GR(t,e){const n=await fetch(`${Ca()}/api/workspaces`,{method:"POST",headers:Ml(),body:JSON.stringify({name:t,areaIds:e})});if(!n.ok)throw new Error(`Failed to create workspace: ${n.statusText}`);return n.json()}async function Pk(t,e){const n=await fetch(`${Ca()}/api/workspaces/${t}`,{method:"PUT",headers:Ml(),body:JSON.stringify(e)});if(!n.ok)throw new Error(`Failed to update workspace: ${n.statusText}`);return n.json()}async function YR(t){const e=await fetch(`${Ca()}/api/workspaces/${t}`,{method:"DELETE",headers:Ml()});if(!e.ok)throw new Error(`Failed to delete workspace: ${e.statusText}`)}async function KR(){const t=await fetch(`${Ca()}/api/workspaces/active`,{headers:Ml()});if(!t.ok)throw new Error(`Failed to get active workspace: ${t.statusText}`);return(await t.json()).activeWorkspaceId??null}async function Ik(t){const e=await fetch(`${Ca()}/api/workspaces/active`,{method:"PUT",headers:Ml(),body:JSON.stringify({workspaceId:t})});if(!e.ok)throw new Error(`Failed to set active workspace: ${e.statusText}`)}const vu=new Set;let Xa=null,no=[],vj=!1;const kb=new Set;function tg(t){vj=t,kb.forEach(e=>e(t))}const wj="tide-commander-active-workspace";function Bk(){return typeof window>"u"?null:localStorage.getItem(wj)||null}function ng(t){typeof window>"u"||localStorage.setItem(wj,t||"")}function Rc(){vu.forEach(t=>t())}function QR(){return Xa}function vp(t){return Xa?t?Xa.areaIds.includes(t):!1:!0}function Jq(t){return Xa?Xa.areaIds.includes(t):!0}function lx(){const[,t]=b.useState(0);return b.useEffect(()=>{const e=()=>t(n=>n+1);return vu.add(e),()=>{vu.delete(e)}},[]),[Xa,no]}function XR(t){return vu.add(t),()=>{vu.delete(t)}}function JR(){const[t,e]=b.useState(vj);return b.useEffect(()=>{const n=s=>e(s);return kb.add(n),()=>{kb.delete(n)}},[]),t}const sg=new Map,kj=Ce.memo(function(){const{t:e}=pt("common"),n=rr(),[s,a]=b.useState([]),[r,i]=b.useState(()=>Bk()),[c,d]=b.useState(!1),[f,h]=b.useState(!1),[m,x]=b.useState(!0),[y,v]=b.useState(null),[S,C]=b.useState(""),[k,N]=b.useState([]),[A,E]=b.useState(!1),D=b.useRef(null);b.useEffect(()=>{let z=!1;return(async()=>{try{const F=Bk(),[$,V]=await Promise.all([VR(),KR()]);if(z)return;const G=F&&$.some(B=>B.id===F)?F:V&&$.some(B=>B.id===V)?V:null;a($),no=$,i(G),ng(G),Xa=$.find(B=>B.id===G)??null,Rc()}catch(F){console.error("workspace error:",F)}finally{z||x(!1)}})(),()=>{z=!0}},[]),b.useEffect(()=>{if(!c&&!f)return;const z=F=>{D.current&&!D.current.contains(F.target)&&(d(!1),h(!1))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[c,f]);const _=b.useMemo(()=>s.find(z=>z.id===r)??null,[s,r]),I=b.useCallback(async z=>{tg(!0);const F=Date.now();if(r){const B=qR();B&&(sg.set(r,B),Pk(r,{cameraState:B}).then(Q=>{a(K=>{const W=K.map(be=>be.id===r?Q:be);return no=W,W})}).catch(Q=>console.error("workspace error:",Q)))}i(z),ng(z),d(!1);const $=z?s.find(B=>B.id===z)??null:null;if(Xa=$,no=s,Rc(),z){const Q=($==null?void 0:$.cameraState)??sg.get(z);Q&&(WR(Q.position,Q.target),sg.set(z,Q))}Ik(z).catch(B=>console.error("workspace error:",B));const V=Date.now()-F,G=400;V<G?setTimeout(()=>tg(!1),G-V):tg(!1)},[r,s]),O=b.useMemo(()=>Array.from(n.values()).filter(z=>!z.archived),[n]),T=b.useCallback(async()=>{if(S.trim())try{const z=await GR(S.trim(),k),F=[...s,z];a(F),no=F,Rc(),C(""),N([]),E(!1)}catch(z){console.error("workspace error:",z)}},[S,k,s]),M=b.useCallback(async()=>{if(!(!y||!S.trim()))try{const z=await Pk(y,{name:S.trim(),areaIds:k}),F=s.map($=>$.id===y?z:$);a(F),no=F,y===r&&(Xa=z),Rc(),v(null),C(""),N([])}catch(z){console.error("workspace error:",z)}},[y,S,k,s,r]),R=b.useCallback(async z=>{try{await YR(z);const F=s.filter($=>$.id!==z);a(F),no=F,r===z&&(i(null),ng(null),Xa=null,await Ik(null).catch($=>console.error("workspace error:",$))),Rc()}catch(F){console.error("workspace error:",F)}},[s,r]),P=b.useCallback(z=>{v(z.id),C(z.name),N([...z.areaIds]),E(!1)},[]),U=b.useCallback(()=>{v(null),C(""),N([]),E(!0)},[]),q=b.useCallback(z=>{N(F=>F.includes(z)?F.filter($=>$!==z):[...F,z])},[]);return m?null:o.jsxs("div",{className:"workspace-switcher",ref:D,children:[o.jsxs("button",{className:"workspace-switcher-trigger",onClick:()=>{d(!c),h(!1)},title:"Workspaces",children:[o.jsx("span",{className:"workspace-switcher-icon",children:"📂"}),o.jsx("span",{className:"workspace-switcher-label",children:_?_.name:e("agentBar.allWorkspaces",{defaultValue:"All"})}),o.jsx("span",{className:"workspace-switcher-arrow",children:c?"▲":"▼"})]}),c&&!f&&o.jsxs("div",{className:"workspace-switcher-dropdown",children:[o.jsx("button",{className:`workspace-switcher-option ${r?"":"active"}`,onClick:()=>I(null),children:e("agentBar.allWorkspaces",{defaultValue:"All"})}),s.map(z=>o.jsxs("button",{className:`workspace-switcher-option ${z.id===r?"active":""}`,onClick:()=>I(z.id),children:[z.name,o.jsx("span",{className:"workspace-switcher-option-count",children:z.areaIds.length})]},z.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(z=>o.jsx("div",{className:"workspace-switcher-manager-item",children:y===z.id?o.jsxs("div",{className:"workspace-switcher-editor",children:[o.jsx("input",{type:"text",value:S,onChange:F=>C(F.target.value),className:"workspace-switcher-input",placeholder:"Workspace name",autoFocus:!0,onKeyDown:F=>{F.key==="Enter"&&M(),F.key==="Escape"&&v(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:()=>q(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:()=>v(null),children:"Cancel"})]})]}):o.jsxs("div",{className:"workspace-switcher-manager-row",children:[o.jsx("span",{className:"workspace-switcher-manager-name",children:z.name}),o.jsxs("span",{className:"workspace-switcher-manager-count",children:[z.areaIds.length," areas"]}),o.jsx("button",{className:"workspace-switcher-btn-edit",onClick:()=>P(z),title:"Edit",children:"✏"}),o.jsx("button",{className:"workspace-switcher-btn-delete",onClick:()=>R(z.id),title:"Delete",children:"🗑"})]})},z.id))}),A?o.jsxs("div",{className:"workspace-switcher-editor workspace-switcher-create-form",children:[o.jsx("input",{type:"text",value:S,onChange:z=>C(z.target.value),className:"workspace-switcher-input",placeholder:"New workspace name",autoFocus:!0,onKeyDown:z=>{z.key==="Enter"&&T(),z.key==="Escape"&&E(!1)}}),o.jsxs("div",{className:"workspace-switcher-area-list",children:[O.map(z=>o.jsxs("label",{className:"workspace-switcher-area-check",children:[o.jsx("input",{type:"checkbox",checked:k.includes(z.id),onChange:()=>q(z.id)}),o.jsx("span",{style:{color:z.color},children:z.name})]},z.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:T,children:"Create"}),o.jsx("button",{className:"workspace-switcher-btn-cancel",onClick:()=>E(!1),children:"Cancel"})]})]}):o.jsxs("button",{className:"workspace-switcher-option workspace-switcher-add",onClick:U,children:["+ ",e("agentBar.newWorkspace",{defaultValue:"New Workspace"})]})]})]})}),qf="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 wp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function Sj(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function ZR(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function wu(t){typeof window<"u"&&(window.__tidePersistedScene=t)}function iu(t){typeof window<"u"&&(window.__tidePersistedCanvas=t)}function Cj(t){typeof window<"u"&&(window.__tideWsConnected=t)}function eO(t){typeof window<"u"&&(window.__tideIsPageUnloading=t)}function tO(){sessionStorage.setItem(qf,"true")}function Zd(t){eO(!0),sessionStorage.removeItem(qf),yj(),DR(),window.__tideScene&&(window.__tideScene=null);const e=wp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),wu(null)):console.log("[App] No persistedScene to dispose"),iu(null),Cj(!1);const n=document.getElementById("battlefield");n&&n.remove();const s=document.getElementById("app");s&&(s.innerHTML="")}function nO(){var a,r;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(qf)==="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=wp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}wu(null)}const n=document.getElementById("battlefield"),s=Sj();n&&n!==s&&n.remove(),sessionStorage.removeItem(qf)}function sO(){typeof window>"u"||(nO(),window.addEventListener("pageshow",t=>{t.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Zd(),window.location.reload())}),window.onunload=()=>Zd(),window.onbeforeunload=t=>{Zd()},window.addEventListener("pagehide",t=>{Zd(`pagehide (persisted=${t.persisted})`)}))}sO();const Fk={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},zk={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},$k={idleAnimation:"sit",workingAnimation:"sprint"},aO=0;function Aj(){const t={characterScale:2,scale2d:.7,scale3d:.7,show2DTaskLabels:!0,gridVisible:!1,timeMode:"day",terrain:Fk,modelStyle:zk,animations:$k,fpsLimit:aO},e=na(ft.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:{...Fk,...e.terrain},modelStyle:{...zk,...e.modelStyle},animations:{...$k,...e.animations},fpsLimit:e.fpsLimit??t.fpsLimit}}return t}function rO(t){va(ft.CONFIG,t)}function iO(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function jj(){console.log("[Tide HMR] Manual scene refresh triggered");const t=wp();if(t){try{t.dispose()}catch(n){console.warn("[Tide HMR] Error disposing scene:",n)}wu(null)}iu(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=jj);function oO({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:x,openBossLogsModal:y,openDatabasePanel:v,onSceneLoadingChange:S}){const C=b.useRef(null),k=b.useRef(null),N=b.useRef(null),A=b.useRef(null),E=b.useRef(null);return b.useEffect(()=>{if(n!=="3d"){S==null||S(!1);return}if(!t.current||!e.current)return;let D=!1;S==null||S(!0);const _=wp(),O=Sj()===t.current;function T(){var R,P,U,q,z,F,$,V;(R=C.current)==null||R.setOnToast(a),(P=C.current)==null||P.setOnBuildingClick((G,B)=>{H.selectBuilding(G);const Q=H.getState().buildings.get(G);(Q==null?void 0:Q.type)==="folder"&&Q.folderPath?H.openFileExplorer(Q.folderPath):(Q==null?void 0:Q.type)==="server"||(Q==null?void 0:Q.type)==="boss"||(Q==null?void 0:Q.type)==="database"?(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{f({buildingId:G,screenPos:B,fromClick:!0}),k.current=null},150)):m(G)}),(U=C.current)==null||U.setOnContextMenu((G,B,Q)=>{c.open(G,B,Q)}),(q=C.current)==null||q.setOnAgentHover(()=>{}),(z=C.current)==null||z.setOnBuildingHover((G,B)=>{const Q=h();if(G&&B){const K=H.getState().buildings.get(G);((K==null?void 0:K.type)==="server"||(K==null?void 0:K.type)==="boss"||(K==null?void 0:K.type)==="database")&&!(Q!=null&&Q.fromClick)&&f({buildingId:G,screenPos:B,fromClick:!1})}else Q!=null&&Q.fromClick||f(null)}),(F=C.current)==null||F.setOnGroundClick(()=>{f(null)}),($=C.current)==null||$.setOnAreaDoubleClick(G=>{H.selectArea(G),i.open()}),(V=C.current)==null||V.setOnBuildingDoubleClick(G=>{var Q;k.current&&(clearTimeout(k.current),k.current=null),f(null);const B=H.getState().buildings.get(G);(B==null?void 0:B.type)==="server"&&((Q=B.pm2)!=null&&Q.enabled)?x==null||x(G):(B==null?void 0:B.type)==="boss"?y==null||y(G):(B==null?void 0:B.type)==="database"?v==null||v(G):(B==null?void 0:B.type)==="folder"&&B.folderPath?H.openFileExplorer(B.folderPath):m(G)})}if(_)try{C.current=_,O?(console.log("[Tide] Reusing existing scene (StrictMode remount)"),_.ensureRenderLoopRunning()):(console.log("[Tide] Reattaching persisted scene to new canvas"),_.reattach(t.current,e.current),iu(t.current));const R=H.getState();_.syncAreas(),_.syncBuildings(),R.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",R.agents.size),_.syncAgents(Array.from(R.agents.values()))),T()}catch(R){console.error("[Tide] Failed to reattach persisted 3D scene:",R),S==null||S(!1)}finally{A.current=requestAnimationFrame(()=>{E.current=requestAnimationFrame(()=>{S==null||S(!1),E.current=null}),A.current=null})}else{const R=t.current,P=e.current,U=async()=>{if(D){console.log("[Tide] Effect cleaned up before scene init, skipping"),S==null||S(!1);return}if(!R.isConnected||!P.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),S==null||S(!1);return}(!R.clientWidth||!R.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),R.style.width="100%",R.style.height="100%",R.offsetHeight),(!R.clientWidth||!R.clientHeight)&&(R.width=window.innerWidth,R.height=window.innerHeight),tO();try{const{SceneManager:q}=await vt(async()=>{const{SceneManager:$}=await import("./SceneManager-G0H-cWU4.js");return{SceneManager:$}},__vite__mapDeps([6,4,3,1]));if(D){S==null||S(!1);return}const z=new q(R,P);C.current=z,wu(z),iu(R);const F=Aj();z.setCharacterScale(F.characterScale),z.setScale3D(F.scale3d),z.setTimeMode(F.timeMode),z.setTerrainConfig(F.terrain),z.setFloorStyle(F.terrain.floorStyle,!0),z.setGridVisible(F.gridVisible),z.setAgentModelStyle(F.modelStyle),z.setIdleAnimation(F.animations.idleAnimation),z.setWorkingAnimation(F.animations.workingAnimation),z.setFpsLimit(F.fpsLimit),z.syncAreas(),z.syncBuildings(),z.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const $=H.getState();$.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",$.customAgentClasses.size),z.setCustomAgentClasses($.customAgentClasses)),$.agents.size>0&&(console.log("[Tide] Syncing agents from store:",$.agents.size),z.syncAgents(Array.from($.agents.values()))),z.upgradeAgentModels()}).catch($=>{console.warn("[Tide] Some models failed to load, using fallback:",$)}).finally(()=>{S==null||S(!1)}),T()}catch(q){console.error("[Tide] Failed to initialize 3D scene:",q),S==null||S(!1)}};N.current=requestAnimationFrame(()=>void U())}hj({onAgentCreated:R=>{var P,U,q;(P=C.current)==null||P.addAgent(R),(U=C.current)==null||U.refreshSelectionVisuals(),(q=window.__spawnModalSuccess)==null||q.call(window)},onAgentUpdated:(R,P)=>{var q;const U=H.getState().agents.get(R.id)||R;(q=C.current)==null||q.updateAgent(U,P)},onAgentDeleted:R=>{var P;(P=C.current)==null||P.removeAgent(R)},onAgentsSync:R=>{var U;const P=Array.from(H.getState().agents.values());(U=C.current)==null||U.syncAgents(P)},onAreasSync:()=>{var P,U;(P=C.current)==null||P.syncAreas();const R=Array.from(H.getState().agents.values());(U=C.current)==null||U.syncAgents(R)},onSpawnError:()=>{var R;(R=window.__spawnModalError)==null||R.call(window)},onSpawnSuccess:()=>{var R;(R=window.__spawnModalSuccess)==null||R.call(window)},onDirectoryNotFound:R=>{var P;(P=window.__spawnModalDirNotFound)==null||P.call(window,R)},onToolUse:(R,P,U)=>{var q;(q=C.current)==null||q.showToolBubble(R,P,U)},onDelegation:(R,P)=>{var U;(U=C.current)==null||U.showDelegationEffect(R,P)},onCustomClassesSync:R=>{var P,U;(P=C.current)==null||P.setCustomAgentClasses(R),(U=C.current)==null||U.upgradeAgentModels()},onBuildingUpdated:R=>{var P;(P=C.current)==null||P.updateBuilding(R)},onSubagentStarted:R=>{var P;(P=C.current)==null||P.addSubagentEffect(R.id,R.parentAgentId,R.name,R.subagentType)},onSubagentCompleted:R=>{var q;const P=H.getSubagent(R)||H.getSubagentByToolUseId(R),U=(P==null?void 0:P.id)||R;(q=C.current)==null||q.completeSubagentEffect(U),setTimeout(()=>{var z;(z=C.current)==null||z.removeSubagentEffect(U)},3e4)}});const M=XR(()=>{if(C.current){C.current.syncAreas(),C.current.syncBuildings();const R=Array.from(H.getState().agents.values());C.current.syncAgents(R)}});return()=>{M(),D=!0,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),H.getState().viewMode!=="3d"&&iO()&&C.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),RR(),C.current.dispose(),C.current=null,wu(null),iu(null))}},[n,s]),C}function lO({showToast:t,showAgentNotification:e}){b.useEffect(()=>{hj({onToast:t,onReconnect:()=>{H.triggerReconnect()},onAgentNotification:a=>{e(a)}}),ZR()||(yu(),Cj(!0)),CR();let n;jR(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&uj(a.agentId)}).then(a=>{n=a});const s=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>yu(),100)};return window.addEventListener("tideAppResume",s),()=>{window.removeEventListener("tideAppResume",s),n==null||n()}},[t,e])}function cO(t){b.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 x=`${h.position.x.toFixed(2)},${h.position.z.toFixed(2)},${h.status},${h.class},${h.isBoss},${((d=h.subordinateIds)==null?void 0:d.length)??0}`.split("").reduce((y,v)=>(y<<5)-y+v.charCodeAt(0),0);c.set(f,x),s.get(f)!==x&&(i=!0)}return c.size!==s.size&&(i=!0),{newVersion:c,changed:i}};return H.subscribe(()=>{var x;const r=H.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,(x=t.current)==null||x.refreshSelectionVisuals())})},[t])}function uO(t){b.useEffect(()=>{var s;(s=t.current)==null||s.syncAreas();let e=0,n=0;return H.subscribe(()=>{var c,d;const r=H.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 x=0;x<h.name.length;x++)m+=h.name.charCodeAt(x);for(let x=0;x<h.color.length;x++)m+=h.color.charCodeAt(x);if(h.directoryGitCounts)for(const x of h.directoryGitCounts)m+=(x+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 x=0;x<h.logo.position.length;x++)m+=h.logo.position.charCodeAt(x);if(h.logo.filename)for(let x=0;x<h.logo.filename.length;x++)m+=h.logo.filename.charCodeAt(x)}i^=m|0}i!==n&&(n=i,(d=t.current)==null||d.syncAreas())})},[t])}function dO(t){b.useEffect(()=>{var s;(s=t.current)==null||s.syncBuildings();let e=0,n=0;return H.subscribe(()=>{var c,d;const r=H.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 x=0;x<m.length;x++)i=(i<<5)-i+m.charCodeAt(x)|0}i!==n&&(n=i,(d=t.current)==null||d.syncBuildings())})},[t])}function fO(t,e){b.useEffect(()=>{var n;(n=t.current)==null||n.highlightArea(e)},[t,e])}function pO(t,e){b.useEffect(()=>{var n;(n=t.current)==null||n.setPowerSaving(e)},[t,e])}function Bt(t,e,n,s,a={},r="global"){return{id:t,name:e,description:n,key:s,modifiers:a,enabled:!0,context:r}}const ag=[Bt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Bt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Bt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Bt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Bt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Bt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Bt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Bt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Bt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Bt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Bt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Bt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Bt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Bt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Bt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Bt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Bt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Bt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Bt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Bt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Bt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Bt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Bt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Bt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Bt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Bt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Bt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Bt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Bt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Bt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Bt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Bt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Bt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Bt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Bt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Bt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Bt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Bt("clear-context","Clear Context","Clear context of the selected agent","c",{alt:!0,shift:!0}),Bt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Bt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Bt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Bt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Bt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Bt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Bt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Bt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Bt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Bt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function kn(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 hO(t){return t===" "||t==="Space"?"space":(t.length===1,t.toLowerCase())}function mO(t){const e=t.trim().toLowerCase();if(e==="space")return"Space";if(e==="esc")return"Escape";if(e==="return")return"Enter";const n={escape:"Escape",enter:"Enter",tab:"Tab",backspace:"Backspace",delete:"Delete",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown"};return n[e]?n[e]:e}function gO(t){if(!(t!=null&&t.key))return"";const e=[];return t.modifiers.ctrl&&e.push("ctrl"),t.modifiers.alt&&e.push("alt"),t.modifiers.shift&&e.push("shift"),t.modifiers.meta&&e.push("meta"),e.push(hO(t.key)),e.join("+")}function cx(t){if(!t)return null;const e=t.split("+").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return null;const n=e[e.length-1],s={};for(const r of e.slice(0,-1))r==="ctrl"||r==="control"?s.ctrl=!0:r==="alt"||r==="option"?s.alt=!0:r==="shift"?s.shift=!0:(r==="meta"||r==="cmd"||r==="command")&&(s.meta=!0);const a=mO(n);return a?{key:a,modifiers:s}:null}function bO(t){const e=cx(t);return e?Sb({key:e.key,modifiers:e.modifiers}):""}function xO(t,e){const n=cx(e);return n?kn(t,{key:n.key,modifiers:n.modifiers,enabled:!0}):!1}function Sb(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 yO(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 vO({sceneRef:t,spawnModal:e,commanderModal:n,explorerModal:s,spotlightModal:a,deleteConfirmModal:r,onRequestBuildingDelete:i,onOpenDatabasePanel:c,onCloseDatabasePanel:d,databasePanelOpen:f}){b.useEffect(()=>{const h=m=>{var P,U,q,z,F;const x=H.getShortcuts(),y=m.target,v=y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true"||!!y.closest(".cm-editor"),S=H.getState(),C=x.find($=>$.id==="deselect-all");if(kn(m,C)){if(y.closest(".guake-bottom-terminal-embed"))return;if(Cf()){m.preventDefault();return}if(S.activeTool==="rectangle"||S.activeTool==="circle"){(P=t.current)==null||P.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():S.terminalOpen?(H.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(H.deselectAll(),(U=t.current)==null||U.refreshSelectionVisuals())}for(let $=1;$<=9;$++){const V=x.find(G=>G.id===`select-agent-${$}`);if(kn(m,V)){m.preventDefault();const G=H.getState(),B=$-1,Q=Array.from(G.agents.keys());B<Q.length&&(H.selectAgent(Q[B]),(q=t.current)==null||q.refreshSelectionVisuals());return}}const k=x.find($=>$.id==="spawn-agent");if(kn(m,k)){m.preventDefault(),e.open();return}const N=x.find($=>$.id==="toggle-commander-tab");if(kn(m,N)&&!v){m.preventDefault(),n.toggle();return}const A=x.find($=>$.id==="toggle-commander");if(kn(m,A)){m.preventDefault(),n.toggle();return}const E=x.find($=>$.id==="toggle-file-explorer");if(kn(m,E)){m.preventDefault();const $=H.getState();if(s.isOpen||$.explorerFolderPath!==null||$.explorerAreaId!==null)s.close(),H.closeFileExplorer();else{const G=H.getLastExplorerState();if((G==null?void 0:G.type)==="folder")H.openFileExplorer(G.path);else if((G==null?void 0:G.type)==="area")if($.areas.has(G.areaId))s.open(G.areaId);else{const B=Array.from($.areas.values()).filter(Q=>Q.directories&&Q.directories.length>0);B.length>0&&s.open(B[0].id)}else{const B=Array.from($.areas.values()).filter(Q=>Q.directories&&Q.directories.length>0);B.length>0&&s.open(B[0].id)}}return}if(m.altKey&&!m.ctrlKey&&!m.shiftKey&&!m.metaKey&&m.code==="KeyD"){if(m.preventDefault(),m.stopPropagation(),f){d();return}const $=localStorage.getItem("tide-commander-last-database-building"),V=H.getState();if($){const G=V.buildings.get($);if((G==null?void 0:G.type)==="database"){c($);return}}for(const[G,B]of V.buildings)if(B.type==="database"){c(G);return}return}const D=x.find($=>$.id==="toggle-spotlight");if(kn(m,D)||m.altKey&&!m.ctrlKey&&!m.metaKey&&m.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:D,altKey:m.altKey,code:m.code}),m.preventDefault(),a.toggle();return}const _=x.find($=>$.id==="toggle-2d-view");if(kn(m,_)){m.preventDefault();const $=H.getState().viewMode,V=$==="3d"?"2d":$==="2d"?"dashboard":"3d";H.setViewMode(V);return}const I=x.find($=>$.id==="clear-context");if(kn(m,I)){m.preventDefault();const $=H.getState(),V=$.selectedAgentIds.size===1?Array.from($.selectedAgentIds)[0]:null;V&&H.clearContext(V);return}const O=x.find($=>$.id==="next-working-agent"),T=x.find($=>$.id==="prev-working-agent");if((kn(m,O)||kn(m,T))&&!v){const $=H.getState();if($.terminalOpen)return;const V=Array.from($.agents.values());let G=V.filter(W=>$.agentsWithUnseenOutput.has(W.id));if(G.length===0&&(G=V.filter(W=>W.status==="working")),G.length===0)return;m.preventDefault();const B=$.selectedAgentIds.size===1?Array.from($.selectedAgentIds)[0]:null,Q=B?G.findIndex(W=>W.id===B):-1;let K;kn(m,O)?K=Q===-1?0:(Q+1)%G.length:K=Q===-1?G.length-1:(Q-1+G.length)%G.length,H.selectAgent(G[K].id),(z=t.current)==null||z.refreshSelectionVisuals();return}const M=x.find($=>$.id==="delete-selected"),R=x.find($=>$.id==="delete-selected-backspace");if((kn(m,M)||kn(m,R))&&!v){const $=H.getState();if($.selectedAgentIds.size>0){m.preventDefault(),r.open();return}if($.selectedBuildingIds.size>0){m.preventDefault(),i();return}return}if(!v){const $=Array.from(S.agents.values()).find(V=>{var B;const G=(B=V.shortcut)==null?void 0:B.trim();return G?xO(m,G):!1});if($){m.preventDefault(),m.stopPropagation(),H.selectAgent($.id),H.setTerminalOpen(!0),(F=t.current)==null||F.refreshSelectionVisuals();return}}};return document.addEventListener("keydown",h,!0),()=>document.removeEventListener("keydown",h,!0)},[t,e,n,s,a,r,i,c,d,f])}function wO(){const[t,e]=b.useState(!1);return window.__tideSetBackNavModal=e,b.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()&&(Cf()||(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()?Cf()?a=Date.now():(c=window.__tideSetBackNavModal)==null||c.call(window,!0):(Cf(),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 rg="agent-order-change";function kO(t){const e=b.useMemo(()=>new Set(t.map(d=>d.id)),[t]),[n,s]=b.useState(()=>na(ft.AGENT_ORDER,[]));b.useEffect(()=>{const d=f=>{s(f.detail)};return window.addEventListener(rg,d),()=>{window.removeEventListener(rg,d)}},[]);const a=b.useMemo(()=>{const d=n.filter(x=>e.has(x)),f=t.filter(x=>!d.includes(x.id)).map(x=>x.id),h=[...d,...f],m=new Map(t.map(x=>[x.id,x]));return h.map(x=>m.get(x)).filter(x=>x!==void 0)},[t,n,e]),r=b.useCallback(d=>{s(d),va(ft.AGENT_ORDER,d),window.dispatchEvent(new CustomEvent(rg,{detail:d}))},[]),i=b.useCallback((d,f)=>{const h=a.map(x=>x.id),[m]=h.splice(d,1);h.splice(f,0,m),r(h)},[a,r]),c=b.useCallback(()=>{s([]),va(ft.AGENT_ORDER,[])},[]);return b.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 ka(t){const e=b.useRef(null),n=b.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),s=b.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),t()),e.current=null},[t]);return{handleMouseDown:n,handleClick:s}}const SO=3e4;function CO(){const t=b.useRef(null);b.useEffect(()=>{const e=async()=>{var i,c;const n=H.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 Lt(_t(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!h.ok)continue;const x=((i=(await h.json()).files)==null?void 0:i.length)||0;s.set(d,x);for(const y of f){const v=H.getState().buildings.get(y);v&&v.gitChangesCount!==x&&H.updateBuildingLocal(y,{gitChangesCount:x})}}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 x=await Lt(_t(`/api/files/git-status?path=${encodeURIComponent(d)}`));if(!x.ok)continue;h=((c=(await x.json()).files)==null?void 0:c.length)||0,s.set(d,h)}const m=new Map;for(const x of f)m.has(x.areaId)||m.set(x.areaId,[]),m.get(x.areaId).push({dirIndex:x.dirIndex,count:h});for(const[x,y]of m){const v=H.getState().areas.get(x);if(!v)continue;const S=v.directoryGitCounts?[...v.directoryGitCounts]:new Array(v.directories.length).fill(0);let C=!1;for(const{dirIndex:k,count:N}of y)S[k]!==N&&(S[k]=N,C=!0);C&&H.updateAreaLocal(x,{directoryGitCounts:S})}}catch{}};return e(),t.current=setInterval(e,SO),()=>{t.current&&(clearInterval(t.current),t.current=null)}},[])}const ig={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:"",vibrationIntensity:1,tabTitle:"",tmuxMode:!1},Hk=90,og=["simple","chat","advanced"],Uk=55,Wk=20,qk=95,AO=200,jO=12e4,NO=5,ta=new Map;function TO(t){const e=ta.get(t);e&&(ta.delete(t),ta.set(t,e))}function EO(){for(;ta.size>NO;){const t=ta.keys().next().value;if(t!==void 0)ta.delete(t);else break}}function _O(t){ta.delete(t)}function MO(t){return t.trim().replace(/\r\n/g,`
|
|
43
43
|
`)}function Cb(t,e){return`${t}:${MO(e)}`}function Vk(t,e,n,s){if(t.uuid&&e.has(t.uuid))return!1;const a=t.isUserPrompt?"user":"assistant",r=Cb(a,t.text),i=t.timestamp||0,c=n.get(r);return c!==void 0&&Math.abs(i-c)<=jO?!1:i>s}function Nj({selectedAgentId:t,hasSessionId:e,reconnectCount:n,historyRefreshTrigger:s,lastPrompts:a,outputScrollRef:r}){const[i,c]=b.useState([]),[d,f]=b.useState(!1),[h,m]=b.useState(!1),[x,y]=b.useState(0),[v,S]=b.useState(!1),[C,k]=b.useState(!1),[N,A]=b.useState(0),E=b.useRef(!0),D=b.useRef(0),_=b.useRef(0),I=b.useRef(!1),O=b.useRef(!1),T=b.useRef(null),M=b.useRef(!1),R=b.useRef(null),P=b.useRef(null);b.useEffect(()=>(E.current=!0,()=>{E.current=!1}),[]),b.useEffect(()=>{if(!t||!e){c([]),_.current=0,k(!1),O.current=!1,A(0),f(!1),m(!1),y(fe=>fe+1),M.current=!1,R.current=null;return}const V=`${t}:${n}:${s}`;if(R.current===V)return;const G=T.current!==null&&T.current!==t,B=n>0,Q=G||B,K=!G&&!M.current&&e;T.current=t,M.current=e,R.current=V;let W;if(B){const fe=H.getOutputs(t);fe.length>0&&(W=fe.map(J=>({...J})))}P.current&&(clearTimeout(P.current),P.current=null),B&&ta.delete(t),D.current+=1;const be=D.current;if(m(!0),!B){const fe=ta.get(t);fe?(TO(t),c(fe.messages),_.current=fe.messages.length,k(fe.hasMore),O.current=fe.hasMore,A(fe.totalCount)):(c([]),_.current=0,k(!1),O.current=!1,A(0))}!K&&!B&&(P.current=setTimeout(()=>{f(!0)},150)),Lt(_t(`/api/agents/${t}/history?limit=${Hk}&offset=0`)).then(fe=>{if(!fe.ok)throw new Error(`HTTP ${fe.status}: ${fe.statusText}`);return fe.json()}).then(fe=>{if(be!==D.current)return;const J=Array.isArray(fe.messages)?fe.messages:[],xe=Array.isArray(fe.subagents)?fe.subagents:[];c(J),_.current=J.length;const je=fe.hasMore||!1;if(k(je),O.current=je,A(fe.totalCount||0),xe.length>0&&H.hydrateSubagentsFromHistory(t,xe),ta.set(t,{messages:J,hasMore:je,totalCount:fe.totalCount||0}),EO(),W&&W.length>0){const oe=J.length>0?Math.max(...J.map(De=>De.timestamp?new Date(De.timestamp).getTime():0)):0,Ee=new Set(J.map(De=>De.uuid).filter(De=>typeof De=="string"&&De.length>0)),Fe=new Map;for(const De of J){if(De.type!=="user"&&De.type!=="assistant")continue;const ge=Cb(De.type,De.content),Oe=De.timestamp?new Date(De.timestamp).getTime():0,te=Fe.get(ge)??0;Oe>te&&Fe.set(ge,Oe)}const Ve=W.filter(De=>Vk(De,Ee,Fe,oe));H.clearOutputs(t);for(const De of Ve)H.addOutput(t,De)}else if(J.length>0){const oe=Math.max(...J.map(ge=>ge.timestamp?new Date(ge.timestamp).getTime():0)),Ee=new Set(J.map(ge=>ge.uuid).filter(ge=>typeof ge=="string"&&ge.length>0)),Fe=new Map;for(const ge of J){if(ge.type!=="user"&&ge.type!=="assistant")continue;const Oe=Cb(ge.type,ge.content),te=ge.timestamp?new Date(ge.timestamp).getTime():0,$e=Fe.get(Oe)??0;te>$e&&Fe.set(Oe,te)}const Ve=H.getOutputs(t),De=Ve.filter(ge=>{const Oe=Vk(ge,Ee,Fe,oe);return Oe||console.warn(`[HISTORY-DEDUP] Removing live output: uuid=${ge.uuid||"none"} ts=${ge.timestamp} lastHistTs=${oe} text="${ge.text.slice(0,80)}"`),Oe});if(Ve.length!==De.length){console.warn(`[HISTORY-DEDUP] Cleared ${Ve.length-De.length}/${Ve.length} overlapping outputs for agent ${t}`),H.clearOutputs(t);for(const ge of De)H.addOutput(t,ge)}}if(!a.get(t)){for(let oe=J.length-1;oe>=0;oe--)if(J[oe].type==="user"){H.setLastPrompt(t,J[oe].content);break}}}).catch(fe=>{if(console.error("Failed to load history:",fe),c([]),_.current=0,k(!1),O.current=!1,A(0),Q&&W&&W.length>0){H.clearOutputs(t);for(const J of W)H.addOutput(t,J)}}).finally(()=>{E.current&&be===D.current&&(P.current&&(clearTimeout(P.current),P.current=null),f(!1),m(!1),y(fe=>fe+1))})},[t,e,n,s]);const U=b.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,S(!0);const B=_.current;try{const K=await(await Lt(_t(`/api/agents/${t}/history?limit=${Hk}&offset=${B}`))).json(),W=Array.isArray(K.subagents)?K.subagents:[];if(W.length>0&&H.hydrateSubagentsFromHistory(t,W),K.messages&&K.messages.length>0){if(!E.current)return;c(fe=>{const J=[...K.messages,...fe];return _.current=J.length,J});const be=K.hasMore||!1;O.current=be,k(be),requestAnimationFrame(()=>{requestAnimationFrame(()=>{E.current&&(r.current&&(r.current.scrollTop=r.current.scrollHeight-G),I.current=!1,S(!1))})})}else{if(!E.current)return;I.current=!1,S(!1)}}catch(Q){if(console.error("Failed to load more history:",Q),!E.current)return;I.current=!1,S(!1)}},[t,r]),q=b.useCallback(V=>{if(!r.current||V.current)return;const{scrollTop:G}=r.current;!I.current&&O.current&&G<AO&&U()},[U,r]),z=b.useCallback(()=>{c([]),_.current=0,t&&ta.delete(t)},[t]),F=b.useRef(!1),$=b.useCallback(async()=>{var V,G;if(!(!t||!O.current)&&!(I.current||F.current)){F.current=!0,I.current=!0,S(!0);try{const Q=await(await Lt(_t(`/api/agents/${t}/history?limit=100000&offset=0`))).json();if(!E.current)return;const K=Array.isArray(Q.subagents)?Q.subagents:[];K.length>0&&H.hydrateSubagentsFromHistory(t,K),Q.messages&&Q.messages.length>0&&(c(Q.messages),_.current=Q.messages.length),O.current=!1,k(!1),A(Q.totalCount||((V=Q.messages)==null?void 0:V.length)||0),ta.set(t,{messages:Q.messages||[],hasMore:!1,totalCount:Q.totalCount||((G=Q.messages)==null?void 0:G.length)||0})}catch(B){console.error("Failed to load all history:",B)}finally{E.current&&(I.current=!1,F.current=!1,S(!1))}}},[t]);return{history:i,loadingHistory:d,fetchingHistory:h,historyLoadVersion:x,loadingMore:v,hasMore:C,totalCount:N,isMountedRef:E,loadMoreHistory:U,loadAllHistory:$,allLoaded:!C,handleScroll:q,clearHistory:z,hasCachedHistory:b.useCallback(V=>ta.has(V),[])}}function Oc(...t){}function DO(t){return(t.tokensUsed??0)===0&&(t.contextUsed??0)===0&&!t.contextStats&&!t.sessionId&&!t.currentTask&&!t.lastAssignedTask}function Gk(t,e){var r,i;if(!t||DO(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 RO(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,Gk(h,f)),(f.class==="boss"||f.isBoss)&&Oc("[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 v;const c=t().agents.get(r.id);let d=r;const f=r.trackingStatus,h=f!=null&&f!=="working";(c==null?void 0:c.status)!=="working"&&r.status==="working"&&!h&&(d={...r,trackingStatus:"working",trackingStatusDetail:void 0,trackingStatusTimestamp:r.trackingStatusTimestamp??Date.now()});const x=(c==null?void 0:c.status)!==d.status;x&&Oc(`[Store] Agent ${d.name} status update: ${c==null?void 0:c.status} → ${d.status}`);let y=!1;e(S=>{const C=new Map(S.agents);C.set(d.id,Gk(c,d)),S.agents=C,x&&(c==null?void 0:c.status)==="working"&&d.status==="idle"&&(S.terminalOpen&&S.selectedAgentIds.has(d.id)||(S.agentsWithUnseenOutput=new Set(S.agentsWithUnseenOutput),S.agentsWithUnseenOutput.add(d.id),Oc(`[Store] Agent ${d.name} completed work - marked as unseen`),y=!0))}),y&&a&&a(),n(),x&&Oc(`[Store] Agent ${d.name} status now in store: ${(v=t().agents.get(d.id))==null?void 0:v.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(x=>{const y=new Map(x.agents),v=f.contextStats?{...f.contextStats,totalTokens:i,contextWindow:h,usedPercent:m,lastUpdated:Date.now()}:void 0;y.set(r,{...f,contextUsed:i,contextLimit:h,contextStats:v}),x.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)}),_O(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,x,y,v,S,C,k,N,A){Oc("[Store] spawnAgent called with:",{name:r,agentClass:i,cwd:c,position:d,sessionId:f,useChrome:h,permissionMode:m,initialSkillIds:x,provider:y,codexConfig:v,codexModel:S,model:C,effort:N,opencodeModel:A,customInstructions:k?`${k.length} chars`:void 0});const E=d?{x:d.x,y:0,z:d.z}:void 0,D={type:"spawn_agent",payload:{name:r,class:i,cwd:c,position:E,sessionId:f,useChrome:h,permissionMode:m,initialSkillIds:x,provider:y,codexConfig:v,codexModel:S,opencodeModel:A,model:C,effort:N,customInstructions:k}},_=s();if(!_){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}_(D)},createDirectoryAndSpawn(r,i,c){var d;(d=s())==null||d({type:"create_directory",payload:{path:r,name:i,class:c}})},sendCommand(r,i){var c;e(d=>{d.lastPrompts.set(r,{text:i,timestamp:Date.now()})}),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},x=new Map(h.agents);x.set(r,m),h.agents=x}),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,trackingStatus:void 0,trackingStatusDetail:void 0,trackingStatusTimestamp:void 0,currentTool:void 0,lastAssignedTask:void 0,lastAssignedTaskTime:void 0,sessionId:void 0,tokensUsed:0,contextUsed:0,contextStats:void 0},v=new Map(c.agents);v.set(r,y),c.agents=v}const f=new Map(c.agentOutputs);f.delete(r),c.agentOutputs=f;const h=new Map(c.lastPrompts);h.delete(r),c.lastPrompts=h;const m=new Map(c.subagents);let x=!1;for(const[y,v]of m)v.parentAgentId===r&&(m.delete(y),x=!0);x&&(c.subagents=m)}),n()},restoreSession(r,i){var c;(c=s())==null||c({type:"restore_session",payload:{agentId:r,sessionId:i}}),e(d=>{const f=d.agents.get(r);if(f){const x={...f,status:"idle",currentTask:void 0,taskLabel:void 0,currentTool:void 0,sessionId:i,tokensUsed:0,contextUsed:0,contextStats:void 0},y=new Map(d.agents);y.set(r,x),d.agents=y}const h=new Map(d.agentOutputs);h.delete(r),d.agentOutputs=h;const m=new Map(d.lastPrompts);m.delete(r),d.lastPrompts=m}),n()},requestSessionHistory(r){var i;(i=s())==null||i({type:"request_session_history",payload:{agentId:r}})},setSessionHistory(r,i){e(c=>{const d=new Map(c.sessionHistories);d.set(r,i),c.sessionHistories=d}),n()},getSessionHistory(r){return t().sessionHistories.get(r)||[]},collapseContext(r){var i;(i=s())==null||i({type:"collapse_context",payload:{agentId:r}})},removeAgentFromServer(r){var i;(i=s())==null||i({type:"remove_agent",payload:{agentId:r}})},renameAgent(r,i){var f;const d=t().agents.get(r);d&&(e(h=>{const m={...d,name:i},x=new Map(h.agents);x.set(r,m),h.agents=x}),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),i.shortcut!==void 0&&(m.shortcut=i.shortcut);const x=new Map(h.agents);x.set(r,m),h.agents=x}),n()),(f=s())==null||f({type:"update_agent_properties",payload:{agentId:r,updates:i}}),i.shortcut!==void 0&&Lt(_t(`/api/agents/${r}`),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:i.shortcut})}).catch(h=>{console.error("[Store] Failed to persist agent shortcut",h)})},getTotalTokens(){let r=0;for(const i of 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 Lt(_t("/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 Yk=200;function Kk(t){return t.length<=Yk?t:t.slice(-Yk)}function OO(t,e,n,s){return{addOutput(a,r){const i=s();e(c=>{const d=c.agentOutputs.get(a)||[];if(r.uuid&&d.some(x=>x.uuid===r.uuid))return;const f=Kk([...d,r]);xu.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=Kk(c),e(d=>{const f=new Map(d.agentOutputs);f.set(a,c),d.agentOutputs=f}),n(),c}}}function LO(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 PO(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 x=m.assignedAgentIds.indexOf(i);x!==-1&&m.assignedAgentIds.splice(x,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(v=>v.zIndex??0)),m=h+1,x=d.zIndex??0,y=f.filter(v=>(v.zIndex??0)===h);x===h&&y.length===1||(e(v=>{v.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,x=f.filter(y=>(y.zIndex??0)===h);m===h&&x.length===1||(e(y=>{for(const v of y.areas.values())v.id!==i&&(v.zIndex=(v.zIndex??0)+1);y.areas.get(i).zIndex=0}),r(),a(),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,x=m.x-h.x,y=m.z-h.z,v=Array.from(d.areas.values()),C=(v.length===0?-1:Math.max(...v.map(k=>k.zIndex??0)))+1;e(k=>{const N=k.areas.get(i);if(N.archived=!1,N.archivedAt=void 0,N.center=m,N.zIndex=C,x!==0||y!==0)for(const A of N.assignedAgentIds){const E=k.agents.get(A);E&&(E.position={x:E.position.x+x,y:E.position.y,z:E.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 Tj="tide:bottom-pm2-log-retention",lg=5e3,IO=[1e3,2500,5e3,1e4,null];function Ej(){if(typeof window>"u")return lg;try{const t=window.localStorage.getItem(Tj);if(!t)return lg;if(t==="unlimited")return null;const e=Number(t);if(Number.isFinite(e)&&e>0)return Math.floor(e)}catch{}return lg}function BO(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Tj,t===null?"unlimited":String(t))}catch{}}function _j(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 FO(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 x of h.selectedBuildingIds)m.delete(x);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(x=>{const y=new Map(x.buildings);y.delete(i),x.buildings=y,x.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(x=>{const y=new Map(x.streamingBuildingLogs);y.set(i,""),x.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=Ej(),m=_j(f+c,h),x=new Map(d.streamingBuildingLogs);x.set(i,m),d.streamingBuildingLogs=x}),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 x=new Map(m.buildings);x.set(i,{...f,subordinateBuildingIds:c}),m.buildings=x}),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 x=m.bossStreamingLogs.get(i)||[],y={subordinateId:c,subordinateName:d,chunk:f,timestamp:Date.now(),isError:h},v=[...x,y];v.length>1e3&&v.splice(0,v.length-1e3);const S=new Map(m.bossStreamingLogs);S.set(i,v),m.bossStreamingLogs=S}),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 zO(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 $O(t,e,n,s){return{spawnBossAgent(a,r,i,c,d,f,h,m,x,y,v,S,C){var N;const k=c?{x:c.x,y:0,z:c.z}:void 0;(N=s())==null||N({type:"spawn_boss_agent",payload:{name:a,class:r,cwd:i,position:k,subordinateIds:d,useChrome:f,permissionMode:h,provider:m,codexConfig:x,codexModel:y,model:v,customInstructions:S,initialSkillIds:C}})},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 x=new Map(c.agentTaskProgress),y=new Map(d);y.set(r,{...f,output:m}),x.set(a,y),c.agentTaskProgress=x}),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),x=new Map(d);x.set(r,{...f,status:i?"completed":"failed",completedAt:Date.now(),output:h}),m.set(a,x),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 HO(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 UO(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(`
|
|
@@ -149,5 +149,5 @@ ${Qe}`:re=Qe}H.sendCommand(n,re),P==null||P(),r(""),c(!1),C(new Map),h([]),k(),w
|
|
|
149
149
|
`)},v.onerror=V=>{Gt("WebSocket ERROR:",V)},x.onResize(({cols:V,rows:G})=>h(V,G))})(),()=>{var N;m=!0,c.current=!1,S==null||S.cancel(),C==null||C.disconnect(),k&&((N=s.current)==null||N.removeEventListener("contextmenu",k)),v&&v.readyState<=WebSocket.OPEN&&v.close(),i.current=null,x==null||x.dispose(),a.current=null,r.current=null}},[n,e,f,h]),b.useEffect(()=>{n&&r.current&&a.current&&requestAnimationFrame(()=>{var m;(m=r.current)==null||m.fit(),a.current&&h(a.current.cols,a.current.rows)})},[n,h]),o.jsx("div",{ref:s,className:"guake-bottom-terminal-embed",style:{display:n?void 0:"none"}})}),yW=[{key:"working",title:"Working",emptyLabel:"No agents",toneClass:"working"},{key:"waiting-subordinates",title:"Waiting Subordinates",emptyLabel:"No agents",toneClass:"waiting-subordinates"},{key:"need-review",title:"Need Review",emptyLabel:"No agents",toneClass:"need-review"},{key:"blocked",title:"Blocked",emptyLabel:"No agents",toneClass:"blocked"},{key:"can-clear-context",title:"Can Clear Context",emptyLabel:"No agents",toneClass:"can-clear-context"}];function vW({activeAgentId:t,onSelectAgent:e}){const{t:n}=pt(["terminal","common"]),[s]=lx(),a=tL(),[r,i]=b.useState(new Set),c=b.useMemo(()=>yW.map(y=>{const v=a[y.key].filter(S=>{if(!s)return!0;const C=H.getAreaForAgent(S.id);return vp((C==null?void 0:C.id)??null)}).sort((S,C)=>(C.trackingStatusTimestamp||0)-(S.trackingStatusTimestamp||0));return{...y,agents:v}}),[s,a]),d=b.useCallback(async y=>{try{const v=await Lt(_t(`/api/agents/${y}`),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({trackingStatus:null})});if(!v.ok)throw new Error(`Failed to clear tracking status: ${v.statusText}`);const S=H.getState().agents.get(y);S&&H.updateAgent({...S,trackingStatus:null,trackingStatusDetail:void 0,trackingStatusTimestamp:void 0})}catch(v){console.error("Failed to clear tracking status",v)}},[]),f=b.useCallback(async y=>{i(v=>new Set(v).add(y.id));try{await d(y.id)}finally{i(v=>{const S=new Set(v);return S.delete(y.id),S})}},[d]),[h,m]=b.useState(null),x=b.useCallback(async(y,v)=>{if(v.length!==0){m(y),i(S=>{const C=new Set(S);return v.forEach(k=>C.add(k.id)),C});try{for(const S of v)y==="can-clear-context"&&H.clearContext(S.id),await d(S.id)}finally{m(null),i(S=>{const C=new Set(S);return v.forEach(k=>C.delete(k.id)),C})}}},[d]);return o.jsx("div",{className:"tracking-board",children:c.map(y=>o.jsxs("section",{className:`tracking-board-column tracking-board-column--${y.toneClass}`,children:[o.jsxs("header",{className:"tracking-board-column-header",children:[o.jsx("span",{className:"tracking-board-column-indicator"}),o.jsx("span",{className:"tracking-board-column-title",children:y.title}),y.agents.length>0&&o.jsx("button",{type:"button",className:`tracking-board-column-action${y.key==="can-clear-context"?" tracking-board-column-action--context":""}`,onClick:()=>void x(y.key,y.agents),disabled:h===y.key,title:y.key==="can-clear-context"?"Clear context and status for all agents":"Clear status for all agents in this column",children:h===y.key?"Clearing...":y.key==="can-clear-context"?`Clear All (${y.agents.length})`:"Clear all"}),o.jsx("span",{className:"tracking-board-column-count",children:y.agents.length})]}),o.jsx("div",{className:"tracking-board-column-body",children:y.agents.length===0?o.jsx("div",{className:"tracking-board-empty",children:y.emptyLabel}):y.agents.map(v=>o.jsx(wW,{agent:v,isActive:v.id===t,isClearing:r.has(v.id),onSelectAgent:e,onClearStatus:f,timeLabel:v.trackingStatusTimestamp?xp(v.trackingStatusTimestamp):n("common:time.justNow",{defaultValue:"just now"})},v.id))})]},y.key))})}function wW({agent:t,isActive:e,isClearing:n,onSelectAgent:s,onClearStatus:a,timeLabel:r}){const i=Aa(),c=ir(t.class,i),d=!!c.iconPath;return o.jsxs("article",{className:`tracking-board-card${e?" active":""}`,onClick:()=>s(t.id),title:t.trackingStatusDetail||t.taskLabel||t.name,children:[o.jsx("div",{className:`tracking-board-card-avatar${d?"":" emoji"}`,style:d?void 0:{backgroundColor:c.color?`${c.color}22`:void 0},children:o.jsx(Vn,{agent:t,size:"100%",customClasses:i})}),o.jsxs("div",{className:"tracking-board-card-content",children:[o.jsxs("div",{className:"tracking-board-card-header",children:[o.jsx("span",{className:"tracking-board-card-name",children:t.name}),o.jsx("span",{className:"tracking-board-card-time",children:r}),o.jsx("button",{type:"button",className:"tracking-board-card-clear",onClick:f=>{f.stopPropagation(),a(t)},disabled:n,title:"Clear tracking status","aria-label":"Clear tracking status",children:"×"})]}),t.taskLabel&&o.jsx("div",{className:"tracking-board-card-task",title:t.taskLabel,children:t.taskLabel}),o.jsx("div",{className:"tracking-board-card-detail",children:t.trackingStatusDetail||t.currentTask||"No detail provided"})]})]})}const kW=128,SW=95;function CW(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 AW=1;function wf(){return`bp-${AW++}`}const jW=b.memo(function({buildingId:e,filterText:n,maxRetention:s}){const{streamingBuildingLogs:a}=ws(),r=a.get(e)||"",i=b.useRef(null),c=b.useRef(!1),d=b.useRef(0),f=n.trim().toLowerCase(),h=30,m=b.useCallback(()=>{const A=i.current;if(!A)return;const E=A.scrollTop+A.clientHeight>=A.scrollHeight-h;c.current=!E},[]),x=b.useMemo(()=>_j(r,s),[r,s]);b.useLayoutEffect(()=>{const A=i.current;if(!A)return;const E=d.current,D=A.scrollHeight;if(c.current){const _=E-D;_>0&&(A.scrollTop=Math.max(0,A.scrollTop-_))}else A.scrollTop=D;d.current=A.scrollHeight},[x,f]);const y=b.useMemo(()=>x?f?x.split(`
|
|
150
150
|
`).filter(A=>A.toLowerCase().includes(f)).join(`
|
|
151
151
|
`):x:"",[x,f]),v=b.useMemo(()=>y?y.split(`
|
|
152
|
-
`):[],[y]),S=b.useMemo(()=>v.map(A=>Sl(A||" ")),[v]),C=b.useMemo(()=>x?f&&!y?"No log lines match the current filter.":null:"Waiting for logs...",[x,f,y]),k=f1({count:S.length,getScrollElement:()=>i.current,estimateSize:()=>20,overscan:12,measureElement:A=>A.getBoundingClientRect().height}),N=k.getVirtualItems();return o.jsx("div",{ref:i,className:"guake-bottom-pm2-logs",onScroll:m,children:C?o.jsx("div",{className:"guake-bottom-pm2-logs-empty",children:C}):o.jsx("div",{className:"guake-bottom-pm2-logs-inner",style:{height:k.getTotalSize()},children:N.map(A=>o.jsx("div",{ref:k.measureElement,className:"guake-bottom-pm2-log-line","data-index":A.index,style:{transform:`translateY(${A.start}px)`},dangerouslySetInnerHTML:{__html:S[A.index]}},A.key))})})});b.memo(function({src:e,title:n}){const s=b.useRef(null),[a,r]=b.useState(!1),[i,c]=b.useState(null);b.useEffect(()=>{r(!1),c(null);const h=setTimeout(()=>c(e),400);return()=>clearTimeout(h)},[e]);const d=b.useCallback(()=>{var m;const h=s.current;if(h){document.activeElement===h&&h.blur();try{(m=h.contentWindow)==null||m.blur()}catch{}}},[]),f=b.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 b.useEffect(()=>{if(!i)return;const h=Date.now(),m=()=>{Date.now()-h>1500||(d(),f())};return window.addEventListener("focus",m,!0),document.addEventListener("focusin",m,!0),()=>{window.removeEventListener("focus",m,!0),document.removeEventListener("focusin",m,!0)}},[f,d,i]),o.jsxs(o.Fragment,{children:[!a&&o.jsx("div",{className:"guake-bottom-terminal-starting",children:o.jsx("span",{children:"Loading terminal..."})}),o.jsx("iframe",{ref:s,src:i??void 0,className:`guake-bottom-terminal-iframe${a?"":" iframe-loading"}`,title:n,allow:"clipboard-read; clipboard-write",loading:"lazy",tabIndex:-1,onLoad:()=>{r(!0),d(),f()}})]})});const NW=b.memo(function({onSaveSnapshot:e}={}){var dr,$l,So,Hl,Yr,la,Co,Kr,Ea,Ao,Di,Ul,Ri;const{t:n}=pt(["terminal","common"]),s=Dl(),a=fx(),r=Pj(),i=Ij(),c=mx(),d=gx(),f=SL(),h=!!f,m=b.useMemo(()=>f?{id:f.agentId,name:f.agentName,class:f.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:f.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:f.createdAt,lastActivity:f.createdAt}:null,[f]),x=Array.from(a),v=x.length===1?x[0]:null,C=(dx(v)||null)??(h?m:null),k=v??(h?(f==null?void 0:f.agentId)??null:null),N=_L(),A=rr(),E=hx(),D=b.useMemo(()=>{if(!k)return null;const Z=new Set,Te=[];for(const We of A.values())We.archived||We.directories.length===0||We.assignedAgentIds.includes(k)&&(Z.add(We.id),Te.push(We));const le=s.get(k);if(le)for(const We of A.values())We.archived||We.directories.length===0||Z.has(We.id)||CW({x:le.position.x,z:le.position.z},We)&&(Z.add(We.id),Te.push(We));return Te.length===0?null:Te.flatMap(We=>We.directories.filter(gt=>gt&>.trim().length>0).map(gt=>({areaId:We.id,areaName:We.name,dir:gt})))},[k,A,s]),_=b.useMemo(()=>{var le;if(!k)return[];const Z=H.getAreaForAgent(k);if(!Z)return[];const Te=[];for(const We of E.values())We.type==="terminal"&&H.isPositionInArea(We.position,Z)&&Te.push({id:We.id,name:We.name,hasUrl:!!((le=We.terminalStatus)!=null&&le.url)});return Te},[k,E,A]),I=b.useMemo(()=>{var le;if(!k)return[];const Z=H.getAreaForAgent(k);if(!Z)return[];const Te=[];for(const We of E.values())We.type==="server"&&((le=We.pm2)!=null&&le.enabled)&&H.isPositionInArea(We.position,Z)&&Te.push({id:We.id,name:We.name});return Te},[k,E,A]),O=b.useMemo(()=>{if(!k)return[];const Z=H.getAreaForAgent(k);if(!Z)return[];const Te=[];for(const le of E.values())le.type==="database"&&le.database&&H.isPositionInArea(le.position,Z)&&Te.push({id:le.id,name:le.name});return Te},[k,E,A]),{branches:T,fetchRemote:M,fetchingDirs:R}=a6(D),{terminalHeight:P,terminalRef:U,handleResizeStart:q}=JU(),{mobileOverviewHeight:z,handleResizeMouseDown:F,handleResizeTouchStart:$}=t6(),V=XU(),[G,B]=b.useState(()=>{const Z=ex(ft.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,Z))}),Q=b.useRef(null),K=b.useCallback((Z,Te)=>{Z.preventDefault(),Q.current={startX:Z.clientX,startW:G},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",H.setTerminalResizing(!0);let le=G;const We=Tt=>{if(!Q.current)return;const Cn=Tt.clientX-Q.current.startX,tn=Te==="left"?-Cn:Cn;le=Math.max(280,Math.min(700,Q.current.startW+tn)),B(le)},gt=()=>{Q.current=null,document.body.style.cursor="",document.body.style.userSelect="",H.setTerminalResizing(!1),document.removeEventListener("mousemove",We),document.removeEventListener("mouseup",gt),tx(ft.SIDE_PANEL_WIDTH,le)};document.addEventListener("mousemove",We),document.addEventListener("mouseup",gt)},[G]),W=b.useRef(null),be=b.useRef(null),[fe,J]=b.useState(()=>{const Z=wa(ft.VIEW_MODE);return Z==="simple"||Z==="chat"||Z==="advanced"?Z:wa(ft.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[xe,je]=b.useState(()=>_r(ft.TERMINAL_FULLSCREEN,!1)),[oe,Ee]=b.useState(null),[Fe,Ve]=b.useState(null),[De,ge]=b.useState(null),[Oe,te]=b.useState(null),[$e,se]=b.useState(!1);Qt("guake-image-modal",oe!==null,()=>Ee(null)),Qt("guake-bash-modal",Fe!==null,()=>Ve(null)),Qt("guake-response-modal",Oe!==null,()=>te(null)),Qt("guake-context-confirm",De!==null,()=>ge(null)),Qt("guake-agent-info",$e,()=>se(!1));const[Ne,_e]=b.useState(!1),[pe,Ge]=b.useState(()=>ms.isEnabled()),[it,dt]=b.useState(()=>_r(ft.GIT_PANEL_OPEN,!1)),ce=b.useCallback(Z=>{dt(Z),Qa(ft.GIT_PANEL_OPEN,Z)},[]),[X,ne]=b.useState(()=>_r(ft.BUILDINGS_PANEL_OPEN,!1)),ke=b.useCallback(Z=>{ne(Z),Qa(ft.BUILDINGS_PANEL_OPEN,Z)},[]),[ee,ye]=b.useState(()=>_r(ft.WORKFLOW_PANEL_OPEN,!1)),Ie=b.useCallback(Z=>{ye(Z),Qa(ft.WORKFLOW_PANEL_OPEN,Z)},[]),[He,ue]=b.useState(!1);b.useEffect(()=>{if(!k){ue(!1);return}let Z=!1;return(async()=>{try{const Te=await Lt(_t("/api/workflows/definitions"));if(Z||!Te.ok)return;const We=(await Te.json()).some(gt=>gt.states.some(Tt=>{var Cn,tn;return((Cn=Tt.action)==null?void 0:Cn.type)==="agent_task"&&((tn=Tt.action)==null?void 0:tn.agentId)===k}));Z||ue(We)}catch{Z||ue(!1)}})(),()=>{Z=!0}},[k]);const de=EL(),re=b.useCallback(Z=>H.setOverviewPanelOpen(Z),[]),[me,ve]=b.useState([]),[Ue,Qe]=b.useState({}),[ze,nt]=b.useState(()=>Ej()),[ot,st]=b.useState(()=>{try{return localStorage.getItem("tide:bottom-split-direction")==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[lt,rt]=b.useState(()=>{try{const Z=localStorage.getItem("tide:bottom-terminal-height");return Z?Math.max(120,Math.min(600,Number(Z))):250}catch{return 250}}),ht=b.useRef(null),[jt,he]=b.useState([1]),Me=b.useRef(null),Ye=b.useRef(null),[tt,Nt]=b.useState(null),[zt,Pt]=b.useState(null),It=b.useMemo(()=>me.filter(Z=>Z.areaId===zt),[me,zt]),Vt=b.useMemo(()=>new Set(It.map(Z=>Z.buildingId)),[It]),mt=b.useRef(new Map);b.useEffect(()=>{try{const Z=localStorage.getItem("tide:bottom-panels-v2");if(Z){const Te=JSON.parse(Z);mt.current=new Map(Te.map(([le,We])=>[le,We.map(gt=>({id:gt.id??wf(),type:gt.type,buildingId:gt.buildingId}))]))}else{const Te=localStorage.getItem("tide:bottom-terminals");if(Te){const le=JSON.parse(Te);for(const[We,gt]of le)mt.current.set(We,[{id:wf(),type:"terminal",buildingId:gt}])}}}catch{}},[]);const ct=b.useCallback(Z=>{if(!k)return;const Te=H.getAreaForAgent(k);if(Te)try{Z.length>0?mt.current.set(Te.id,Z.map(We=>({id:We.id,type:We.type,buildingId:We.buildingId}))):mt.current.delete(Te.id);const le=Array.from(mt.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(le))}catch{}},[k]),xt=b.useCallback(()=>{if(!k)return null;const Z=H.getAreaForAgent(k);return(Z==null?void 0:Z.id)??null},[k]),Dt=b.useCallback((Z,Te)=>{const le=xt();Qe({}),ve(We=>{for(const tn of We)tn.areaId===le&&tn.type==="pm2-logs"&&H.stopLogStreaming(tn.buildingId);const gt=We.filter(tn=>tn.areaId!==le),Tt={id:wf(),type:Te,buildingId:Z,areaId:le??void 0},Cn=[...gt,Tt];return ct([Tt]),Cn})},[ct,xt]),Sn=b.useCallback((Z,Te,le)=>{const We=xt();st(le);try{localStorage.setItem("tide:bottom-split-direction",le)}catch{}ve(gt=>{const Tt=gt.filter($n=>$n.areaId===We);if(Tt.length>=4||Tt.some($n=>$n.buildingId===Z))return gt;const Cn={id:wf(),type:Te,buildingId:Z,areaId:We??void 0},tn=[...gt,Cn];return ct(Tt.concat(Cn)),tn})},[ct,xt]),cn=b.useCallback(Z=>{Qe(Te=>{if(!(Z in Te))return Te;const le={...Te};return delete le[Z],le}),ve(Te=>{const le=Te.find(Tt=>Tt.id===Z);(le==null?void 0:le.type)==="pm2-logs"&&H.stopLogStreaming(le.buildingId);const We=Te.filter(Tt=>Tt.id!==Z),gt=le==null?void 0:le.areaId;return gt&&ct(We.filter(Tt=>Tt.areaId===gt)),We})},[ct]);b.useCallback(()=>{Qe({}),ve(Z=>{for(const Te of Z)Te.type==="pm2-logs"&&H.stopLogStreaming(Te.buildingId);return ct([]),[]})},[ct]),b.useEffect(()=>{if(!k){Pt(null);return}const Z=H.getAreaForAgent(k);if(!Z){Pt(null);return}Pt(Z.id),ve(Te=>{if(Te.filter(Tt=>Tt.areaId===Z.id).length>0)return Te;const We=mt.current.get(Z.id);if(!We||We.length===0)return Te;const gt=We.map(Tt=>({id:Tt.id,type:Tt.type,buildingId:Tt.buildingId,areaId:Z.id}));return[...Te,...gt]})},[k]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&Dt(le.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",Z),()=>window.removeEventListener("tide:open-bottom-terminal",Z)},[Dt]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&Dt(le.buildingId,"pm2-logs")};return window.addEventListener("tide:open-bottom-pm2-logs",Z),()=>window.removeEventListener("tide:open-bottom-pm2-logs",Z)},[Dt]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&Dt(le.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",Z),()=>window.removeEventListener("tide:open-bottom-database",Z)},[Dt]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&(le!=null&&le.type)&&(le!=null&&le.direction)&&(It.length===0?Dt(le.buildingId,le.type):Sn(le.buildingId,le.type,le.direction))};return window.addEventListener("tide:split-bottom-panel",Z),()=>window.removeEventListener("tide:split-bottom-panel",Z)},[It.length,Dt,Sn]),b.useEffect(()=>{he(Z=>Z.length===It.length?Z:It.length<=1?[1]:(It.length>Z.length,Array(It.length).fill(1)))},[It.length]);const cs=b.useCallback((Z,Te)=>{var $n;Z.preventDefault();const le=ot==="horizontal";Me.current={index:Te,startPos:le?Z.clientX:Z.clientY,startRatios:[...jt]},document.body.style.cursor=le?"col-resize":"row-resize",document.body.style.userSelect="none";const We=($n=Ye.current)==null?void 0:$n.querySelectorAll("iframe");We==null||We.forEach(ts=>ts.style.pointerEvents="none");const gt=Ye.current,Tt=gt?le?gt.offsetWidth:gt.offsetHeight:1,Cn=ts=>{const Ds=Me.current;if(!Ds||!gt)return;const Up=(le?ts.clientX:ts.clientY)-Ds.startPos,Hu=Ds.startRatios.reduce((Wp,qp)=>Wp+qp,0),Uu=Up/Tt*Hu,Oi=[...Ds.startRatios],Wu=.1*Hu;Oi[Te]=Math.max(Wu,Ds.startRatios[Te]+Uu),Oi[Te+1]=Math.max(Wu,Ds.startRatios[Te+1]-Uu),he(Oi)},tn=()=>{Me.current=null,document.body.style.cursor="",document.body.style.userSelect="",We==null||We.forEach(ts=>ts.style.pointerEvents=""),document.removeEventListener("mousemove",Cn),document.removeEventListener("mouseup",tn)};document.addEventListener("mousemove",Cn),document.addEventListener("mouseup",tn)},[ot,jt]),Ba=b.useRef(new Set);b.useEffect(()=>{const Z=new Set(me.filter(Te=>Te.type==="pm2-logs").map(Te=>Te.buildingId));for(const Te of Z)Ba.current.has(Te)||H.startLogStreaming(Te,200);Ba.current=Z},[me]);const Es=b.useRef(new Set);b.useEffect(()=>{var le;const Z=me.filter(We=>We.type==="terminal");for(const We of Z){const gt=E.get(We.buildingId);!!((le=gt==null?void 0:gt.terminalStatus)!=null&&le.url)?Es.current.add(We.buildingId):Es.current.has(We.buildingId)&&(Es.current.delete(We.buildingId),cn(We.id))}const Te=new Set(Z.map(We=>We.buildingId));for(const We of Es.current)Te.has(We)||Es.current.delete(We)},[me,E,cn]);const Us=b.useCallback(Z=>{Z.preventDefault(),ht.current={startY:Z.clientY,startH:lt};let Te=lt;const le=gt=>{if(!ht.current)return;const Tt=ht.current.startY-gt.clientY;Te=Math.max(120,Math.min(600,ht.current.startH+Tt)),rt(Te)},We=()=>{ht.current=null,document.removeEventListener("mousemove",le),document.removeEventListener("mouseup",We);try{localStorage.setItem("tide:bottom-terminal-height",String(Te))}catch{}};document.addEventListener("mousemove",le),document.addEventListener("mouseup",We)},[lt]),[Fa,Ss]=b.useState(!1),es=b.useRef(0),Mt=r&&C!==null,is=b.useRef([]),fn=b.useRef(-1),ur=b.useRef(!1),Ur=b.useRef(!1),_s=b.useRef(!1),Ms=b.useRef(null),[_i,wo]=b.useState(!1),[Wr,Il]=b.useState(!1),bs=b.useCallback(()=>{const Z=is.current,Te=fn.current;wo(Te>0),Il(Te>=0&&Te<Z.length-1)},[]),ja=b.useCallback(Z=>{const Te=is.current;if(Te.length===0)return;let le=fn.current+Z;for(;le>=0&&le<Te.length;){const We=Te[le];if(s.has(We)){ur.current=!0,fn.current=le,bs(),H.selectAgent(We);return}le+=Z}},[s,bs]),us=b.useCallback(()=>{ja(-1)},[ja]),Gn=b.useCallback(()=>{ja(1)},[ja]),qr=b.useCallback((Z,Te)=>{if(typeof window>"u")return;const le=window.history.state,gt={...typeof le=="object"&&le!==null?le:{},__guakeAgentNav:{agentId:Z}};Te==="replace"?window.history.replaceState(gt,"",window.location.href):window.history.pushState(gt,"",window.location.href)},[]),Ae=b.useCallback(()=>{je(Z=>{const Te=!Z;return Qa(ft.TERMINAL_FULLSCREEN,Te),Te})},[]),Je=n6({agents:s,selectedAgentId:k,isOpen:Mt,overviewPanelOpen:de,loadingHistory:((dr=W.current)==null?void 0:dr.historyLoader.fetchingHistory)??!1,hasModalOpen:!!(oe||Fe||Oe||c||d),outputRef:(($l=W.current)==null?void 0:$l.outputScrollRef)??{current:null}});b.useEffect(()=>{const Z=U.current;if(!Z||!Mt)return;const Te=We=>{We.button===3?(We.preventDefault(),We.stopPropagation(),us()):We.button===4&&(We.preventDefault(),We.stopPropagation(),Gn())},le=We=>{(We.button===3||We.button===4)&&We.preventDefault()};return Z.addEventListener("mouseup",Te),Z.addEventListener("mousedown",le),()=>{Z.removeEventListener("mouseup",Te),Z.removeEventListener("mousedown",le)}},[Mt,us,Gn]);const Ct=b.useCallback(Z=>{H.setLastSelectionViaDirectClick(!0),H.selectAgent(Z)},[]),en=typeof window<"u"&&window.innerWidth<=768&&de&&Mt,Ln=aR({gestureRef:((So=W.current)==null?void 0:So.outputScrollRef)??{current:null},agentListRef:be,enabled:en,onSelect:Ct});b.useEffect(()=>{Ne&&!pe&&(Ge(!0),ms.setEnabled(!0))},[Ne,pe]),b.useEffect(()=>{Mt||se(!1)},[Mt]),b.useEffect(()=>{var Te;if(!(Fe!=null&&Fe.isLive)||!Fe.command)return;const Z=((Te=W.current)==null?void 0:Te.getDedupedHistory())??[];for(const le of Z)if(le._bashCommand===Fe.command&&le._bashOutput){Ve({command:Fe.command,output:le._bashOutput,isLive:!1});return}},[Fe]);const $t=b.useCallback((Z,Te)=>{Ee({url:Z,name:Te})},[]),At=b.useCallback((Z,Te)=>{const le=_p(Z,C==null?void 0:C.cwd),We=le.line?{...Te||{},targetLine:le.line}:Te;H.setFileViewerPath(le.path,We,C==null?void 0:C.cwd)},[C==null?void 0:C.cwd]),Nn=b.useCallback((Z,Te)=>{Ve({command:Z,output:Te,isLive:Te==="Running..."})},[]),Cs=b.useCallback(Z=>{te(Z)},[]),Pn=b.useCallback(()=>{se(Z=>!Z)},[]),[Ws,Na]=b.useState(0),[oa,Bl]=b.useState(!1),Fu=b.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(Bl(!0),Na(kW),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{H.setMobileView("3d"),Bl(!1),Na(0)},SW))},[]),zu=b.useCallback(Z=>{oa||Na(Z)},[oa]);b.useEffect(()=>{Na(0),Bl(!1)},[k]),b.useEffect(()=>{if(!k){is.current=[],fn.current=-1,bs(),_s.current=!1,Ms.current=null;return}const Z=is.current;if(ur.current){ur.current=!1,bs();return}const Te=fn.current;if(Te>=0&&Z[Te]===k){bs();return}const le=Te<Z.length-1?Z.slice(0,Te+1):Z.slice();le.push(k),le.length>100&&le.shift(),is.current=le,fn.current=le.length-1,bs()},[k,bs]),b.useEffect(()=>{if(!(!Mt||!k)){if(!_s.current){qr(k,"replace"),_s.current=!0,Ms.current=k;return}if(Ur.current){Ur.current=!1,Ms.current=k;return}Ms.current!==k&&(qr(k,"push"),Ms.current=k)}},[Mt,k,qr]),b.useEffect(()=>{if(!Mt)return;const Z=Te=>{var Tt,Cn;const le=(Cn=(Tt=Te.state)==null?void 0:Tt.__guakeAgentNav)==null?void 0:Cn.agentId;if(!le||typeof le!="string"||!s.has(le)||le===v)return;Ur.current=!0,ur.current=!0;const We=is.current,gt=We.lastIndexOf(le);gt>=0?fn.current=gt:(We.push(le),fn.current=We.length-1),bs(),H.selectAgent(le)};return window.addEventListener("popstate",Z),()=>window.removeEventListener("popstate",Z)},[Mt,s,v,bs]),b.useEffect(()=>{Mt&&v&&H.clearUnseenForAgent(v)},[Mt,v]);const ko=b.useRef(null);b.useLayoutEffect(()=>{const Z=ko.current;Z!==null&&Z!==v&&H.getState().currentSnapshot&&H.setCurrentSnapshot(null),ko.current=v},[v]),b.useEffect(()=>{const Z=Te=>{if(Te.key==="`"&&!Te.ctrlKey&&!Te.altKey&&C){const le=Te.target;le.tagName!=="INPUT"&&le.tagName!=="TEXTAREA"&&(Te.preventDefault(),H.toggleTerminal())}};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[C]),b.useEffect(()=>{if(!Mt)return;const Z=Te=>{Te.altKey&&(Te.key!=="ArrowLeft"&&Te.key!=="ArrowRight"||(Te.key==="ArrowLeft"&&_i?(Te.preventDefault(),us()):Te.key==="ArrowRight"&&Wr&&(Te.preventDefault(),Gn())))};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[Mt,_i,Wr,us,Gn]),b.useEffect(()=>{const Z=Te=>{var le;Te.key==="Escape"&&(c?(Te.stopImmediatePropagation(),H.clearFileViewerPath()):d?(Te.stopImmediatePropagation(),H.closeContextModal()):Oe?(Te.stopImmediatePropagation(),te(null)):Fe?(Te.stopImmediatePropagation(),Ve(null)):oe?(Te.stopImmediatePropagation(),Ee(null)):(le=W.current)!=null&&le.search.searchMode&&(Te.stopImmediatePropagation(),W.current.search.closeSearch()))};return document.addEventListener("keydown",Z,!0),()=>document.removeEventListener("keydown",Z,!0)},[oe,Fe,Oe,c,d]);const $u=b.useRef(Mt),Mi=b.useRef(!1);b.useEffect(()=>{$u.current=Mt},[Mt]),b.useEffect(()=>{if(window.innerWidth<=768)return;const Te=gt=>{var $n;if(!(gt instanceof Element))return!1;const Tt=($n=U.current)==null?void 0:$n.contains(gt),Cn=gt.closest(".agent-bar"),tn=!!gt.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!!Tt||!!Cn||tn},le=gt=>{if(!$u.current){Mi.current=!1;return}if(eR("terminal")){Mi.current=!1;return}Mi.current=!Te(gt.target)},We=gt=>{Mi.current&&(Te(gt.target)||H.setTerminalOpen(!1),Mi.current=!1)};return document.addEventListener("mousedown",le,!0),document.addEventListener("mouseup",We,!0),()=>{document.removeEventListener("mousedown",le,!0),document.removeEventListener("mouseup",We,!0)}},[]),b.useEffect(()=>{const Z=()=>{document.hidden&&V.cleanup()};return document.addEventListener("visibilitychange",Z),()=>document.removeEventListener("visibilitychange",Z)},[V]),b.useEffect(()=>()=>V.cleanup(),[k,V]);const Vr=typeof window<"u"&&window.innerWidth<=768;if(!C)return Vr&&i==="terminal"&&a.size===0?o.jsx("div",{ref:U,className:`guake-terminal open ${xe?"fullscreen":""}`,style:{"--terminal-height":`${P}%`},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")})]})})})}):Vr&&i==="terminal"&&a.size>0?o.jsx("div",{ref:U,className:`guake-terminal open ${xe?"fullscreen":""}`,style:{"--terminal-height":`${P}%`},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(!k)return null;const Ta=Z=>{Z.preventDefault(),Z.stopPropagation(),es.current++,Z.dataTransfer.types.includes("Files")&&Ss(!0)},Fl=Z=>{Z.preventDefault(),Z.stopPropagation()},zl=Z=>{Z.preventDefault(),Z.stopPropagation(),es.current--,es.current===0&&Ss(!1)},Gr=async Z=>{var le,We;Z.preventDefault(),Z.stopPropagation(),es.current=0,Ss(!1);const Te=Z.dataTransfer.files;if(Te.length)for(const gt of Te){const Tt=await((le=W.current)==null?void 0:le.terminalInput.uploadFile(gt));Tt&&((We=W.current)==null||We.terminalInput.setAttachedFiles(Cn=>[...Cn,Tt]))}};return o.jsxs("div",{ref:U,className:`guake-terminal ${Mt?"open":"collapsed"} ${xe&&Mt?"fullscreen":""} ${Ne&&Mt?"with-debug-panel":""} ${it&&Mt?"with-git-panel":""} ${X&&Mt?"with-buildings-panel":""} ${ee&&Mt?"with-workflow-panel":""} ${N&&Mt?"with-tracking-board":""} ${de&&Mt?"with-overview-panel":""} ${Fa?"drag-over":""} ${Ws>0?"mobile-swipe-close-active":""} ${oa?"mobile-swipe-close-closing":""}`,style:{"--terminal-height":`${P}%`,"--mobile-swipe-close-offset":`${Ws}px`,"--guake-side-panel-width":`${G}px`,...z>0?{"--guake-mobile-overview-height":`${z}px`}:{}},onDragEnter:Ta,onDragOver:Fl,onDragLeave:zl,onDrop:Gr,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")})]}),!h&&Ne&&Mt&&k&&o.jsx(O6,{agentId:k,onClose:()=>_e(!1)}),!h&&it&&Mt&&k&&o.jsx(G6,{agentId:k,agents:s,onClose:()=>ce(!1),branchInfoMap:T,fetchRemote:M,fetchingDirs:R}),!h&&X&&Mt&&k&&o.jsx(rW,{agentId:k,onClose:()=>ke(!1)}),!h&&ee&&Mt&&k&&o.jsx(lW,{agentId:k,onClose:()=>Ie(!1)}),!h&&N&&Mt&&k&&o.jsxs("div",{className:"guake-tracking-board-panel",children:[o.jsxs("div",{className:"guake-tracking-board-header",children:[o.jsxs("div",{className:"guake-tracking-board-title",children:[o.jsx("span",{className:"guake-tracking-board-icon",children:"▥"}),o.jsx("span",{children:"Tracking Board"})]}),o.jsx("button",{type:"button",className:"guake-tracking-board-close",onClick:()=>H.setTrackingBoardVisible(!1),title:"Close tracking board",children:"✕"})]}),o.jsx("div",{className:"guake-tracking-board-body",children:o.jsx(vW,{activeAgentId:k,onSelectAgent:Z=>{H.setLastSelectionViaDirectClick(!0),H.selectAgent(Z)}})})]}),!h&&(Ne||it||X||ee||N)&&Mt&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:Z=>K(Z,"right")}),!h&&de&&Mt&&k&&o.jsx(d5,{activeAgentId:k,onClose:()=>re(!1),onSelectAgent:Z=>{H.setLastSelectionViaDirectClick(!0),H.selectAgent(Z)},agentListRef:be,twoFingerState:Ln}),!h&&de&&Mt&&k&&o.jsx("div",{className:"guake-side-panel-resize left",onMouseDown:Z=>K(Z,"left")}),!h&&de&&Mt&&k&&o.jsx("div",{className:"aop-resize-handle",onMouseDown:F,onTouchStart:$}),o.jsxs("div",{className:"guake-content",children:[o.jsx(C6,{selectedAgent:C,selectedAgentId:k,sortedAgents:Je.sortedAgents,swipeOffset:Je.swipeOffset,viewMode:fe,setViewMode:J,searchMode:((Hl=W.current)==null?void 0:Hl.search.searchMode)??!1,toggleSearch:((Yr=W.current)==null?void 0:Yr.search.toggleSearch)??(()=>{}),closeSearch:((la=W.current)==null?void 0:la.search.closeSearch)??(()=>{}),debugPanelOpen:Ne,setDebugPanelOpen:_e,debuggerEnabled:pe,setDebuggerEnabled:Ge,gitPanelOpen:it,setGitPanelOpen:ce,buildingsPanelOpen:X,setBuildingsPanelOpen:ke,workflowPanelOpen:ee,setWorkflowPanelOpen:Ie,hasWorkflow:He,trackingBoardVisible:N,setTrackingBoardVisible:Z=>H.setTrackingBoardVisible(Z),overviewPanelOpen:de,setOverviewPanelOpen:re,agentInfoOpen:$e,onToggleAgentInfo:Pn,isFullscreen:xe,onToggleFullscreen:Ae,onNavigateBack:us,onNavigateForward:Gn,canNavigateBack:_i,canNavigateForward:Wr,outputsLength:((Co=W.current)==null?void 0:Co.outputsLength)??0,setContextConfirm:ge,headerRef:Je.headerRef,onSaveSnapshot:h?void 0:e,isSnapshotView:h}),o.jsxs("div",{className:`guake-swipe-container ${Je.swipeAnimationClass}`,style:Je.swipeOffset!==0?{transform:`translateX(${Je.swipeOffset*40}%)`}:void 0,children:[Je.sortedAgents.length>1&&Je.swipeOffset!==0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`swipe-indicator left ${Je.swipeOffset>.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-icon",children:"←"}),o.jsx("span",{className:"indicator-name",children:(Kr=Je.nextAgent)==null?void 0:Kr.name})]}),o.jsxs("div",{className:`swipe-indicator right ${Je.swipeOffset<-.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-name",children:(Ea=Je.prevAgent)==null?void 0:Ea.name}),o.jsx("span",{className:"indicator-icon",children:"→"})]})]}),Je.sortedAgents.length>1&&Je.sortedAgents.length<=8&&Je.swipeOffset!==0&&o.jsx("div",{className:`swipe-dots ${Math.abs(Je.swipeOffset)>.1?"visible":""}`,children:Je.sortedAgents.map((Z,Te)=>o.jsx("div",{className:`swipe-dot ${Te===Je.currentAgentIndex?"active":""}`},Z.id))}),o.jsx(sW,{activeAgentId:k,activeAgent:C,paneRef:W,viewMode:fe,isOpen:Mt,isSnapshotView:h,currentSnapshot:f,onImageClick:$t,onFileClick:At,onBashClick:Nn,onViewMarkdown:Cs,keyboard:V,onSaveSnapshot:h?void 0:e,canSwipeClose:Vr&&i==="terminal"&&!((Ao=W.current)!=null&&Ao.search.searchMode)&&!((Di=W.current)!=null&&Di.historyLoader.fetchingHistory),onSwipeCloseOffsetChange:zu,onSwipeClose:Fu,hasModalOpen:!!(oe||Fe||Oe||c)})]}),o.jsxs("div",{className:"guake-agent-status-bar",children:[!h&&(C==null?void 0:C.isDetached)&&o.jsx(Zn,{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")]})}),(C==null?void 0:C.cwd)&&o.jsxs("span",{className:"guake-agent-cwd",title:C.cwd,children:["📁 ",C.cwd.split("/").filter(Boolean).slice(-2).join("/")||C.cwd]}),D&&D.map(({areaId:Z,areaName:Te,dir:le})=>{const We=T.get(le),gt=R.has(le);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${Te}: ${le}${We?` (${We.branch}${We.ahead?` ↑${We.ahead}`:""}${We.behind?` ↓${We.behind}`:""})`:""}`,onClick:()=>H.openFileExplorerForAreaFolder(Z,le),children:["📂 ",le.split("/").filter(Boolean).pop()||le,We&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",We.branch]}),We.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${We.ahead} ahead`,children:["↑",We.ahead]}),We.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${We.behind} behind`,children:["↓",We.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${gt?"fetching":""}`,title:"Git fetch",onClick:Tt=>{Tt.stopPropagation(),M(le)},children:gt?"⏳":"⇣"})]})]},`${Z}:${le}`)}),!h&&C&&(()=>{const Z=C.contextStats,Te=!!Z,le=Z?Z.totalTokens:C.contextUsed||0,We=Z?Z.contextWindow:C.contextLimit||2e5,gt=Z?Z.usedPercent:Math.round(le/We*100),Tt=Math.max(0,Math.min(100,gt)),Cn=Math.max(0,100-Tt),tn=Tt>=80?"#ff4a4a":Tt>=60?"#ff9e4a":Tt>=40?"#ffd700":"#4aff9e",$n=(le/1e3).toFixed(1),ts=(We/1e3).toFixed(1);return o.jsxs("span",{className:"guake-agent-context",onClick:()=>H.setContextModalAgentId(k),title:n(Te?"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,Tt)}%`,backgroundColor:tn}})}),o.jsxs("span",{className:"context-tokens",style:{color:tn},children:[$n,"k/",ts,"k"]}),o.jsxs("span",{className:"context-free",children:["(",n("terminal:context.percentFree",{percent:Cn}),")"]}),!Te&&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(Z=>{const Te=Vt.has(Z.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""} ${Z.hasUrl?"":"offline"}`,title:`${Te?"Hide":"Show"} terminal: ${Z.name}${Z.hasUrl?"":" (starting...)"}`,onClick:()=>{if(Te){const le=me.find(We=>We.buildingId===Z.id);le&&cn(le.id)}else Z.hasUrl||H.sendBuildingCommand(Z.id,"start"),Dt(Z.id,"terminal")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Vt.has(Z.id)||Nt({position:{x:le.clientX,y:le.clientY},buildingId:Z.id,type:"terminal"})},children:"💻"},Z.id)})}),I.length>0&&o.jsx("span",{className:"guake-status-terminals",children:I.map(Z=>{const Te=Vt.has(Z.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} logs: ${Z.name}`,onClick:()=>{if(Te){const le=me.find(We=>We.buildingId===Z.id);le&&cn(le.id)}else Dt(Z.id,"pm2-logs")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Vt.has(Z.id)||Nt({position:{x:le.clientX,y:le.clientY},buildingId:Z.id,type:"pm2-logs"})},children:"📜"},Z.id)})}),O.length>0&&o.jsx("span",{className:"guake-status-terminals",children:O.map(Z=>{const Te=Vt.has(Z.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} database: ${Z.name}`,onClick:()=>{if(Te){const le=me.find(We=>We.buildingId===Z.id);le&&cn(le.id)}else Dt(Z.id,"database")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Vt.has(Z.id)||Nt({position:{x:le.clientX,y:le.clientY},buildingId:Z.id,type:"database"})},children:"🗄️"},Z.id)})}),o.jsx(hW,{})]})]}),(()=>{const Z=[];return tt&&(Z.push({id:"open",label:"Open",icon:"⬇",onClick:()=>Dt(tt.buildingId,tt.type)}),It.length>0&&(Z.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Sn(tt.buildingId,tt.type,"horizontal")}),Z.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Sn(tt.buildingId,tt.type,"vertical")}))),o.jsx(or,{children:o.jsx(go,{isOpen:tt!==null,position:(tt==null?void 0:tt.position)||{x:0,y:0},worldPosition:{x:0,z:0},actions:Z,onClose:()=>Nt(null)})})})(),It.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:Us}),o.jsx("div",{ref:Ye,className:`guake-bottom-panels-container ${ot}`,style:{height:lt},onWheel:Z=>Z.stopPropagation(),children:It.map((Z,Te)=>{const le=E.get(Z.buildingId);if(!le)return null;const We=jt[Te]??1,gt=(()=>{var Tt;if(Z.type==="terminal")return(Tt=le.terminalStatus)!=null&&Tt.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>cn(Z.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(Kb,{terminalUrl:le.terminalStatus.url,visible:!0})]},Z.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name," (starting...)"]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>cn(Z.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..."})})]},Z.id);if(Z.type==="pm2-logs"){const Cn=Ue[Z.id]||"";return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",le.name]}),o.jsxs("div",{className:"guake-bottom-terminal-controls",children:[o.jsx("input",{type:"text",className:"guake-bottom-terminal-filter",value:Cn,onChange:tn=>{const $n=tn.target.value;Qe(ts=>{if(!$n.trim()){if(!(Z.id in ts))return ts;const Ds={...ts};return delete Ds[Z.id],Ds}return{...ts,[Z.id]:$n}})},placeholder:"Filter logs","aria-label":`Filter logs for ${le.name}`,spellCheck:!1}),o.jsx("select",{className:"guake-bottom-terminal-retention",value:ze===null?"unlimited":String(ze),onChange:tn=>{const $n=tn.target.value==="unlimited"?null:Number(tn.target.value);nt($n),BO($n)},"aria-label":`Max log retention for ${le.name}`,children:IO.map(tn=>o.jsx("option",{value:tn===null?"unlimited":String(tn),children:tn===null?"Unlimited":`${tn.toLocaleString()} lines`},tn===null?"unlimited":tn))}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>H.clearStreamingLogs(Z.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:()=>H.sendBuildingCommand(Z.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:()=>cn(Z.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(jW,{buildingId:Z.buildingId,filterText:Cn,maxRetention:ze})]},Z.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>cn(Z.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(QU,{building:le})]},Z.id)})();return Te>0?o.jsxs(Ce.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${ot}`,onMouseDown:Tt=>cs(Tt,Te-1)}),gt]},Z.id):gt})})]}),me.filter(Z=>Z.areaId!==zt&&Z.type==="terminal").map(Z=>{var le;const Te=E.get(Z.buildingId);return(le=Te==null?void 0:Te.terminalStatus)!=null&&le.url?o.jsx(Kb,{terminalUrl:Te.terminalStatus.url,visible:!1},Z.id):null})]}),Mt&&!xe&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:q,title:n("common:rightPanel.dragToResize")}),!(Mt&&xe)&&o.jsxs("div",{className:"guake-handle",onClick:()=>{Mt&&H.toggleTerminal()},onDoubleClick:()=>{Mt||H.toggleTerminal()},style:{top:Mt?`min(${P}%, calc(100vh - 72px))`:"0"},children:[o.jsx("span",{className:"guake-handle-icon",children:Mt?"▲":"▼"}),o.jsx("span",{className:"guake-handle-text",children:C.name})]}),oe&&o.jsx(N6,{url:oe.url,name:oe.name,onClose:()=>Ee(null)}),Fe&&o.jsx(T6,{state:Fe,onClose:()=>Ve(null)}),De&&o.jsx(E6,{action:De,selectedAgentId:k,subordinateCount:((Ul=C==null?void 0:C.subordinateIds)==null?void 0:Ul.length)||0,onClose:()=>ge(null),onClearHistory:((Ri=W.current)==null?void 0:Ri.historyLoader.clearHistory)??(()=>{})}),o.jsx(_6,{}),o.jsx(M6,{}),o.jsx(R6,{agent:C,isOpen:$e,onClose:()=>se(!1)}),!h&&o.jsx(D6,{agent:C,content:Oe,onClose:()=>te(null)})]})});function TW(t){return t.trim().replace(/^v/i,"")}function MA(t){const n=TW(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 EW(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 _W(t,e){const n=MA(t),s=MA(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 EW(n.prerelease,s.prerelease)}function MW(t,e){const n=_W(t,e);return n===null?"unknown":n<0?"behind":n>0?"ahead":"equal"}async function DW(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 RW(t,e,n={}){const s=await DW(t,n);return s?{currentVersion:e,latestVersion:s,relation:MW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const OW="tide-commander",tb="1.48.0";function LW(){const[t,e]=b.useState({currentVersion:tb,latestVersion:null,relation:"unknown",isChecking:!1}),n=b.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await RW(OW,tb);e({currentVersion:tb,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return b.useEffect(()=>{n()},[n]),{...t,refresh:n}}const PW=b.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:x,onDragOver:y,onDragEnter:v,onDragLeave:S,onDrop:C,onAgentClick:k,onAgentDoubleClick:N,onTouchStart:A,onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onHoverEnter:I,onHoverLeave:O,onItemRef:T}){const M=!a||r,R=b.useCallback(P=>{T(e.id,P)},[e.id,T]);return o.jsxs("div",{ref:R,className:`agent-bar-item ${i?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${d?"dragging":""} ${f?"drag-over":""} ${r?"touch-drag-enabled":""}`,draggable:M,onDragStart:P=>m(P,e),onDragEnd:x,onDragOver:P=>y(P,s),onDragEnter:P=>v(P,s),onDragLeave:S,onDrop:P=>C(P,s),onTouchStart:P=>A(P,e.id),onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onClick:P=>k(e,P),onDoubleClick:()=>N(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(Vn,{classId:e.class,size:"100%",className:"agent-bar-icon"}),o.jsx("span",{className:"agent-bar-status",style:{backgroundColor:Zb(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:Jb(e.lastActivity)},title:xp(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${n+1}`,children:["^",n+1]})]})}),IW=b.memo(function({onFocusAgent:e,onSpawnClick:n,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=pt(["common"]),c=Dl(),d=rr(),f=fx(),h=JO(),m=px(),x=Fr(),y=Aa(),v=Uj(),[S]=lx(),[C,k]=b.useState(!1);mj("AgentBar");const N=b.useRef(null),A=b.useRef(null),E=b.useRef(null),D=b.useRef(new Map);b.useEffect(()=>{{k(!1);return}},[x.experimental2DView]),b.useEffect(()=>{const ve=A.current;if(!ve)return;const Ue=Qe=>{ve.scrollWidth<=ve.clientWidth||(Qe.preventDefault(),Math.abs(Qe.deltaX)>Math.abs(Qe.deltaY)?ve.scrollLeft+=Qe.deltaX:ve.scrollLeft+=Qe.deltaY)};return ve.addEventListener("wheel",Ue,{passive:!1}),()=>ve.removeEventListener("wheel",Ue)},[]);const[_,I]=b.useState(null),[O,T]=b.useState(new Map),[M,R]=b.useState(null),[P,U]=b.useState(null),q=b.useRef(0),[z,F]=b.useState(null),$=b.useRef(null),V=b.useRef(null),G=b.useRef(null),B=b.useRef(null),Q=350,K=8,W=b.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),be=b.useMemo(()=>Array.from(c.values()).filter(ve=>{if(H.isAgentInArchivedArea(ve.id))return!1;if(S){const Ue=H.getAreaForAgent(ve.id);if(!vp((Ue==null?void 0:Ue.id)??null))return!1}return!0}).sort((ve,Ue)=>(ve.createdAt||0)-(Ue.createdAt||0)),[c,d,S]),{orderedAgents:fe,moveAgent:J}=kO(be),xe=fe,je=b.useMemo(()=>{const ve=new Map;for(const Ue of xe)ve.set(Ue.id,H.getAreaForAgent(Ue.id));return ve},[xe,d]),oe=b.useMemo(()=>{const ve=new Map;for(const Qe of xe){const ze=je.get(Qe.id)||null,nt=(ze==null?void 0:ze.id)||null;ve.has(nt)||ve.set(nt,{area:ze,agents:[]}),ve.get(nt).agents.push(Qe)}const Ue=Array.from(ve.values());return Ue.sort((Qe,ze)=>{var nt,ot;return!Qe.area&&ze.area?1:Qe.area&&!ze.area?-1:!Qe.area&&!ze.area?0:(((nt=Qe.area)==null?void 0:nt.name)||"").localeCompare(((ot=ze.area)==null?void 0:ot.name)||"")}),Ue},[xe,je]),Ee=b.useRef(e);Ee.current=e;const Fe=b.useRef(M);Fe.current=M;const Ve=b.useRef(xe);Ve.current=xe;const De=b.useRef(je);De.current=je;const ge=b.useRef(J);ge.current=J,b.useEffect(()=>{const ve=new Map(O);let Ue=!1;for(const Qe of xe){const ze=O.get(Qe.id);Qe.currentTool?(!ze||ze.tool!==Qe.currentTool)&&(ve.set(Qe.id,{tool:Qe.currentTool,key:Date.now()}),Ue=!0):ze&&setTimeout(()=>{T(nt=>{const ot=new Map(nt);return ot.delete(Qe.id),ot})},1500)}Ue&&T(ve)},[xe.map(ve=>ve.currentTool).join(",")]),b.useEffect(()=>{const ve=h;if(!ve)return;const Ue=D.current.get(ve),Qe=A.current;Ue&&Qe&&requestAnimationFrame(()=>{const ze=Ue.getBoundingClientRect(),nt=Qe.getBoundingClientRect(),st=ze.left-nt.left+Qe.scrollLeft+ze.width/2,lt=Qe.clientWidth;Qe.scrollTo({left:st-lt/2,behavior:"smooth"})})},[h]);const Oe=b.useCallback((ve,Ue)=>{if(G.current===ve.id){G.current=null,Ue.preventDefault(),Ue.stopPropagation();return}H.setLastSelectionViaDirectClick(!0),Ue.shiftKey?H.addToSelection(ve.id):H.selectAgent(ve.id),H.setTerminalOpen(!0)},[]),te=b.useCallback(ve=>{var Ue;(Ue=Ee.current)==null||Ue.call(Ee,ve.id),H.setTerminalOpen(!0)},[]),$e=b.useCallback(()=>I(null),[]),se=b.useCallback((ve,Ue)=>{Ue?D.current.set(ve,Ue):D.current.delete(ve)},[]),Ne=b.useCallback((ve,Ue)=>{R(Ue),F(Ue.id),ve.dataTransfer.effectAllowed="move",ve.dataTransfer.setData("text/plain",Ue.id),requestAnimationFrame(()=>{ve.target.classList.add("dragging")})},[]),_e=b.useCallback(ve=>{R(null),U(null),F(null),q.current=0,ve.target.classList.remove("dragging")},[]),pe=b.useCallback((ve,Ue)=>{ve.preventDefault();const Qe=Fe.current;if(Qe){const ze=De.current.get(Qe.id),nt=Ve.current[Ue],ot=nt?De.current.get(nt.id):null,st=(ze==null?void 0:ze.id)??null,lt=(ot==null?void 0:ot.id)??null;ve.dataTransfer.dropEffect=st===lt?"move":"none"}else ve.dataTransfer.dropEffect="move"},[]),Ge=b.useCallback((ve,Ue)=>{ve.preventDefault(),q.current++;const Qe=Fe.current;if(Qe){const ze=De.current.get(Qe.id),nt=Ve.current[Ue],ot=nt?De.current.get(nt.id):null,st=(ze==null?void 0:ze.id)??null,lt=(ot==null?void 0:ot.id)??null;U(st===lt?Ue:null)}else U(Ue)},[]),it=b.useCallback(ve=>{q.current--,q.current===0&&U(null)},[]),dt=b.useCallback((ve,Ue)=>{ve.preventDefault();const Qe=Fe.current;if(!Qe)return;const ze=Ve.current,nt=De.current,ot=ze.findIndex(st=>st.id===Qe.id);if(ot!==-1&&ot!==Ue){const st=nt.get(Qe.id),lt=ze[Ue],rt=lt?nt.get(lt.id):null,ht=(st==null?void 0:st.id)??null,jt=(rt==null?void 0:rt.id)??null;ht===jt&&ge.current(ot,Ue)}R(null),U(null),F(null),q.current=0},[]),ce=b.useCallback(()=>{$.current&&(clearTimeout($.current),$.current=null)},[]),X=b.useCallback(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),ne=b.useCallback((ve,Ue)=>{if(!W||ve.touches.length!==1)return;ce(),X(),F(null);const Qe=ve.touches[0];V.current={agentId:Ue,x:Qe.clientX,y:Qe.clientY},$.current=setTimeout(()=>{F(Ue),G.current=Ue,$.current=null},Q)},[ce,X,W]),ke=b.useCallback(ve=>{if(!W||ve.touches.length!==1)return;const Ue=V.current;if(!Ue||!$.current)return;const Qe=ve.touches[0],ze=Qe.clientX-Ue.x,nt=Qe.clientY-Ue.y;Math.sqrt(ze*ze+nt*nt)>K&&(ce(),V.current=null)},[ce,W]),ee=b.useCallback(()=>{ce(),V.current=null,Fe.current||F(null),X(),B.current=setTimeout(()=>{G.current=null,B.current=null},450)},[ce,X]);b.useEffect(()=>()=>{ce(),X()},[ce,X]);const ye=ve=>{const Ue=`common:status.${ve}`;return i(Ue,{defaultValue:i("common:status.unknown")})},{currentVersion:Ie,latestVersion:He,relation:ue,isChecking:de}=LW(),re=Ie;let me=0;return o.jsxs("div",{className:"agent-bar",ref:N,children:[o.jsxs("div",{className:"agent-bar-scroll",ref:A,children:[o.jsxs("div",{className:"agent-bar-version",title:He?`Tide Commander v${re} (npm: v${He})`:`Tide Commander v${re}`,children:[o.jsxs("span",{children:["v",re]}),ue==="behind"&&He?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${He}`,children:["npm v",He]}):ue==="ahead"&&He?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${He}`,children:["npm v",He]}):null,ue==="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)"})}):ue==="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)"})}):ue==="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")}):de?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)"})}),C&&o.jsx(Zn,{content:"Refresh 3D Scene (HMR changes pending)",position:"bottom",children:o.jsx("button",{className:"agent-bar-hmr-refresh",onClick:jj,children:"↻"})})]}),o.jsxs("div",{className:"agent-bar-list",ref:E,children:[o.jsx(Zn,{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(Zn,{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(Zn,{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(Zn,{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")})]})}),oe.map(ve=>{var ze,nt,ot,st,lt;const Ue=ve.agents,Qe=!ve.area;return o.jsxs("div",{className:`agent-bar-group ${Qe?"unassigned":""}`,style:{borderColor:((ze=ve.area)==null?void 0:ze.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:((nt=ve.area)==null?void 0:nt.color)||"#888"},children:((ot=ve.area)==null?void 0:ot.name)||i("common:agentBar.unassigned")})}),((st=ve.area)==null?void 0:st.directories)&&ve.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:ve.area.directories.map((rt,ht)=>o.jsxs("div",{className:"agent-bar-folder-item",onClick:jt=>{jt.stopPropagation(),H.openFileExplorer(rt)},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:rt}),o.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},ht))}),Ue.map(rt=>{const ht=me++,jt=xe.findIndex(he=>he.id===rt.id);return o.jsx(PW,{agent:rt,currentIndex:ht,agentIndex:jt,isTouchInput:W,isTouchDragEnabled:z===rt.id,isSelected:f.has(rt.id),hasUnseenOutput:v.has(rt.id),isDragging:(M==null?void 0:M.id)===rt.id,isDragOver:P===jt,customClasses:y,onDragStart:Ne,onDragEnd:_e,onDragOver:pe,onDragEnter:Ge,onDragLeave:it,onDrop:dt,onAgentClick:Oe,onAgentDoubleClick:te,onTouchStart:ne,onTouchMove:ke,onTouchEnd:ee,onTouchCancel:ee,onHoverEnter:I,onHoverLeave:$e,onItemRef:se},rt.id)})]},((lt=ve.area)==null?void 0:lt.id)||"unassigned")})]})]}),Array.from(O.entries()).map(([ve,Ue])=>{const Qe=D.current.get(ve);if(!Qe)return null;const ze=Qe.getBoundingClientRect(),nt=ls[Ue.tool]||ls.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:Ue.tool,style:{position:"fixed",left:ze.left+ze.width/2,bottom:window.innerHeight-ze.top+8},children:[o.jsx("span",{className:"agent-bar-tool-icon",children:nt}),o.jsx("span",{className:"agent-bar-tool-name",children:Ue.tool})]},`tool-${ve}-${Ue.key}`)}),_&&(()=>{const ve=H.getAreaForAgent(_.id),Ue=m.get(_.id),Qe=ir(_.class,y),ze=H.getAgentSupervisorHistory(_.id),nt=ze.length>0?ze[ze.length-1]:void 0,ot=Date.now()-(_.createdAt||Date.now()),st=Math.floor(ot/6e4),lt=Math.floor(st/60),rt=lt>0?`${lt}h ${st%60}m`:`${st}m`,ht=tt=>tt>=1e6?`${(tt/1e6).toFixed(1)}M`:tt>=1e3?`${(tt/1e3).toFixed(1)}K`:tt.toString(),jt=_.contextLimit>0?Math.round(_.contextUsed/_.contextLimit*100):0,he=tt=>{switch(tt){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Me=D.current.get(_.id),Ye={};if(Me){const tt=Me.getBoundingClientRect();Ye.position="fixed",Ye.left=tt.left+tt.width/2,Ye.bottom=window.innerHeight-tt.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:o.jsx(Vn,{classId:_.class,size:18})}),o.jsxs("span",{className:"agent-bar-tooltip-name",children:[o.jsx("img",{src:_.provider==="codex"?"/assets/codex.png":_.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:_.provider,className:"agent-bar-provider-icon",title:_.provider==="codex"?"Codex Agent":_.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),_.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Zb(_.status)},children:ye(_.status)})]}),o.jsxs("div",{className:"agent-bar-tooltip-info",children:[o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.class"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.class," — ",Qe.description]})]}),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:_.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:rt})]}),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:[ht(_.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:jt>80?"#ff4a4a":jt>60?"#ff9e4a":void 0},children:[ht(_.contextUsed)," / ",ht(_.contextLimit)," (",jt,"%)"]})]}),_.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:[ls[_.currentTool]||ls.default," ",_.currentTool]})]}),_.taskLabel&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsx("span",{className:"agent-bar-tooltip-label",children:"📋 Task:"}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:_.taskLabel})]}),_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.task"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.currentTask.substring(0,150),_.currentTask.length>150?"...":""]})]}),_.lastAssignedTask&&!_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.assignedTask"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[_.lastAssignedTask.substring(0,200),_.lastAssignedTask.length>200?"...":""]})]}),Ue&&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:[Ue.text.substring(0,300),Ue.text.length>300?"...":""]})]}),nt&&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:he(nt.analysis.progress)},children:nt.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:nt.analysis.statusDescription})]}),nt.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:[nt.analysis.recentWorkSummary.substring(0,300),nt.analysis.recentWorkSummary.length>300?"...":""]})]}),nt.analysis.concerns&&nt.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:nt.analysis.concerns.join("; ")})]})]})]})]})})()]})});function BW({activeTool:t,onExit:e}){const{t:n}=pt(["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 FW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},nb=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),zW=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"}},$W=b.memo(function({agent:e,screenPos:n,onClose:s}){const{t:a}=pt(["common"]),r=Aa(),i=H.getAreaForAgent(e.id),c=H.getState().lastPrompts.get(e.id),d=ir(e.class,r),f=H.getAgentSupervisorHistory(e.id),h=f.length>0?f[f.length-1]:void 0,m=Date.now()-(e.createdAt||Date.now()),x=Math.floor(m/6e4),y=Math.floor(x/60),v=y>0?`${y}h ${x%60}m`:`${x}m`,S=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,C=b.useMemo(()=>{let A=n.x-150,E=n.y-320-10;return typeof window<"u"&&(A<10?A=10:A+300>window.innerWidth-10&&(A=window.innerWidth-300-10),E<10&&(E=n.y+10)),{position:"fixed",left:A,top:E,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[n.x,n.y]);return o.jsxs("div",{className:"agent-hover-popup",style:C,onMouseLeave:s,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:o.jsx(Vn,{agent:e,size:18})}),o.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Zb(e.status)},children:a(FW[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:v})]}),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:[nb(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:S>80?"#ff4a4a":S>60?"#ff9e4a":void 0},children:[nb(e.contextUsed)," / ",nb(e.contextLimit)," (",S,"%)"]})]}),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:[ls[e.currentTool]||ls.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:zW(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 DA(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 RA(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 OA={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 HW(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:OA[c]&&(a=OA[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 UW=b.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var F,$,V,G,B,Q,K,W,be,fe,J,xe,je,oe,Ee,Fe,Ve,De,ge,Oe;const{t:c}=pt(["terminal","common"]),[d,f]=b.useState(!1),[h,m]=b.useState(null),[x,y]=b.useState(!1),v=b.useRef(null),S=b.useRef(h);S.current=h;const{buildingLogs:C}=ws(),k=H.getBuildingLogs(e.id),N=(F=e.pm2)==null?void 0:F.enabled,A=($=e.docker)==null?void 0:$.enabled,E=b.useRef(null),D=b.useRef(null),_=b.useCallback(te=>{te.preventDefault();const $e=S.current?S.current.x:0,se=S.current?S.current.y:0;v.current={mouseX:te.clientX,mouseY:te.clientY,popupX:$e,popupY:se},y(!0),E.current=Ne=>{if(!v.current)return;const _e=Ne.clientX-v.current.mouseX,pe=Ne.clientY-v.current.mouseY;m({x:v.current.popupX+_e,y:v.current.popupY+pe})},D.current=()=>{y(!1),v.current=null,E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",E.current),document.addEventListener("mouseup",D.current)},[]);b.useEffect(()=>()=>{E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const I=te=>{if(te==="logs"){if((N||A)&&r){r();return}H.sendBuildingCommand(e.id,te),f(!0)}else H.sendBuildingCommand(e.id,te)},O=(te,$e)=>{if(te){const se=`http://localhost:${te}`;$e&&i?i(se):window.open(se,"_blank")}},T=((V=e.pm2Status)==null?void 0:V.ports)||[],M=((B=(G=e.dockerStatus)==null?void 0:G.ports)==null?void 0:B.map(te=>te.host))||[],R=N?T:A?M:[],P=N?!!((Q=e.pm2)!=null&&Q.script):A?!!((K=e.docker)!=null&&K.image)||((W=e.docker)==null?void 0:W.mode)==="compose"||((be=e.docker)==null?void 0:be.mode)==="existing":!!((fe=e.commands)!=null&&fe.start),U=N?!!((J=e.pm2)!=null&&J.script):A?!0:!!((xe=e.commands)!=null&&xe.stop),q=N?!!((je=e.pm2)!=null&&je.script):A?!0:!!((oe=e.commands)!=null&&oe.restart),z=b.useMemo(()=>{const $e=d?400:250;let se=n.x+20,Ne=n.y-80;return typeof window<"u"&&!h&&(n.x+20+280>window.innerWidth&&(se=n.x-280-20),n.y-80<0?Ne=10:n.y-80+$e>window.innerHeight&&(Ne=window.innerHeight-$e-10)),{position:"fixed",left:se+((h==null?void 0:h.x)||0),top:Ne+((h==null?void 0:h.y)||0),zIndex:1e3,cursor:x?"grabbing":void 0}},[n.x,n.y,d,h,x]);return o.jsxs("div",{className:"building-action-popup",style:z,onClick:te=>te.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header ${x?"dragging":""}`,onMouseDown:_,children:[o.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&o.jsx("span",{className:"building-popup-ports",children:R.map(te=>o.jsxs("a",{href:`http://localhost:${te}`,className:"building-popup-port-link",onClick:$e=>{$e.preventDefault(),$e.stopPropagation(),O(te,$e.altKey)},onMouseDown:$e=>$e.stopPropagation(),title:`Open http://localhost:${te} (Alt+Click for modal)`,children:[":",te]},te))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:mb[e.status]},children:e.status}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),N&&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:[((Ee=e.pm2Status.cpu)==null?void 0:Ee.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:DA(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:RA(e.pm2Status.uptime)})]})]}),A&&e.dockerStatus&&o.jsxs("div",{className:"building-popup-metrics",children:[o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"ID"}),o.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"CPU"}),o.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:DA(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:RA(e.dockerStatus.startedAt)})]})]}),A&&((Fe=e.dockerStatus)==null?void 0:Fe.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((te,$e)=>o.jsxs("span",{className:"service-item",title:`${te.name}: ${te.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:te.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:te.name})]},$e))}),(e.lastError||N&&((Ve=e.pm2Status)==null?void 0:Ve.status)==="errored"||A&&((De=e.dockerStatus)==null?void 0:De.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),N&&((ge=e.pm2Status)==null?void 0:ge.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),A&&((Oe=e.dockerStatus)==null?void 0:Oe.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:!P||e.status==="running"||e.status==="starting",title:c(P?"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:!U||e.status==="stopped"||e.status==="stopping",title:c(U?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:buildingAction.stop")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>I("restart"),disabled:!q,title:c(q?"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:te=>O(R[0],te.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(te=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:$e=>O(te,$e.altKey),title:`Open http://localhost:${te} (Alt+Click for modal)`,children:[":",te]},te))]})]}),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:()=>H.clearBuildingLogs(e.id),children:c("terminal:logs.clear")})]}),o.jsx("div",{className:"logs-content",children:k.slice(-50).map((te,$e)=>o.jsx("pre",{children:HW(te)},$e))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function WW(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 qW(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 VW=b.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){const{t:c}=pt(["terminal","common"]),[d,f]=b.useState(null),[h,m]=b.useState(!1),x=b.useRef(null),y=b.useRef(d);y.current=d;const{buildings:v}=ws(),C=(e.subordinateBuildingIds||[]).map(T=>v.get(T)).filter(T=>T!==void 0),k=b.useRef(null),N=b.useRef(null),A=b.useCallback(T=>{T.preventDefault();const M=y.current?y.current.x:0,R=y.current?y.current.y:0;x.current={mouseX:T.clientX,mouseY:T.clientY,popupX:M,popupY:R},m(!0),k.current=P=>{if(!x.current)return;const U=P.clientX-x.current.mouseX,q=P.clientY-x.current.mouseY;f({x:x.current.popupX+U,y:x.current.popupY+q})},N.current=()=>{m(!1),x.current=null,k.current&&document.removeEventListener("mousemove",k.current),N.current&&document.removeEventListener("mouseup",N.current)},document.addEventListener("mousemove",k.current),document.addEventListener("mouseup",N.current)},[]);b.useEffect(()=>()=>{k.current&&document.removeEventListener("mousemove",k.current),N.current&&document.removeEventListener("mouseup",N.current)},[]);const E=T=>{H.sendBossBuildingCommand(e.id,T)},D=C.reduce((T,M)=>(T[M.status]=(T[M.status]||0)+1,T),{}),_=C.some(T=>{var M;return(M=T.pm2)==null?void 0:M.enabled}),I=(T,M)=>{const R=`http://localhost:${T}`;M&&i?i(R):window.open(R,"_blank")},O=b.useMemo(()=>{let R=n.x+20,P=n.y-80;return typeof window<"u"&&!d&&(n.x+20+340>window.innerWidth&&(R=n.x-340-20),n.y-80<0?P=10:n.y-80+350>window.innerHeight&&(P=window.innerHeight-350-10)),{position:"fixed",left:R+((d==null?void 0:d.x)||0),top:P+((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:T=>T.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header boss-header ${h?"dragging":""}`,onMouseDown:A,children:[o.jsx("span",{className:"boss-icon",children:"👑"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"subordinate-count",children:c("terminal:building.unitsCount",{count:C.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),o.jsxs("div",{className:"boss-status-overview",children:[Object.entries(D).map(([T,M])=>o.jsxs("span",{className:"status-badge",style:{backgroundColor:mb[T]||"#666"},children:[M," ",T]},T)),C.length===0&&o.jsx("span",{className:"no-subordinates",children:c("terminal:building.noSubordinates")})]}),C.length>0&&o.jsx("div",{className:"subordinate-list",children:C.map(T=>{var M,R,P;return o.jsxs("div",{className:"subordinate-item",children:[o.jsx("span",{className:"sub-status-dot",style:{backgroundColor:mb[T.status]}}),o.jsx("span",{className:"sub-name",children:T.name}),((M=T.pm2Status)==null?void 0:M.ports)&&T.pm2Status.ports.length>0&&o.jsx("span",{className:"sub-port",children:T.pm2Status.ports.map(U=>o.jsxs("a",{href:`http://localhost:${U}`,className:"building-popup-port-link",onClick:q=>{q.preventDefault(),q.stopPropagation(),I(U,q.altKey)},title:`Open http://localhost:${U} (Alt+Click for modal)`,children:[":",U]},U))}),T.pm2Status&&o.jsxs("span",{className:"sub-metrics",children:[(R=T.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",WW(T.pm2Status.memory||0)]}),((P=T.pm2Status)==null?void 0:P.uptime)&&o.jsx("span",{className:"sub-uptime",children:qW(T.pm2Status.uptime)})]},T.id)})}),o.jsxs("div",{className:"building-popup-actions boss-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>E("start_all"),disabled:C.length===0,title:c("terminal:building.startAllSubs"),children:[o.jsx("span",{className:"icon",children:"▶"}),c("terminal:building.startAll")]}),o.jsxs("button",{className:"action-btn stop",onClick:()=>E("stop_all"),disabled:C.length===0,title:c("terminal:building.stopAllSubs"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:building.stopAll")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>E("restart_all"),disabled:C.length===0,title:c("terminal:building.restartAllSubs"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:building.restartAll")]}),_&&o.jsxs("button",{className:"action-btn logs",onClick:r,title:c("terminal:building.viewUnifiedLogs"),children:[o.jsx("span",{className:"icon",children:"📄"}),c("terminal:building.logs")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:building.fullSettings")})]})}),GW=b.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenDatabasePanel:r}){var D;const{t:i}=pt(["terminal","common"]),[c,d]=b.useState(null),[f,h]=b.useState(!1),m=b.useRef(null),x=b.useRef(c);x.current=c;const y=xx(e.id),v=((D=e.database)==null?void 0:D.connections)??[],S=b.useRef(null),C=b.useRef(null),k=b.useCallback(_=>{_.preventDefault();const I=x.current?x.current.x:0,O=x.current?x.current.y:0;m.current={mouseX:_.clientX,mouseY:_.clientY,popupX:I,popupY:O},h(!0),S.current=T=>{if(!m.current)return;const M=T.clientX-m.current.mouseX,R=T.clientY-m.current.mouseY;d({x:m.current.popupX+M,y:m.current.popupY+R})},C.current=()=>{h(!1),m.current=null,S.current&&document.removeEventListener("mousemove",S.current),C.current&&document.removeEventListener("mouseup",C.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",C.current)},[]);b.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),C.current&&document.removeEventListener("mouseup",C.current)},[]);const N=_=>{H.testDatabaseConnection(e.id,_)},A=_=>y.connectionStatus.get(_),E=b.useMemo(()=>{let O=n.x+20,T=n.y-80;return typeof window<"u"&&!c&&(n.x+20+320>window.innerWidth&&(O=n.x-320-20),n.y-80<0?T=10:n.y-80+300>window.innerHeight&&(T=window.innerHeight-300-10)),{position:"fixed",left:O+((c==null?void 0:c.x)||0),top:T+((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:E,onClick:_=>_.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header database-header ${f?"dragging":""}`,onMouseDown:k,children:[o.jsx("span",{className:"database-icon",children:"🗄️"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"connection-count",children:i("terminal:building.connCount",{count:v.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),v.length>0?o.jsx("div",{className:"database-connection-list",children:v.map(_=>{var O;const I=A(_.id);return o.jsxs("div",{className:"database-connection-item",children:[o.jsx("span",{className:"conn-engine",children:((O=BL[_.engine])==null?void 0:O.icon)??"🗄️"}),o.jsx("span",{className:"conn-name",children:_.name}),o.jsx("span",{className:"conn-host",children:_.engine==="sqlite"?_.filepath||_.database||":memory:":`${_.host}:${_.port}`}),I&&o.jsx("span",{className:`conn-status ${I.connected?"connected":"disconnected"}`,children:I.connected?"●":"○"}),o.jsx("button",{className:"conn-test-btn",onClick:()=>N(_.id),title:i("terminal:building.testConnection"),children:"↻"})]},_.id)})}):o.jsxs("div",{className:"database-no-connections",children:[o.jsx("p",{children:i("terminal:building.noConnections")}),o.jsx("p",{className:"hint",children:i("terminal:building.clickSettingsToAdd")})]}),o.jsxs("div",{className:"building-popup-actions database-actions",children:[o.jsxs("button",{className:"action-btn query",onClick:r,disabled:v.length===0,title:i("terminal:building.openDbExplorer"),children:[o.jsx("span",{className:"icon",children:"⌨"}),i("terminal:building.query")]}),o.jsxs("button",{className:"action-btn test-all",onClick:()=>v.forEach(_=>N(_.id)),disabled:v.length===0,title:i("terminal:building.testAllConnections"),children:[o.jsx("span",{className:"icon",children:"↻"}),i("terminal:building.testAll")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:i("common:buttons.settings")})]})});function YW({visible:t=!0,position:e="top-right"}){const[n,s]=b.useState(0),[a,r]=b.useState([]),[i,c]=b.useState(null),[d,f]=b.useState([]),[h,m]=b.useState(null),[x,y]=b.useState(null),[v,S]=b.useState(!1),[C,k]=b.useState("fps"),[N,A]=b.useState(null),[E,D]=b.useState(null),[_,I]=b.useState(null),[O,T]=b.useState(typeof window<"u"?window.innerWidth:1024),[M,R]=b.useState(null);b.useEffect(()=>{const J=()=>T(window.innerWidth);return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]);const P=kp(),U=b.useMemo(()=>{const J=P.filter(je=>je.memoryUsageMB!==void 0&&je.memoryUsageMB>0);return{totalMB:J.reduce((je,oe)=>je+(oe.memoryUsageMB||0),0),agentCount:J.length,agents:J.map(je=>({name:je.name,memoryMB:je.memoryUsageMB||0,status:je.status})).sort((je,oe)=>oe.memoryMB-je.memoryMB)}},[P]),q=b.useRef([]),z=b.useRef(null);if(b.useEffect(()=>{q.current=d},[d]),b.useEffect(()=>{z.current=h},[h]),b.useEffect(()=>{if(!t)return;const J=async()=>{try{const je=await Lt(_t("/api/perf"));if(je.ok){const oe=await je.json();D(oe)}}catch{}};J();const xe=setInterval(J,v?3e3:1e4);return()=>clearInterval(xe)},[t,v]),b.useEffect(()=>{if(!t)return;const J=Dc.getUsage();J&&M===null&&R(J.usedMB);const xe=setInterval(()=>{var $e,se;Xd.update();const je=Xd.getStats();s(je.current),r(Ne=>[...Ne,je.current].slice(-60));const oe=Dc.getUsage();oe&&c(oe);const Ee=window.__tideScene;if(Ee){const Ne=($e=Ee.getMemoryDiagnostics)==null?void 0:$e.call(Ee);Ne!=null&&Ne.threeJs&&m(Ne.threeJs);const _e=Ee.renderer;if((se=_e==null?void 0:_e.info)!=null&&se.memory){const pe=_e.info.memory.textures||0,Ge=Math.round(pe*1);I({count:pe,estimatedMB:Ge})}}const Fe=document.getElementsByTagName("*"),Ve=document.getElementsByTagName("canvas"),De=document.getElementsByTagName("img"),ge=document.getElementsByTagName("video");let Oe=0;for(let Ne=0;Ne<Math.min(Fe.length,500);Ne++){const _e=Fe[Ne];_e.onclick&&Oe++,_e.onmousedown&&Oe++,_e.onkeydown&&Oe++}Oe+=10,A({nodeCount:Fe.length,listenerCount:Oe,canvasCount:Ve.length,imageCount:De.length,videoCount:ge.length}),oe&&f(Ne=>{const _e=z.current,pe={timestamp:Date.now(),heapMB:oe.usedMB,geometries:(_e==null?void 0:_e.geometries)??0,textures:(_e==null?void 0:_e.textures)??0};return[...Ne,pe].slice(-120)});const te=q.current;if(te.length>=10){const Ne=te[0],_e=te[te.length-1],pe=(_e.timestamp-Ne.timestamp)/1e3/60;pe>.1&&y((_e.heapMB-Ne.heapMB)/pe)}},1e3);return()=>{clearInterval(xe)}},[t,M]),!t)return null;const F=J=>{const xe=Math.floor(J/3600),je=Math.floor(J%3600/60),oe=J%60;return xe>0?`${xe}h ${je}m`:je>0?`${je}m ${oe}s`:`${oe}s`},$=J=>J>=55?"#4aff9e":J>=30?"#ffcc00":"#ff4a4a",V=(J,xe)=>{const je=J/xe;return je<.5?"#4aff9e":je<.8?"#ffcc00":"#ff4a4a"},G=J=>J===null?"#888":J<1?"#4aff9e":J<5?"#ffcc00":"#ff4a4a",B=Xd.getStats(),K=O<=768?80:10,W={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:K,left:10},"bottom-right":{bottom:K,right:10}},be=M&&i?i.usedMB-M:0,fe=J=>({padding:"2px 8px",fontSize:"9px",border:"none",background:C===J?"rgba(74, 158, 255, 0.4)":"rgba(255, 255, 255, 0.1)",color:C===J?"#4a9eff":"#888",borderRadius:"3px",cursor:"pointer"});return o.jsxs("div",{style:{position:"fixed",...W[e],zIndex:99999,fontFamily:"monospace",fontSize:"11px",background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",padding:"6px 10px",color:"#fff",userSelect:"none",minWidth:v?"260px":"120px",maxWidth:"calc(100vw - 20px)",maxHeight:v?"calc(100vh - 100px)":"auto",overflowY:v?"auto":"visible",transition:"all 0.2s ease"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:()=>S(!v),children:[o.jsx("span",{style:{color:$(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"})]}),x!==null&&Math.abs(x)>.5&&o.jsxs("span",{style:{color:G(x),fontSize:"10px",marginLeft:"4px"},children:[x>0?"+":"",x.toFixed(1),"/m"]}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:"#ff9e4a",fontWeight:"bold"},children:E.process.rssMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"SRV"})]}),o.jsx("span",{style:{color:"#444",marginLeft:"auto",fontSize:"10px"},children:v?"▼":"▶"})]}),v&&o.jsxs("div",{style:{marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px"},children:[o.jsxs("div",{style:{display:"flex",gap:"4px",marginBottom:"8px",flexWrap:"wrap"},children:[o.jsx("button",{style:fe("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:fe("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:fe("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:fe("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:fe("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:fe("http"),onClick:()=>k("http"),children:"HTTP"})]}),C==="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:$(B.current)},children:B.current}),o.jsx("span",{style:{color:"#888"},children:"Min:"}),o.jsx("span",{style:{color:$(B.min)},children:B.min}),o.jsx("span",{style:{color:"#888"},children:"Max:"}),o.jsx("span",{style:{color:$(B.max)},children:B.max}),o.jsx("span",{style:{color:"#888"},children:"Avg:"}),o.jsx("span",{style:{color:$(B.avg)},children:B.avg})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"60s History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"30px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:a.slice(-60).map((J,xe)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,J/60*100)}%`,background:$(J),opacity:.8}},xe))})]})]}),C==="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(x)},children:x!==null?`${x.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((J,xe)=>{const je=Math.min(...d.map(Ve=>Ve.heapMB)),Ee=Math.max(...d.map(Ve=>Ve.heapMB))-je||1,Fe=(J.heapMB-je)/Ee*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,Fe)}%`,background:J.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${J.heapMB}MB`},xe)})})]}),U.agentCount>0&&o.jsxs("div",{style:{marginTop:"8px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:["Agent Memory (",U.agentCount,"):"]}),o.jsxs("div",{style:{fontSize:"10px"},children:[o.jsxs("div",{style:{color:"#4aff9e",fontWeight:"bold",marginBottom:"2px"},children:["Total: ",U.totalMB,"MB"]}),o.jsx("div",{style:{maxHeight:"50px",overflowY:"auto"},children:U.agents.slice(0,4).map((J,xe)=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":"#666",maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB,"MB"]})]},xe))})]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[i.usedMB," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsxs("span",{style:{color:"#9e4aff"},children:["DOM (",(N==null?void 0:N.nodeCount.toLocaleString())??0," nodes)"]}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",i.usedMB+((_==null?void 0:_.estimatedMB)??0)+Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)," MB"]})]})]})]})]}),C==="threejs"&&o.jsx("div",{children:h?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Geometries:"}),o.jsx("span",{style:{color:"#4aff9e"},children:h.geometries}),o.jsx("span",{style:{color:"#888"},children:"Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:h.textures}),o.jsx("span",{style:{color:"#888"},children:"Programs:"}),o.jsx("span",{style:{color:"#9e4aff"},children:h.programs})]}),d.length>1&&o.jsxs("div",{children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"Resource History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"40px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:d.slice(-60).map((J,xe)=>{const je=Math.max(...d.map(oe=>oe.textures))||1;return o.jsx("div",{style:{width:"3px",height:`${J.textures/je*100}%`,background:"#ff9e4a",opacity:.8},title:`${J.textures} textures`},xe)})})]}),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."]})}),C==="dom"&&o.jsx("div",{children:N?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:N.nodeCount>5e3?"#ff4a4a":N.nodeCount>2e3?"#ffcc00":"#4aff9e"},children:N.nodeCount.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Canvases:"}),o.jsx("span",{style:{color:"#4a9eff"},children:N.canvasCount}),o.jsx("span",{style:{color:"#888"},children:"Images:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:N.imageCount}),o.jsx("span",{style:{color:"#888"},children:"Videos:"}),o.jsx("span",{style:{color:"#9e4aff"},children:N.videoCount})]}),_&&o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("span",{style:{color:"#888"},children:"GPU Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:_.count}),o.jsx("span",{style:{color:"#888"},children:"Est. VRAM:"}),o.jsxs("span",{style:{color:_.estimatedMB>100?"#ff4a4a":"#4aff9e"},children:["~",_.estimatedMB," MB"]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[(i==null?void 0:i.usedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#9e4aff"},children:"DOM (~0.5KB/node)"}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(N.nodeCount*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",((i==null?void 0:i.usedMB)??0)+((_==null?void 0:_.estimatedMB)??0)+Math.round(N.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..."})}),C==="server"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Uptime:"}),o.jsx("span",{style:{color:"#4aff9e"},children:F(E.uptime)}),o.jsx("span",{style:{color:"#888"},children:"Heap Used:"}),o.jsxs("span",{style:{color:E.process.heapUsedMB>500?"#ff4a4a":"#4aff9e"},children:[E.process.heapUsedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Heap Total:"}),o.jsxs("span",{children:[E.process.heapTotalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"RSS:"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.rssMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"External:"}),o.jsxs("span",{children:[E.process.externalMB," MB"]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"System:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Load Avg:"}),o.jsx("span",{style:{color:E.system.loadAvg[0]>E.system.cpuCount?"#ff4a4a":"#4aff9e"},children:E.system.loadAvg.join(" ")}),o.jsx("span",{style:{color:"#888"},children:"CPUs:"}),o.jsx("span",{children:E.system.cpuCount}),o.jsx("span",{style:{color:"#888"},children:"Sys Memory:"}),o.jsxs("span",{children:[E.system.totalMemMB-E.system.freeMemMB," / ",E.system.totalMemMB," MB"]})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"WebSocket:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Clients:"}),o.jsx("span",{style:{color:"#4a9eff"},children:E.websocket.clients}),o.jsx("span",{style:{color:"#888"},children:"Sent:"}),o.jsx("span",{children:E.websocket.messagesSent.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Received:"}),o.jsx("span",{children:E.websocket.messagesReceived.toLocaleString()})]})]}),E.agents.total>0&&o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:["Agents (",E.agents.working,"w / ",E.agents.idle,"i / ",E.agents.total,"t):"]}),o.jsx("div",{style:{maxHeight:"80px",overflowY:"auto",fontSize:"10px"},children:E.agents.processes.map(J=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":J.status==="idle"?"#888":"#ff4a4a",maxWidth:"100px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB!=null?`${J.memoryMB}MB`:"—",J.pid?` (${J.pid})`:""]})]},J.id))})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading server metrics..."})}),C==="http"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Req/sec (30s):"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.http.reqPerSec}),o.jsx("span",{style:{color:"#888"},children:"Avg Latency:"}),o.jsxs("span",{style:{color:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e"},children:[E.http.avgLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Max Latency:"}),o.jsxs("span",{style:{color:E.http.maxLatencyMs>500?"#ff4a4a":E.http.maxLatencyMs>200?"#ffcc00":"#4aff9e"},children:[E.http.maxLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Recent Reqs:"}),o.jsx("span",{children:E.http.recentRequests})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Avg Latency:"}),o.jsx("div",{style:{height:"8px",background:"rgba(255,255,255,0.1)",borderRadius:"4px",overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:`${Math.min(100,E.http.avgLatencyMs/500*100)}%`,background:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e",transition:"width 0.3s ease"}})}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"8px",color:"#444",marginTop:"2px"},children:[o.jsx("span",{children:"0ms"}),o.jsx("span",{children:"500ms"})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Server Process:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"CPU (user):"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.cpuUser," ms"]}),o.jsx("span",{style:{color:"#888"},children:"CPU (system):"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:[E.process.cpuSystem," ms"]}),o.jsx("span",{style:{color:"#888"},children:"WS Clients:"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.websocket.clients})]})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading HTTP metrics..."})}),o.jsxs("div",{style:{display:"flex",gap:"4px",marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px",flexWrap:"wrap"},children:[o.jsx("button",{onClick:J=>{J.stopPropagation();const xe=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&xe.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: ${x!==null?`${x.toFixed(2)} MB/min`:"N/A"}`),h&&xe.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),U.agentCount>0&&(xe.push("","--- Agent Memory ---",`Total: ${U.totalMB} MB`,`Agents: ${U.agentCount}`),U.agents.slice(0,5).forEach(oe=>{xe.push(` ${oe.name}: ${oe.memoryMB} MB (${oe.status})`)})),N&&xe.push("","--- DOM ---",`DOM Nodes: ${N.nodeCount.toLocaleString()}`,`Canvases: ${N.canvasCount}`,`Images: ${N.imageCount}`,`Videos: ${N.videoCount}`),_&&xe.push("","--- Estimated Memory ---",`GPU Textures: ${_.count}`,`Est. VRAM: ~${_.estimatedMB} MB`,`Est. DOM: ~${Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)} MB`,`Est. Total: ~${((i==null?void 0:i.usedMB)??0)+_.estimatedMB+Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)} MB`),E&&(xe.push("","--- Server ---",`Uptime: ${F(E.uptime)}`,`Heap: ${E.process.heapUsedMB}/${E.process.heapTotalMB} MB`,`RSS: ${E.process.rssMB} MB`,`Load Avg: ${E.system.loadAvg.join(" ")}`,`System Memory: ${E.system.totalMemMB-E.system.freeMemMB}/${E.system.totalMemMB} MB`,"","--- WebSocket ---",`Clients: ${E.websocket.clients}`,`Sent: ${E.websocket.messagesSent}`,`Received: ${E.websocket.messagesReceived}`,"","--- HTTP ---",`Req/sec: ${E.http.reqPerSec}`,`Avg Latency: ${E.http.avgLatencyMs} ms`,`Max Latency: ${E.http.maxLatencyMs} ms`),E.agents.processes.length>0&&(xe.push("","--- Agent Processes ---",`Total: ${E.agents.total} (${E.agents.working} working, ${E.agents.idle} idle)`),E.agents.processes.forEach(oe=>{xe.push(` ${oe.name}: ${oe.memoryMB!=null?`${oe.memoryMB}MB`:"N/A"} (${oe.status})${oe.pid?` PID:${oe.pid}`:""}`)})));const je=xe.join(`
|
|
153
|
-
`);navigator.clipboard.writeText(je).then(()=>{const oe=J.currentTarget,Ee=oe.textContent;oe.textContent="Copied!",setTimeout(()=>{oe.textContent=Ee},1e3)})},style:{flex:1,background:"rgba(74, 255, 158, 0.3)",border:"1px solid rgba(74, 255, 158, 0.5)",color:"#4aff9e",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Copy Stats"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),Dc.report();const xe=window.__tideScene;xe!=null&&xe.logMemoryDiagnostics&&xe.logMemoryDiagnostics()},style:{flex:1,background:"rgba(74, 158, 255, 0.3)",border:"1px solid rgba(74, 158, 255, 0.5)",color:"#4a9eff",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Console"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),vb.clear(),Xd.reset(),Dc.reset(),r([]),f([]);const xe=Dc.getUsage();xe&&R(xe.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 KW(){const t=Hj(),e=b.useCallback(n=>{H.setViewMode(n)},[]);return[t,e]}const QW=["3d","2d","dashboard"],XW=b.memo(function({className:e=""}){const{t:n}=pt(["common"]),[s,a]=KW(),r=b.useRef(null),[i,c]=b.useState(null);b.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=b.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}}),QW.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 DT({className:t}){const{t:e}=pt(["terminal"]),[n,s]=b.useState(!1),[a,r]=b.useState(null),i=sy(),c=b.useCallback(async y=>{if(y.trim()){console.log("[VoiceAssistant] Transcribed:",y),s(!0),r(null);try{const S=await(await Lt(_t("/api/voice-assistant/process"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:y})})).json();if(S.success&&S.response)console.log("[VoiceAssistant] Response:",S.response),i.speak(S.response);else{const C=S.error||e("terminal:voiceAssistant.failedToProcess");console.error("[VoiceAssistant] Error:",C),r(C),i.speak(C)}}catch(v){console.error("[VoiceAssistant] Request failed:",v);const S=e("terminal:voiceAssistant.unavailable");r(S),i.speak(S)}finally{s(!1)}}},[i]),d=ST({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(" ")},x=()=>{if(r(null),i.speaking){i.stop();return}d.transcribing||n||d.toggleRecording()};return o.jsxs("button",{className:m(),onClick:x,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 JW=b.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:x,mobileView:y}){const{t:v}=pt(["terminal","common"]),S=Fr(),C=k=>{k(),n()};return o.jsxs(o.Fragment,{children:[S.experimentalVoiceAssistant&&o.jsx(DT,{className:"mobile-voice-assistant"}),y!=="terminal"&&o.jsx("button",{className:`mobile-fab-toggle ${e?"open":""}`,onClick:n,onTouchStart:k=>k.stopPropagation(),title:v(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:()=>C(s),onTouchEnd:k=>{k.preventDefault(),C(s)},title:v("terminal:mobileFab.showTerminal"),children:"💬"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(a),onTouchEnd:k=>{k.preventDefault(),C(a)},title:v("terminal:header.openSidebar"),children:"📋"}),x&&o.jsx("button",{className:"mobile-fab-option mobile-fab-option--highlight",onClick:()=>C(m),onTouchEnd:k=>{k.preventDefault(),C(m)},title:v("terminal:mobileFab.takeSnapshot"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(r),onTouchEnd:k=>{k.preventDefault(),C(r)},title:v("common:floatingButtons.settingsAndTools"),children:"⚙️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(i),onTouchEnd:k=>{k.preventDefault(),C(i)},title:v("common:floatingButtons.commanderView"),children:"📊"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(c),onTouchEnd:k=>{k.preventDefault(),C(c)},title:v("common:floatingButtons.supervisorOverview"),children:"🎖️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(d),onTouchEnd:k=>{k.preventDefault(),C(d)},title:v("common:floatingButtons.controls"),children:"⌨️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(f),onTouchEnd:k=>{k.preventDefault(),C(f)},title:v("common:floatingButtons.manageSkills"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(h),onTouchEnd:k=>{k.preventDefault(),C(h)},title:v("common:floatingButtons.viewSnapshots"),children:"📸"})]})]})}),ZW=b.memo(function({onOpenToolbox:e,onOpenCommander:n,onOpenSupervisor:s,onOpenControls:a,onOpenSkills:r,onOpenSnapshots:i,isGeneratingReport:c,pip:d}){const{t:f}=pt(["common","terminal"]),h=Fr();return o.jsxs(o.Fragment,{children:[h.experimentalVoiceAssistant&&o.jsx(DT,{}),o.jsx(Zn,{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(Zn,{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(Zn,{content:f("common:floatingButtons.viewSnapshots"),position:"left",children:o.jsx("button",{className:"snapshots-toggle-btn",onClick:i,children:"📸"})}),o.jsx(Zn,{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(Zn,{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(Zn,{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(Zn,{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"})]})})})]})}),eq=Ce.lazy(()=>vt(()=>import("./SpawnModal-BbKpL82w.js"),__vite__mapDeps([17,3,1,4])).then(t=>({default:t.SpawnModal}))),tq=Ce.lazy(()=>vt(()=>import("./BossSpawnModal-DUQ6HEgW.js"),__vite__mapDeps([18,3,1,4])).then(t=>({default:t.BossSpawnModal}))),nq=Ce.lazy(()=>vt(()=>import("./SubordinateAssignmentModal-B1TZX27W.js"),__vite__mapDeps([19,3,1,4])).then(t=>({default:t.SubordinateAssignmentModal}))),sq=Ce.lazy(()=>vt(()=>import("./index-BExjQf95.js"),__vite__mapDeps([20,3,1,4,21])).then(t=>({default:t.Toolbox}))),aq=Ce.lazy(()=>vt(()=>import("./index-BP3hr2mC.js"),__vite__mapDeps([22,3,1,4])).then(t=>({default:t.BuildingConfigModal}))),rq=Ce.lazy(()=>vt(()=>import("./index-BgUdbPaM.js"),__vite__mapDeps([23,24,3,1,4])).then(t=>({default:t.CommanderView}))),iq=Ce.lazy(()=>vt(()=>import("./SupervisorPanel-PK5vEWzs.js"),__vite__mapDeps([25,3,1,4])).then(t=>({default:t.SupervisorPanel}))),oq=Ce.lazy(()=>vt(()=>import("./index-BF9QVox6.js").then(t=>t.y),[]).then(t=>({default:t.FileExplorerPanel}))),lq=Ce.lazy(()=>vt(()=>import("./index--5OtsLD2.js"),__vite__mapDeps([26,3,1,4])).then(t=>({default:t.Spotlight}))),cq=Ce.lazy(()=>vt(()=>import("./ControlsModal-BU8Ip7nq.js"),__vite__mapDeps([27,3,1,4])).then(t=>({default:t.ControlsModal}))),uq=Ce.lazy(()=>vt(()=>import("./SkillsPanel-Djr7DSvf.js"),__vite__mapDeps([28,3,1,4])).then(t=>({default:t.SkillsPanel}))),dq=Ce.lazy(()=>vt(()=>Promise.resolve().then(()=>H2),void 0).then(t=>({default:t.AgentEditModal}))),fq=Ce.lazy(()=>vt(()=>import("./SnapshotManager-BfGQUnsS.js"),__vite__mapDeps([29,3,1,4])).then(t=>({default:t.SnapshotManager}))),pq=Ce.lazy(()=>vt(()=>import("./RestoreArchivedAreaModal-C7ym_R1q.js"),__vite__mapDeps([30,3,1,4])).then(t=>({default:t.RestoreArchivedAreaModal}))),hq=Ce.lazy(()=>vt(()=>import("./IntegrationsPanel-8a2TGZA7.js"),__vite__mapDeps([31,3,1,4])).then(t=>({default:t.IntegrationsPanel}))),mq=Ce.lazy(()=>vt(()=>import("./MonitoringModal-Cu8Kz_D_.js"),__vite__mapDeps([32,3,1,4])).then(t=>({default:t.MonitoringModal}))),gq=Ce.lazy(()=>vt(()=>import("./WorkflowEditorPanel-Brdqd-Ad.js"),__vite__mapDeps([33,3,1,4])).then(t=>({default:t.WorkflowEditorPanel}))),bq=Ce.lazy(()=>vt(()=>import("./TriggerManagerPanel-DVK-bbLW.js"),__vite__mapDeps([34,3,1,4])).then(t=>({default:t.TriggerManagerPanel})));function xq({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:x,triggerManagerModal:y,buildingModal:v,agentEditModal:S,snapshotsModal:C,restoreArchivedModal:k,explorerModal:N,contextMenu:A,spawnPosition:E,spawnAreaId:D,explorerFolderPath:_,contextMenuActions:I,buildingInitialPosition:O,sceneConfig:T,onConfigChange:M,onToolChange:R,onOpenAreaExplorer:P,onDeleteSelectedAgents:U,pendingBuildingDelete:q,onCancelBuildingDelete:z,onConfirmBuildingDelete:F,showBackNavModal:$,onCloseBackNavModal:V,onLeave:G,onOpenPM2LogsModal:B,onOpenBossLogsModal:Q,onOpenDatabasePanel:K,onSyncScene:W}){const be=ws(),fe=Array.from(be.snapshots.values()),J=be.snapshotsLoading;be.currentSnapshot,b.useEffect(()=>{C.isOpen&&H.fetchSnapshots()},[C.isOpen]);const xe=q==="selected",je=q&&q!=="selected"?be.buildings.get(q):null,oe=be.selectedBuildingIds.size;return o.jsxs(b.Suspense,{fallback:null,children:[o.jsx(sq,{config:T,onConfigChange:M,onToolChange:R,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:Ee=>v.open(Ee||null),onOpenAreaExplorer:P,onOpenIntegrationsModal:Ee=>h.open(Ee),onOpenMonitoringModal:()=>m.open(),onOpenWorkflowEditor:()=>x.open(),onOpenTriggerManager:()=>y.open()}),o.jsx(aq,{isOpen:v.isOpen,onClose:v.close,buildingId:v.data,initialPosition:O||void 0}),o.jsx(eq,{isOpen:t.isOpen,onClose:t.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:E,spawnAreaId:D}),o.jsx(tq,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:E}),o.jsx(nq,{isOpen:n.isOpen,bossId:n.data||"",onClose:n.close}),S.isOpen&&S.data&&(()=>{const Ee=be.agents.get(S.data);return Ee?o.jsx(dq,{agent:Ee,isOpen:S.isOpen,onClose:S.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:Ee=>{Ee.key==="Escape"&&r.close(),Ee.key==="Enter"&&U()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Ee=>Ee.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:U,autoFocus:!0,children:"Remove"})]})]})}),(je||xe)&&o.jsx("div",{className:"modal-overlay visible",onClick:z,onKeyDown:Ee=>{Ee.key==="Escape"&&z(),Ee.key==="Enter"&&F()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Ee=>Ee.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",xe&&oe>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[xe?o.jsxs("p",{children:["Delete ",oe," selected building",oe>1?"s":"","?"]}):o.jsxs("p",{children:["Delete ",o.jsx("strong",{children:je==null?void 0:je.name}),"?"]}),o.jsxs("p",{className:"confirm-modal-note",children:["This will permanently remove the building",xe&&oe>1?"s":""," and ",xe&&oe>1?"their":"its"," configuration."]})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:z,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:F,autoFocus:!0,children:"Delete"})]})]})}),$&&o.jsx("div",{className:"modal-overlay navigation-confirm-overlay visible",onClick:V,onKeyDown:Ee=>{Ee.key==="Escape"&&V()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:Ee=>Ee.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(b.Profiler,{id:"CommanderView",onRender:Kc,children:o.jsx(rq,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(iq,{isOpen:i.isOpen,onClose:i.close}),o.jsx(oq,{isOpen:N.isOpen||_!==null||be.explorerAreaId!==null,areaId:N.id||be.explorerAreaId||null,folderPath:_,onChangeArea:Ee=>N.open(Ee),onClose:()=>{N.close(),H.closeFileExplorer()}}),o.jsx(lq,{isOpen:c.isOpen,onClose:c.close,onOpenSpawnModal:()=>t.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenSupervisor:()=>i.open(),onOpenFileExplorer:Ee=>N.open(Ee),onOpenPM2LogsModal:B,onOpenBossLogsModal:Q,onOpenDatabasePanel:K,onOpenMonitoringModal:()=>m.open()}),o.jsx(cq,{isOpen:d.isOpen,onClose:d.close}),o.jsx(uq,{isOpen:f.isOpen,onClose:f.close}),o.jsx(hq,{isOpen:h.isOpen,onClose:h.close,initialTab:h.data}),o.jsx(mq,{isOpen:m.isOpen,onClose:m.close}),o.jsx(gq,{isOpen:x.isOpen,onClose:x.close}),o.jsx(bq,{isOpen:y.isOpen,onClose:y.close}),o.jsx(pq,{isOpen:k.isOpen,restorePosition:k.data??null,onClose:k.close,onRestored:W}),C.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:C.close,children:o.jsx("div",{className:"modal snapshot-manager-modal",onClick:Ee=>Ee.stopPropagation(),children:o.jsx(fq,{snapshots:fe,isLoading:J,onViewSnapshot:async Ee=>{await H.loadSnapshot(Ee),be.selectedAgentIds.clear(),H.setTerminalOpen(!0),C.close()},onDeleteSnapshot:async Ee=>{await H.deleteSnapshot(Ee),await H.fetchSnapshots()},onRestoreSnapshot:async Ee=>{await H.restoreFiles(Ee)},onExportSnapshot:async Ee=>{await H.loadSnapshot(Ee),C.close()},onClose:C.close})})}),o.jsx(go,{isOpen:A.isOpen,position:A.screenPosition,worldPosition:A.worldPosition,actions:I,onClose:A.close})]})}function yq({pip:t,title:e="Tide Commander",children:n}){return b.useEffect(()=>{t.pipWindow&&e&&(t.pipWindow.document.title=e)},[t.pipWindow,e]),!t.isOpen||!t.pipContainer?null:Rl.createPortal(n,t.pipContainer)}function ry(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 oy(t){const e=_u[t.class];return(e==null?void 0:e.icon)||"🤖"}function sb({agent:t,onClick:e}){const n=iy(t.status),s=ry(t.status),a=oy(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 Yc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}const LA={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},PA={systemPrompt:"System Prompt",systemTools:"System Tools",messages:"Messages",freeSpace:"Free Space",autocompactBuffer:"Autocompact Buffer"};function vq({agent:t,onBack:e}){const n=oy(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:ry(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:Yc(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:[Yc(a.totalTokens)," / ",Yc(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:LA[d]},title:`${PA[d]}: ${Yc(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:LA[d]}}),o.jsxs("div",{className:"pip-category-info",children:[o.jsx("div",{className:"pip-category-name",children:PA[d]}),o.jsxs("div",{className:"pip-category-tokens",children:[Yc(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 wq({agentId:t,onBack:e}){const n=dx(t),s=Dj(t),a=zj(),r=$j(),i=px(),c=b.useRef(null),d=b.useRef(null),[f,h]=b.useState(""),[m,x]=b.useState(!1),[y]=b.useState("simple"),v=!!(n!=null&&n.sessionId),S=Nj({selectedAgentId:t,hasSessionId:v,reconnectCount:a,historyRefreshTrigger:r,lastPrompts:i,outputScrollRef:c}),C=dT({outputs:s,viewMode:y}),k=b.useMemo(()=>{const{history:U}=S,q=new Map;for(const F of U)F.type==="tool_result"&&F.toolUseId&&q.set(F.toolUseId,F.content);return(F=>F.map($=>{if($.type==="tool_use"&&$.toolName==="Bash"&&$.toolUseId){const V=q.get($.toolUseId);let G;try{G=($.toolInput||($.content?JSON.parse($.content):{})).command}catch{}return{...$,_bashOutput:V,_bashCommand:G}}return $}))(U.filter(F=>F.type==="user"||F.type==="assistant"||F.type==="tool_use"))},[S.history]),[N,A]=b.useState({top:!1,bottom:!0}),E=b.useCallback(()=>{if(!c.current)return;const{scrollTop:U,scrollHeight:q,clientHeight:z}=c.current;A({top:U>20,bottom:U<q-z-20})},[]);b.useEffect(()=>{c.current&&(c.current.scrollTop=c.current.scrollHeight,E())},[s.length,k.length,E]);const D=b.useCallback(()=>{c.current&&c.current.scrollBy({top:-200,behavior:"smooth"})},[]),_=b.useCallback(()=>{c.current&&c.current.scrollBy({top:200,behavior:"smooth"})},[]),I=b.useCallback(()=>{const U=f.trim();!U||!n||(H.sendCommand(t,U),h(""),setTimeout(()=>{var q;return(q=d.current)==null?void 0:q.focus()},50))},[f,t,n]),O=b.useCallback(U=>{h(U.target.value)},[]),T=b.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),I())},[I]);b.useEffect(()=>{const U=setTimeout(()=>{var q;return(q=d.current)==null?void 0:q.focus()},100);return()=>clearTimeout(U)},[t]);const M=b.useCallback((U,q)=>{const z=_p(U,n==null?void 0:n.cwd),F=z.line?{...q||{},targetLine:z.line}:q;H.setFileViewerPath(z.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=oy(n),P=iy(n.status);return m?o.jsx(vq,{agent:n,onBack:()=>x(!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:P},children:ry(n.status)})]}),o.jsx("div",{className:"pip-context-section",children:o.jsx(Zj,{contextInfo:Cp(n),onClick:()=>x(!0)})}),o.jsxs("div",{className:"pip-conversation-wrapper",children:[o.jsxs("div",{className:"pip-conversation guake-output",ref:c,onScroll:E,children:[!S.loadingHistory&&S.hasMore&&o.jsx("div",{className:"guake-load-more pip-load-more",children:S.loadingMore?o.jsx("span",{children:"Loading older messages..."}):o.jsxs("button",{onClick:S.loadMoreHistory,children:["Load more (",S.totalCount-S.history.length," older)"]})}),S.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((U,q)=>o.jsx(MT,{message:U,agentId:t,simpleView:!0,onFileClick:M},`h-${q}`)),C.map((U,q)=>o.jsx(ay,{output:U,agentId:t,onFileClick:M},`o-${q}`)),!S.loadingHistory&&k.length===0&&C.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:[N.top&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-up",onClick:D,title:"Scroll up",children:"↑"}),N.bottom&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-down",onClick:_,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:T,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 kq({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(sb,{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(sb,{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(sb,{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 Sq(){const[t,e]=b.useState(null),n=a=>{e(a)},s=()=>{e(null)};return t?o.jsx(wq,{agentId:t,onBack:s}):o.jsx(kq,{onSelectAgent:n})}function Cq(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 Aq(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 jq=4e3;function Nq(){const t=Oj(),[e,n]=b.useState(!1),[s,a]=b.useState(!1),[r,i]=b.useState(!0),[c,d]=b.useState(!1),[f,h]=b.useState(()=>nx()),[m,x]=b.useState(!1),[y,v]=b.useState(null),[S,C]=b.useState(null),k=b.useRef(!0),N=b.useRef(!1),A=b.useCallback((O=7e3)=>H.getState().isConnected?Promise.resolve(!0):new Promise(T=>{let M=!1;const R=q=>{M||(M=!0,clearTimeout(U),P(),T(q))},P=H.subscribe(()=>{H.getState().isConnected&&R(!0)}),U=setTimeout(()=>R(!1),O)}),[]);b.useEffect(()=>{const O=setTimeout(()=>i(!1),3e3);return()=>clearTimeout(O)},[]),b.useEffect(()=>{if(t){N.current=!0,d(!1);return}if(N.current){i(!0),d(!0);const O=setTimeout(()=>{i(!1),d(!1)},1e4);return()=>clearTimeout(O)}},[t]),b.useEffect(()=>()=>{k.current=!1},[]),b.useEffect(()=>KD(O=>{h(O)}),[]);const E=b.useCallback(()=>{navigator.clipboard.writeText("bunx tide-commander").then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(()=>{})},[]),D=b.useCallback(async()=>{if(m)return;const O=Date.now(),T=()=>jq-(Date.now()-O);v(null),C("Validating URL");const M=f.trim()||"http://localhost:6200",R=Cq(M);if(!R.ok){C(null),v(R.error||"Invalid backend URL");return}x(!0),C("Checking host reachability");const P=T();if(P<=0){x(!1),C(null),v("Connection timeout after 4 seconds");return}const U=await Aq(R.normalizedUrl,P);if(!U.ok){if(!k.current)return;x(!1),C(null),T()<=0?v("Connection timeout after 4 seconds"):v(U.error||"Failed to reach host");return}YD(R.normalizedUrl),C("Connecting to server"),UR();const q=T();if(q<=0){x(!1),C(null),v("Connection timeout after 4 seconds");return}const z=await A(q);if(k.current){if(!z){x(!1),C(null),T()<=0?v("Connection timeout after 4 seconds"):v("Could not establish WebSocket connection. Verify host and auth token, then retry");return}x(!1),C("Connected"),v(null)}},[f,m,A]),_=b.useCallback(O=>{O.key==="Enter"&&!m&&D()},[D,m]),I=b.useCallback(()=>{n(!0)},[]);return t||e?null:r&&c?o.jsxs("div",{className:"reconnecting-toast",children:[o.jsx("span",{className:"reconnecting-spinner"}),"Reconnecting..."]}):r?null:o.jsx("div",{className:"not-connected-overlay",children:o.jsxs("div",{className:"not-connected-panel",children:[o.jsx("h2",{className:"not-connected-title",children:"Tide Commander"}),o.jsx("p",{className:"not-connected-description",children:"A visual multi-agent orchestrator for Claude Code and Codex. Deploy, control, and monitor your AI team from an RTS-inspired interface."}),o.jsx("p",{className:"not-connected-privacy",children:"Tide Commander syncs with Claude Code instances running on your local machine. No files or code are sent to this server."}),o.jsxs("div",{className:"not-connected-setup",children:[o.jsx("p",{className:"not-connected-setup-label",children:"Get started:"}),o.jsxs("div",{className:"not-connected-code",onClick:E,title:"Click to copy",children:[o.jsx("span",{children:"bunx tide-commander"}),o.jsx("span",{className:"not-connected-copy-icon",children:s?"✓":"⧉"})]})]}),o.jsxs("div",{className:"not-connected-url-section",children:[o.jsx("label",{className:"not-connected-url-label",htmlFor:"backend-url",children:"Backend URL"}),o.jsx("div",{className:"not-connected-url-row",children:o.jsx("input",{id:"backend-url",type:"text",className:"not-connected-url-input",placeholder:"http://localhost:6200",value:f,disabled:m,onChange:O=>{const T=O.target.value;h(T),y&&v(null)},onKeyDown:_})}),o.jsx("span",{className:"config-hint",children:"Leave empty for auto-detect"}),S&&!y&&o.jsx("div",{className:"not-connected-status","aria-live":"polite",children:S}),y&&o.jsx("div",{className:"not-connected-error","aria-live":"assertive",children:y})]}),o.jsxs("div",{className:"not-connected-actions",children:[o.jsx("button",{className:"not-connected-btn not-connected-btn-retry",onClick:()=>{D()},disabled:m,children:m?"Connecting...":"↻ Connect"}),o.jsx("button",{className:"not-connected-btn not-connected-btn-explore",onClick:I,children:"Explore"})]})]})})}const IA="tide-onboarding-dismissed";function Tq({onCreateAgent:t}){const{t:e}=pt("common"),n=Oj(),s=Mj(),[a,r]=b.useState(()=>sessionStorage.getItem(IA)==="1"),i=n&&!a&&s===0,c=b.useCallback(()=>{r(!0),sessionStorage.setItem(IA,"1")},[]),d=b.useCallback(()=>{c(),t()},[c,t]),f=b.useCallback(h=>{h.key==="Escape"&&c()},[c]);return i?o.jsx(or,{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 RT(){return{"Content-Type":"application/json","X-Auth-Token":Ti()}}async function Eq(t){const e=await fetch(`${Ca()}/api/areas/${t}/organize`,{method:"POST",headers:RT()});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 _q(){const t=await fetch(`${Ca()}/api/areas/organize-all`,{method:"POST",headers:RT()});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 OT(t,e){var s,a;const n=H.getState();for(const r of t.organized){const i=n.agents.get(r.agentId);if(i){const c={...i,position:r.position};H.updateAgent(c),(s=e.current)==null||s.updateAgent(c,!0)}}for(const r of t.buildings){const i=n.buildings.get(r.buildingId);i&&(H.updateBuilding(r.buildingId,{position:r.position}),(a=e.current)==null||a.updateBuilding({...i,position:r.position}))}}function Mq(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;H.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:()=>{H.selectAgent(e.id),H.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;H.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:()=>{H.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;H.bringAreaToFront(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),i.push({id:"send-to-back",label:"Send to Back",icon:"⬇️",onClick:()=>{var f;H.sendAreaToBack(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),d.assignedAgentIds.length>0&&i.push({id:"organize-area",label:"Organize Area",icon:"✨",onClick:()=>{Eq(e.id).then(f=>{OT(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,x;const f=d.assignedAgentIds.length;H.archiveArea(e.id,y=>H.stopAgent(y)),(m=r.sceneRef.current)==null||m.syncAreas(),(x=r.sceneRef.current)==null||x.syncAgents(Array.from(H.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;H.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:()=>{H.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};H.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:()=>{H.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 Dq=Ce.lazy(()=>vt(()=>import("./index-RJgcrQXD.js"),__vite__mapDeps([35,3,1,4,36])).then(t=>({default:t.DatabasePanel}))),Rq=Ce.lazy(()=>vt(()=>import("./PM2LogsModal-DTBPwViK.js"),__vite__mapDeps([37,38,3,1,4])).then(t=>({default:t.PM2LogsModal}))),Oq=Ce.lazy(()=>vt(()=>import("./DockerLogsModal-CbYYg1sc.js"),__vite__mapDeps([39,38,3,1,4])).then(t=>({default:t.DockerLogsModal}))),Lq=Ce.lazy(()=>vt(()=>import("./BossLogsModal-CFwfed1-.js"),__vite__mapDeps([40,38,3,1,4])).then(t=>({default:t.BossLogsModal}))),Pq=Ce.lazy(()=>vt(()=>import("./Scene2DCanvas-Bzggyv_C.js"),__vite__mapDeps([41,3,1,4,42])).then(t=>({default:t.Scene2DCanvas}))),Iq=Ce.lazy(()=>vt(()=>import("./index-wIjtXnz9.js"),__vite__mapDeps([43,3,1,4,44])).then(t=>({default:t.DashboardView}))),Bq=Ce.lazy(()=>vt(()=>import("./IframeModal-Ca7ZWrHU.js"),__vite__mapDeps([45,3,1,4,46])).then(t=>({default:t.IframeModal}))),Fq=Ce.lazy(()=>vt(()=>import("./SaveSnapshotModal-Byqak-Tf.js"),__vite__mapDeps([47,3,1,4])).then(t=>({default:t.SaveSnapshotModal})));function zq(){const{t}=pt(["common","notifications"]),e=b.useRef(null),n=b.useRef(null),s=ss(),a=ss(),r=ss(),i=ss(),c=ss(),d=ss(),f=ss(),h=ss(),m=ss(),x=ss(),y=ss(),v=ss(),S=ss(),C=ss(),k=ss(),N=ss(),A=ss(),E=ss(),D=ss(),_=QD(),I=fL(),O=XD(),T=lR(),[M,R]=b.useState(null),P=JR(),[U,q]=b.useState(!1),[z,F]=b.useState(null),[$,V]=b.useState(null),[G,B]=b.useState(null),[Q,K]=b.useState(null),[W,be]=b.useState(null),[fe,J]=b.useState(null),[xe,je]=b.useState(null),[oe,Ee]=b.useState(null),[Fe,Ve]=b.useState(null),[De,ge]=b.useState(null),Oe=b.useCallback(Ae=>{ge(Ae),Ae&&localStorage.setItem("tide-commander-last-database-building",Ae)},[]),te=b.useCallback(()=>Oe(null),[Oe]),{handleMouseDown:$e,handleClick:se}=ka(te),Ne=b.useCallback(()=>Ve(null),[]),{handleMouseDown:_e,handleClick:pe}=ka(Ne),Ge=b.useRef(fe);Ge.current=fe;const it=b.useCallback(Ae=>{J(Ae)},[]),dt=b.useCallback(()=>Ge.current,[]),ce=b.useRef(null),[X,ne]=b.useState(Aj),[ke,ee]=b.useState(0),[ye,Ie]=b.useState(!1),[He,ue]=b.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[de,re]=b.useState(!1),[me,ve]=b.useState(!1),Ue=Ij(),Qe=Hj(),ze=mx(),nt=gx(),ot=Pj(),{showToast:st}=qj(),{showAgentNotification:lt}=YL(),{showBackNavModal:rt,setShowBackNavModal:ht,handleLeave:jt}=wO();lO({showToast:st,showAgentNotification:lt});const[he,Me]=b.useState(!1);b.useEffect(()=>{const Ae=Je=>{var en;((en=Je.detail)==null?void 0:en.mode)==="3d"&&Me(!0)};return window.addEventListener("tide:viewmode-switch-pressed",Ae),()=>{window.removeEventListener("tide:viewmode-switch-pressed",Ae)}},[]),b.useEffect(()=>{Qe==="3d"&&Me(!0)},[Qe]);const Ye=oO({canvasRef:e,selectionBoxRef:n,viewMode:Qe,sceneMountKey:ke,showToast:st,showAgentNotification:lt,toolboxModal:i,contextMenu:O,setHoveredAgentPopup:be,setBuildingPopup:it,getBuildingPopup:dt,openBuildingModal:Ae=>k.open(Ae),openPM2LogsModal:Ae=>je(Ae),openBossLogsModal:Ae=>Ee(Ae),openDatabasePanel:Ae=>Oe(Ae),onSceneLoadingChange:Me}),tt=Mj(),Nt=rr(),zt=hx(),Pt=fx(),It=rL(),Vt=aL(),mt=sL(),ct=Fr(),xt=oL(),Dt=CL(),Sn=AL(),cn=b.useMemo(()=>Array.from(Pt),[Pt]),cs=b.useRef(!1);mj("AppContent"),cO(Ye),uO(Ye),dO(Ye),CO(),fO(Ye,Vt),pO(Ye,ct.powerSaving),b.useEffect(()=>{var Ae;document.title=((Ae=ct.tabTitle)==null?void 0:Ae.trim())||"Tide Commander"},[ct.tabTitle]),b.useEffect(()=>{var Pn,Ws;if(cs.current||typeof window>"u")return;const Ae=new URLSearchParams(window.location.search),Je=(Pn=Ae.get("agentId"))==null?void 0:Pn.trim(),Ct=(Ws=Ae.get("agentName"))==null?void 0:Ws.trim();if(!Je&&!Ct||tt===0)return;const en=H.getState().agents,Ln=Ae.get("openTerminal"),$t=Ln?["1","true","yes"].includes(Ln.toLowerCase()):!0;let At=Je?en.get(Je):void 0;if(!At&&Ct){const Na=Ct.toLowerCase();At=Array.from(en.values()).find(oa=>oa.name.toLowerCase()===Na)}if(!At){console.warn("[DeepLink] No matching agent found for query params",{rawAgentId:Je,rawAgentName:Ct}),cs.current=!0;return}H.selectAgent(At.id),$t&&H.setTerminalOpen(!0),Ae.delete("agentId"),Ae.delete("agentName"),Ae.delete("openTerminal");const Nn=Ae.toString(),Cs=`${window.location.pathname}${Nn?`?${Nn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,Cs),cs.current=!0},[tt]),vO({sceneRef:Ye,spawnModal:s,commanderModal:c,explorerModal:_,spotlightModal:h,deleteConfirmModal:d,onRequestBuildingDelete:()=>K("selected"),onOpenDatabasePanel:Oe,onCloseDatabasePanel:te,databasePanelOpen:De!==null}),Qt("spawn-modal",s.isOpen,s.close),Qt("boss-spawn-modal",a.isOpen,a.close),Qt("subordinate-modal",r.isOpen,r.close),Qt("toolbox-modal",i.isOpen,i.close),Qt("commander-modal",c.isOpen,c.close),Qt("delete-confirm-modal",d.isOpen,d.close),Qt("supervisor-modal",f.isOpen,f.close),Qt("spotlight-modal",h.isOpen,h.close),Qt("controls-modal",m.isOpen,m.close),Qt("skills-modal",x.isOpen,x.close),Qt("integrations-modal",y.isOpen,y.close),Qt("monitoring-modal",v.isOpen,v.close),Qt("workflow-editor-modal",S.isOpen,S.close),Qt("trigger-manager-modal",C.isOpen,C.close),Qt("building-modal",k.isOpen,k.close),Qt("agent-edit-modal",N.isOpen,N.close),Qt("snapshots-modal",A.isOpen,A.close),Qt("save-snapshot-modal",E.isOpen,E.close),Qt("explorer-modal",_.isOpen||I!==null,()=>{_.close(),H.closeFileExplorer()}),Qt("context-menu",O.isOpen,O.close),Qt("mobile-sidebar",ye,()=>Ie(!1)),Qt("mobile-fab-menu",me,()=>ve(!1)),Qt("file-viewer",ze!==null,()=>H.clearFileViewerPath()),Qt("context-modal",nt!==null,()=>H.closeContextModal()),Qt("terminal",ot,()=>H.setTerminalOpen(!1)),Qt("pm2-logs-modal",xe!==null,()=>je(null)),Qt("boss-logs-modal",oe!==null,()=>Ee(null)),Qt("database-panel",De!==null,te),Qt("terminal-modal",Fe!==null,Ne);const Ba=b.useRef(ot),Es=b.useRef(x),Us=b.useRef(m);Es.current=x,Us.current=m,b.useEffect(()=>{Ba.current&&!ot&&(Es.current.close(),Us.current.close()),Ba.current=ot},[ot]),b.useEffect(()=>{},[]),b.useEffect(()=>{if(Ue!=="3d"||Qe!=="3d")return;const Ae=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(Ae)},[Ue,Qe]);const Fa=b.useCallback(Ae=>{var Je,Ct,en,Ln,$t,At,Nn,Cs,Pn,Ws;ne(Ae),rO(Ae),(Je=Ye.current)==null||Je.setCharacterScale(Ae.characterScale),(Ct=Ye.current)==null||Ct.setScale3D(Ae.scale3d),(en=Ye.current)==null||en.setTimeMode(Ae.timeMode),(Ln=Ye.current)==null||Ln.setTerrainConfig(Ae.terrain),($t=Ye.current)==null||$t.setFloorStyle(Ae.terrain.floorStyle),(At=Ye.current)==null||At.setGridVisible(Ae.gridVisible),(Nn=Ye.current)==null||Nn.setAgentModelStyle(Ae.modelStyle),(Cs=Ye.current)==null||Cs.setIdleAnimation(Ae.animations.idleAnimation),(Pn=Ye.current)==null||Pn.setWorkingAnimation(Ae.animations.workingAnimation),(Ws=Ye.current)==null||Ws.setFpsLimit(Ae.fpsLimit)},[Ye]),Ss=b.useCallback(Ae=>{var Je;if((Je=Ye.current)==null||Je.setDrawingTool(Ae),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(Ae),Ae==="rectangle"||Ae==="circle"){const Ct=t(Ae==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");st("info",Ct,t("notifications:drawing.clickAndDrag"),3e3)}},[Ye,st]),es=b.useCallback(Ae=>{var Je;(Je=Ye.current)==null||Je.focusAgent(Ae)},[Ye]),Mt=b.useCallback(Ae=>{H.killAgent(Ae)},[]),is=b.useCallback(Ae=>{var Je;(Je=Ye.current)==null||Je.callSubordinates(Ae)},[Ye]),fn=b.useCallback(Ae=>{_.open(Ae)},[_]),ur=b.useCallback(()=>{k.open(null)},[k]),Ur=b.useCallback(()=>{var Ae;(Ae=Ye.current)==null||Ae.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),st("info",t("notifications:drawing.rectangleTool"),t("notifications:drawing.clickAndDrag"),3e3)},[Ye,st]),_s=b.useCallback(Ae=>{R(Ae)},[]),Ms=b.useCallback(()=>{R(null)},[]),_i=b.useCallback(()=>{const Ae=Array.from(H.getState().selectedAgentIds);Ae.forEach(Je=>{var Ct;H.removeAgentFromServer(Je),(Ct=Ye.current)==null||Ct.removeAgent(Je)}),d.close(),st("info",t("notifications:toast.agentsRemoved"),t("notifications:toast.agentsRemovedMsg",{count:Ae.length}))},[st,d,Ye,t]),wo=b.useCallback(()=>{var Ae,Je;if(Q==="selected"){const Ct=It.size;H.deleteSelectedBuildings(),(Ae=Ye.current)==null||Ae.syncBuildings(),st("info",t("notifications:toast.buildingsDeleted"),t("notifications:toast.buildingsDeletedMsg",{count:Ct}))}else if(Q){const Ct=zt.get(Q);H.deleteBuilding(Q),(Je=Ye.current)==null||Je.syncBuildings(),st("info",t("notifications:toast.buildingDeleted"),t("notifications:toast.buildingDeletedMsg",{name:(Ct==null?void 0:Ct.name)||"Building"}))}K(null)},[Q,zt,It.size,st,Ye,t]),Wr=b.useMemo(()=>Mq(O.worldPosition,O.target,H.getState().agents,Nt,zt,{showToast:st,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:Ae=>_.open(Ae),openBuildingModal:Ae=>k.open(Ae),openAgentEditModal:Ae=>N.open(Ae),requestBuildingDelete:Ae=>K(Ae),setSpawnPosition:F,openRestoreArchivedModal:Ae=>D.open(Ae),sceneRef:Ye}),[O.worldPosition,O.target,Nt,zt,s,a,k,i,c,_,N,D,st,Ye]);b.useEffect(()=>{!s.isOpen&&!a.isOpen&&(F(null),B(null))},[s.isOpen,a.isOpen]),b.useEffect(()=>{const Ae=$t=>{const At=$t.detail;B((At==null?void 0:At.areaId)||null),F((At==null?void 0:At.position)||null),s.open()},Je=$t=>{var Cs,Pn;const At=$t.detail;if(!(At!=null&&At.buildingId))return;const Nn=H.getState().buildings.get(At.buildingId);Nn&&(Nn.type==="server"&&((Cs=Nn.pm2)!=null&&Cs.enabled)?je(At.buildingId):Nn.type==="boss"?Ee(At.buildingId):Nn.type==="database"?Oe(At.buildingId):Nn.type==="folder"&&Nn.folderPath?H.openFileExplorer(Nn.folderPath):Nn.type==="terminal"&&((Pn=Nn.terminalStatus)!=null&&Pn.url)?Ve(At.buildingId):k.open(At.buildingId))},Ct=$t=>{const At=$t.detail;At!=null&&At.buildingId&&k.open(At.buildingId)},en=$t=>{const At=$t.detail;V((At==null?void 0:At.position)||null),k.open(null)},Ln=$t=>{const At=$t.detail;At!=null&&At.buildingId?Ve(At.buildingId):At!=null&&At.url&&R(At.url)};return window.addEventListener("tide:open-spawn-modal",Ae),window.addEventListener("tide:building-action",Je),window.addEventListener("tide:building-edit",Ct),window.addEventListener("tide:building-create",en),window.addEventListener("tide:open-iframe-modal",Ln),()=>{window.removeEventListener("tide:open-spawn-modal",Ae),window.removeEventListener("tide:building-action",Je),window.removeEventListener("tide:building-edit",Ct),window.removeEventListener("tide:building-create",en),window.removeEventListener("tide:open-iframe-modal",Ln)}},[s,k]);const Il=mt==="rectangle"||mt==="circle",bs=b.useCallback(()=>{var Ae;(Ae=Ye.current)==null||Ae.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ye]),ja=b.useCallback(()=>ve(Ae=>!Ae),[]),us=b.useCallback(()=>H.setMobileView("terminal"),[]),Gn=b.useCallback(()=>Ie(!0),[]),qr=cn.length===1&&H.getOutputs(cn[0]).length>0;return o.jsxs("div",{className:`app ${ot?"terminal-open":""} ${Il?"drawing-mode":""} ${He?"sidebar-collapsed":""} mobile-view-${Ue} view-mode-${Qe}`,children:[o.jsx(Nq,{}),o.jsx(Tq,{onCreateAgent:s.open}),o.jsx(YW,{visible:ct.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(XW,{className:"app-view-mode-toggle"}),o.jsx(kj,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:U,title:"Auto-organize all agents in their areas",onClick:()=>{q(!0),_q().then(Ae=>{OT(Ae,Ye),st("success","Organized",`Arranged ${Ae.organized.length} agent${Ae.organized.length!==1?"s":""}`)}).catch(Ae=>{console.error("organize all error:",Ae),st("error","Organize Failed",Ae.message||"Failed to organize")}).finally(()=>q(!1))},children:[U?"⏳":"✨"," Organize"]})]}),o.jsxs("main",{className:"main-content",children:[o.jsxs("div",{className:"battlefield-container",children:[P&&o.jsxs("div",{className:"workspace-switch-overlay",children:[o.jsx("div",{className:"workspace-switch-spinner"}),o.jsx("span",{className:"workspace-switch-text",children:"Switching workspace..."})]}),o.jsx(Ce.Suspense,{fallback:null,children:Qe==="dashboard"?o.jsx(Iq,{onSelectAgent:Ae=>H.selectAgent(Ae),onFocusAgent:Ae=>{H.setViewMode("3d"),es(Ae)},onKillAgent:Mt,onSelectBuilding:Ae=>H.selectBuilding(Ae),onOpenTerminal:Ae=>{H.selectAgent(Ae),H.setTerminalOpen(!0)},onFocusZone:Ae=>{H.setViewMode("3d");const Je=H.getState().areas.get(Ae);Je&&Je.assignedAgentIds.length>0&&es(Je.assignedAgentIds[0])}}):Qe==="2d"?o.jsx(Pq,{onAgentClick:(Ae,Je)=>{Je?H.addToSelection(Ae):H.selectAgent(Ae)},onAgentDoubleClick:Ae=>{if(window.innerWidth<=768){H.openTerminalOnMobile(Ae);return}H.selectAgent(Ae),H.setTerminalOpen(!0)},onBuildingClick:(Ae,Je)=>{H.selectBuilding(Ae);const Ct=H.getState().buildings.get(Ae);(Ct==null?void 0:Ct.type)==="folder"&&Ct.folderPath?H.openFileExplorer(Ct.folderPath):((Ct==null?void 0:Ct.type)==="server"||(Ct==null?void 0:Ct.type)==="boss"||(Ct==null?void 0:Ct.type)==="database")&&(ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{it({buildingId:Ae,screenPos:Je,fromClick:!0}),ce.current=null},150))},onBuildingDoubleClick:Ae=>{var Ct;ce.current&&(clearTimeout(ce.current),ce.current=null),it(null);const Je=H.getState().buildings.get(Ae);(Je==null?void 0:Je.type)==="server"&&((Ct=Je.pm2)!=null&&Ct.enabled)?je(Ae):(Je==null?void 0:Je.type)==="boss"?Ee(Ae):(Je==null?void 0:Je.type)==="database"?Oe(Ae):(Je==null?void 0:Je.type)==="folder"&&Je.folderPath?H.openFileExplorer(Je.folderPath):k.open(Ae)},onGroundClick:()=>{H.selectAgent(null),H.selectBuilding(null)},onAreaDoubleClick:Ae=>{H.selectArea(Ae),i.open()},onContextMenu:(Ae,Je,Ct)=>{const en=Ct?{type:Ct.type,id:Ct.id}:{type:"ground"};O.open(Ae,Je,en)},onMoveCommand:(Ae,Je)=>{const en=Ae.length,Ln=[];if(en===1)Ln.push({x:Je.x,y:0,z:Je.z});else if(en<=6){const $t=1.2*Math.max(1,en/3);for(let At=0;At<en;At++){const Nn=At/en*Math.PI*2-Math.PI/2;Ln.push({x:Je.x+Math.cos(Nn)*$t,y:0,z:Je.z+Math.sin(Nn)*$t})}}else{const $t=Math.ceil(Math.sqrt(en)),At=Math.ceil(en/$t),Nn=($t-1)*1.2/2,Cs=(At-1)*1.2/2;for(let Pn=0;Pn<en;Pn++){const Ws=Pn%$t,Na=Math.floor(Pn/$t);Ln.push({x:Je.x+Ws*1.2-Nn,y:0,z:Je.z+Na*1.2-Cs})}}Ae.forEach(($t,At)=>{H.moveAgent($t,Ln[At])})},onBuildingDragMove:(Ae,Je)=>{var en;const Ct=H.getState().buildings.get(Ae);Ct&&(H.getState().buildings.set(Ae,{...Ct,position:{x:Je.x,z:Je.z}}),(en=window.__tideScene2D)==null||en.syncBuildings())},onBuildingDragEnd:(Ae,Je)=>{H.updateBuildingPosition(Ae,Je)},scale2d:X.scale2d,showTaskLabels:X.show2DTaskLabels,showGrid:X.gridVisible,fpsLimit:X.fpsLimit}):o.jsxs(Ce.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:n,id:"selection-box"})]},ke)}),he&&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(JW,{isOpen:me,onToggle:ja,onShowTerminal:us,onOpenSidebar:Gn,onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:x.open,onOpenSnapshots:A.open,onTakeSnapshot:E.open,canTakeSnapshot:qr,mobileView:Ue}),ye&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>Ie(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${He?"is-collapsed":""} ${de?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)Ie(!ye);else{const Je=!He;ue(Je),localStorage.setItem("tide-commander-sidebar-collapsed",String(Je))}},title:He?"Open sidebar":"Close sidebar",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:de?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:He?"15 18 9 12 15 6":"9 18 15 12 9 6"})})}),o.jsxs("aside",{className:`sidebar ${ye?"sidebar-open":""} ${He?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>Ie(!1),title:"Close sidebar",children:"✕"}),cn.length>0?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(b.Profiler,{id:"UnitPanel",onRender:Kc,children:o.jsx(fS,{onFocusAgent:es,onKillAgent:Mt,onCallSubordinates:is,onOpenAreaExplorer:fn})})}),o.jsx("div",{className:"sidebar-section tool-history-section",children:o.jsx(b.Profiler,{id:"ToolHistory",onRender:Kc,children:o.jsx(K4,{agentIds:cn})})})]}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(b.Profiler,{id:"UnitPanel",onRender:Kc,children:o.jsx(fS,{onFocusAgent:es,onKillAgent:Mt,onCallSubordinates:is,onOpenAreaExplorer:fn})})})]}),o.jsx(b.Profiler,{id:"GuakeOutputPanel",onRender:Kc,children:o.jsx(NW,{onSaveSnapshot:E.open})})]}),o.jsx(ZW,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:x.open,onOpenSnapshots:A.open,isGeneratingReport:xt,pip:T}),o.jsx(BW,{activeTool:mt,onExit:bs}),W&&(()=>{const Ae=H.getState().agents.get(W.agentId);return Ae?o.jsx($W,{agent:Ae,screenPos:W.screenPos,onClose:()=>be(null)}):null})(),fe&&(()=>{const Ae=zt.get(fe.buildingId);if(!Ae)return null;const Je=()=>it(null);return Ae.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(VW,{building:Ae,screenPos:fe.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(fe.buildingId)},onOpenLogsModal:()=>{Je(),Ee(fe.buildingId)},onOpenUrlInModal:_s})]}):Ae.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(GW,{building:Ae,screenPos:fe.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(fe.buildingId)},onOpenDatabasePanel:()=>{Je(),Oe(fe.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(UW,{building:Ae,screenPos:fe.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(fe.buildingId)},onOpenLogsModal:()=>{je(fe.buildingId)},onOpenUrlInModal:_s})]})})(),xe&&(()=>{var Je;const Ae=zt.get(xe);return Ae?(Je=Ae.docker)!=null&&Je.enabled?o.jsx(Oq,{building:Ae,isOpen:!0,onClose:()=>je(null)}):o.jsx(Rq,{building:Ae,isOpen:!0,onClose:()=>je(null)}):null})(),oe&&(()=>{const Ae=zt.get(oe);return Ae?o.jsx(Lq,{building:Ae,isOpen:!0,onClose:()=>Ee(null)}):null})(),De&&(()=>{const Ae=zt.get(De);return Ae?o.jsx("div",{className:"modal-overlay visible",onMouseDown:$e,onClick:se,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(Dq,{building:Ae,onClose:te})})}):null})(),Fe&&(()=>{var Je;const Ae=zt.get(Fe);return!Ae||!((Je=Ae.terminalStatus)!=null&&Je.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:_e,onClick:pe,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 - ",Ae.name]}),o.jsx("button",{className:"terminal-modal-close",onClick:Ne,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(Kb,{terminalUrl:Ae.terminalStatus.url,visible:!0})]})})})(),o.jsx(yq,{pip:T,title:"Tide Commander - Agents",children:o.jsx(Sq,{})}),o.jsx(Bq,{url:M||"",title:M?`Preview - ${M}`:"",isOpen:!!M,onClose:Ms}),E.isOpen&&cn.length===1&&(()=>{const Ae=cn[0],Je=H.getState().agents.get(Ae);if(!Je)return null;const Ct=H.getOutputs(Ae);return o.jsx(Fq,{isOpen:E.isOpen,onClose:E.close,agent:Je,outputCount:Ct.length,onSave:async en=>{try{const Ln=Ct.map($t=>({type:"message",content:$t.text,timestamp:new Date($t.timestamp).toISOString()}));await H.createSnapshot(en.agentId,Je.name,en.title,en.description,Ln,[]),E.close(),st("success",t("notifications:toast.snapshotSaved"),t("notifications:toast.snapshotSavedMsg"))}catch(Ln){const $t=Ln instanceof Error?Ln.message:t("notifications:toast.snapshotFailedMsg");st("error",t("notifications:toast.snapshotFailed"),$t)}},isSaving:Dt,error:Sn||void 0})})(),o.jsx(IW,{onFocusAgent:es,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:ur,onNewAreaClick:Ur}),o.jsx(xq,{spawnModal:s,bossSpawnModal:a,subordinateModal:r,toolboxModal:i,commanderModal:c,deleteConfirmModal:d,supervisorModal:f,spotlightModal:h,controlsModal:m,skillsModal:x,integrationsModal:y,monitoringModal:v,workflowEditorModal:S,triggerManagerModal:C,buildingModal:k,buildingInitialPosition:$,agentEditModal:N,snapshotsModal:A,restoreArchivedModal:D,explorerModal:_,contextMenu:O,spawnPosition:z,spawnAreaId:G,explorerFolderPath:I,contextMenuActions:Wr,sceneConfig:X,onConfigChange:Fa,onToolChange:Ss,onOpenAreaExplorer:fn,onDeleteSelectedAgents:_i,pendingBuildingDelete:Q,onCancelBuildingDelete:()=>K(null),onConfirmBuildingDelete:wo,showBackNavModal:rt,onCloseBackNavModal:()=>ht(!1),onLeave:jt,onOpenPM2LogsModal:Ae=>je(Ae),onOpenBossLogsModal:Ae=>Ee(Ae),onOpenDatabasePanel:Ae=>Oe(Ae),onSyncScene:()=>{var Ae,Je;(Ae=Ye.current)==null||Ae.syncAreas(),(Je=Ye.current)==null||Je.syncAgents(Array.from(H.getState().agents.values()))}})]})}function $q(){return o.jsx(PL,{children:o.jsx(GL,{children:o.jsx(zq,{})})})}class Hq extends b.Component{constructor(n){super(n);et(this,"handleReload",()=>{window.location.reload()});et(this,"handleDismiss",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(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:"💥"}),En.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:En.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:En.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:En.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:En.t("common:buttons.tryToContinue")})]}),o.jsx("div",{style:{marginTop:"24px",color:"#666",fontSize:"12px"},children:En.t("errors:crash.checkConsole")})]})})}return this.props.children}}S6();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 LT=document.getElementById("app");if(!LT)throw new Error("Could not find #app container");const Uq=jM.createRoot(LT);Uq.render(o.jsx(Ce.StrictMode,{children:o.jsx(b.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(Hq,{children:o.jsx($q,{})})})}));console.log("[Tide] Tide Commander initialized");export{Lc as $,FL as A,Uj as B,Vn as C,BL as D,GD as E,AV as F,xp as G,Jb as H,Dl as I,hx as J,rr as K,fx as L,pL as M,Aa as N,aV as O,zL as P,TV as Q,YU as R,ft as S,ls as T,wa as U,yV as V,Lt as W,Qj as X,NV as Y,$2 as Z,ou as _,xx as a,go as a$,nf as a0,fg as a1,er as a2,Sp as a3,xV as a4,dx as a5,Wf as a6,Kq as a7,IL as a8,mb as a9,_p as aA,VD as aB,Q5 as aC,N6 as aD,T6 as aE,D6 as aF,oV as aG,Dj as aH,cV as aI,uV as aJ,ex as aK,tx as aL,jf as aM,EV as aN,vt as aO,i1 as aP,jV as aQ,o1 as aR,l1 as aS,du as aT,Rr as aU,Or as aV,L6 as aW,P6 as aX,qj as aY,Yg as aZ,I6 as a_,hV as aa,Ti as ab,Yq as ac,dV as ad,Xx as ae,Zs as af,fu as ag,up as ah,Ca as ai,or as aj,nx as ak,KD as al,En as am,UR as an,YD as ao,mV as ap,gV as aq,bV as ar,pV as as,zj as at,Hk as au,sV as av,Rj as aw,Qt as ax,x5 as ay,uT as az,wL as b,zp as b0,r1 as b1,ra as b2,f1 as b3,z6 as b4,Jx as b5,Fb as b6,z4 as b7,Bj as b8,Sb as b9,rV as ba,iV as bb,bO as bc,xO as bd,z2 as be,nV as bf,eV as bg,lV as bh,kp as bi,t2 as bj,P2 as bk,B2 as bl,vV as bm,_u as bn,Tu as bo,$L as bp,wV as bq,CV as br,kV as bs,tV as bt,Zq as bu,SV as bv,WR as bw,qR as bx,Dc as by,sx as bz,fV as c,kL as d,Qx as e,ws as f,KU as g,ka as h,Sl as i,o as j,$f as k,_t as l,nS as m,kn as n,na as o,Xq as p,Qq as q,b as r,H as s,Xd as t,pt as u,vp as v,Jq as w,QR as x,XR as y,Ce as z};
|
|
152
|
+
`):[],[y]),S=b.useMemo(()=>v.map(A=>Sl(A||" ")),[v]),C=b.useMemo(()=>x?f&&!y?"No log lines match the current filter.":null:"Waiting for logs...",[x,f,y]),k=f1({count:S.length,getScrollElement:()=>i.current,estimateSize:()=>20,overscan:12,measureElement:A=>A.getBoundingClientRect().height}),N=k.getVirtualItems();return o.jsx("div",{ref:i,className:"guake-bottom-pm2-logs",onScroll:m,children:C?o.jsx("div",{className:"guake-bottom-pm2-logs-empty",children:C}):o.jsx("div",{className:"guake-bottom-pm2-logs-inner",style:{height:k.getTotalSize()},children:N.map(A=>o.jsx("div",{ref:k.measureElement,className:"guake-bottom-pm2-log-line","data-index":A.index,style:{transform:`translateY(${A.start}px)`},dangerouslySetInnerHTML:{__html:S[A.index]}},A.key))})})});b.memo(function({src:e,title:n}){const s=b.useRef(null),[a,r]=b.useState(!1),[i,c]=b.useState(null);b.useEffect(()=>{r(!1),c(null);const h=setTimeout(()=>c(e),400);return()=>clearTimeout(h)},[e]);const d=b.useCallback(()=>{var m;const h=s.current;if(h){document.activeElement===h&&h.blur();try{(m=h.contentWindow)==null||m.blur()}catch{}}},[]),f=b.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 b.useEffect(()=>{if(!i)return;const h=Date.now(),m=()=>{Date.now()-h>1500||(d(),f())};return window.addEventListener("focus",m,!0),document.addEventListener("focusin",m,!0),()=>{window.removeEventListener("focus",m,!0),document.removeEventListener("focusin",m,!0)}},[f,d,i]),o.jsxs(o.Fragment,{children:[!a&&o.jsx("div",{className:"guake-bottom-terminal-starting",children:o.jsx("span",{children:"Loading terminal..."})}),o.jsx("iframe",{ref:s,src:i??void 0,className:`guake-bottom-terminal-iframe${a?"":" iframe-loading"}`,title:n,allow:"clipboard-read; clipboard-write",loading:"lazy",tabIndex:-1,onLoad:()=>{r(!0),d(),f()}})]})});const NW=b.memo(function({onSaveSnapshot:e}={}){var dr,$l,So,Hl,Yr,la,Co,Kr,Ea,Ao,Di,Ul,Ri;const{t:n}=pt(["terminal","common"]),s=Dl(),a=fx(),r=Pj(),i=Ij(),c=mx(),d=gx(),f=SL(),h=!!f,m=b.useMemo(()=>f?{id:f.agentId,name:f.agentName,class:f.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:f.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:f.createdAt,lastActivity:f.createdAt}:null,[f]),x=Array.from(a),v=x.length===1?x[0]:null,C=(dx(v)||null)??(h?m:null),k=v??(h?(f==null?void 0:f.agentId)??null:null),N=_L(),A=rr(),E=hx(),D=b.useMemo(()=>{if(!k)return null;const Z=new Set,Te=[];for(const We of A.values())We.archived||We.directories.length===0||We.assignedAgentIds.includes(k)&&(Z.add(We.id),Te.push(We));const le=s.get(k);if(le)for(const We of A.values())We.archived||We.directories.length===0||Z.has(We.id)||CW({x:le.position.x,z:le.position.z},We)&&(Z.add(We.id),Te.push(We));return Te.length===0?null:Te.flatMap(We=>We.directories.filter(gt=>gt&>.trim().length>0).map(gt=>({areaId:We.id,areaName:We.name,dir:gt})))},[k,A,s]),_=b.useMemo(()=>{var le;if(!k)return[];const Z=H.getAreaForAgent(k);if(!Z)return[];const Te=[];for(const We of E.values())We.type==="terminal"&&H.isPositionInArea(We.position,Z)&&Te.push({id:We.id,name:We.name,hasUrl:!!((le=We.terminalStatus)!=null&&le.url)});return Te},[k,E,A]),I=b.useMemo(()=>{var le;if(!k)return[];const Z=H.getAreaForAgent(k);if(!Z)return[];const Te=[];for(const We of E.values())We.type==="server"&&((le=We.pm2)!=null&&le.enabled)&&H.isPositionInArea(We.position,Z)&&Te.push({id:We.id,name:We.name});return Te},[k,E,A]),O=b.useMemo(()=>{if(!k)return[];const Z=H.getAreaForAgent(k);if(!Z)return[];const Te=[];for(const le of E.values())le.type==="database"&&le.database&&H.isPositionInArea(le.position,Z)&&Te.push({id:le.id,name:le.name});return Te},[k,E,A]),{branches:T,fetchRemote:M,fetchingDirs:R}=a6(D),{terminalHeight:P,terminalRef:U,handleResizeStart:q}=JU(),{mobileOverviewHeight:z,handleResizeMouseDown:F,handleResizeTouchStart:$}=t6(),V=XU(),[G,B]=b.useState(()=>{const Z=ex(ft.SIDE_PANEL_WIDTH,420);return Math.max(280,Math.min(700,Z))}),Q=b.useRef(null),K=b.useCallback((Z,Te)=>{Z.preventDefault(),Q.current={startX:Z.clientX,startW:G},document.body.style.cursor="ew-resize",document.body.style.userSelect="none",H.setTerminalResizing(!0);let le=G;const We=Tt=>{if(!Q.current)return;const Cn=Tt.clientX-Q.current.startX,tn=Te==="left"?-Cn:Cn;le=Math.max(280,Math.min(700,Q.current.startW+tn)),B(le)},gt=()=>{Q.current=null,document.body.style.cursor="",document.body.style.userSelect="",H.setTerminalResizing(!1),document.removeEventListener("mousemove",We),document.removeEventListener("mouseup",gt),tx(ft.SIDE_PANEL_WIDTH,le)};document.addEventListener("mousemove",We),document.addEventListener("mouseup",gt)},[G]),W=b.useRef(null),be=b.useRef(null),[fe,J]=b.useState(()=>{const Z=wa(ft.VIEW_MODE);return Z==="simple"||Z==="chat"||Z==="advanced"?Z:wa(ft.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[xe,je]=b.useState(()=>_r(ft.TERMINAL_FULLSCREEN,!1)),[oe,Ee]=b.useState(null),[Fe,Ve]=b.useState(null),[De,ge]=b.useState(null),[Oe,te]=b.useState(null),[$e,se]=b.useState(!1);Qt("guake-image-modal",oe!==null,()=>Ee(null)),Qt("guake-bash-modal",Fe!==null,()=>Ve(null)),Qt("guake-response-modal",Oe!==null,()=>te(null)),Qt("guake-context-confirm",De!==null,()=>ge(null)),Qt("guake-agent-info",$e,()=>se(!1));const[Ne,_e]=b.useState(!1),[pe,Ge]=b.useState(()=>ms.isEnabled()),[it,dt]=b.useState(()=>_r(ft.GIT_PANEL_OPEN,!1)),ce=b.useCallback(Z=>{dt(Z),Qa(ft.GIT_PANEL_OPEN,Z)},[]),[X,ne]=b.useState(()=>_r(ft.BUILDINGS_PANEL_OPEN,!1)),ke=b.useCallback(Z=>{ne(Z),Qa(ft.BUILDINGS_PANEL_OPEN,Z)},[]),[ee,ye]=b.useState(()=>_r(ft.WORKFLOW_PANEL_OPEN,!1)),Ie=b.useCallback(Z=>{ye(Z),Qa(ft.WORKFLOW_PANEL_OPEN,Z)},[]),[He,ue]=b.useState(!1);b.useEffect(()=>{if(!k){ue(!1);return}let Z=!1;return(async()=>{try{const Te=await Lt(_t("/api/workflows/definitions"));if(Z||!Te.ok)return;const We=(await Te.json()).some(gt=>gt.states.some(Tt=>{var Cn,tn;return((Cn=Tt.action)==null?void 0:Cn.type)==="agent_task"&&((tn=Tt.action)==null?void 0:tn.agentId)===k}));Z||ue(We)}catch{Z||ue(!1)}})(),()=>{Z=!0}},[k]);const de=EL(),re=b.useCallback(Z=>H.setOverviewPanelOpen(Z),[]),[me,ve]=b.useState([]),[Ue,Qe]=b.useState({}),[ze,nt]=b.useState(()=>Ej()),[ot,st]=b.useState(()=>{try{return localStorage.getItem("tide:bottom-split-direction")==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[lt,rt]=b.useState(()=>{try{const Z=localStorage.getItem("tide:bottom-terminal-height");return Z?Math.max(120,Math.min(600,Number(Z))):250}catch{return 250}}),ht=b.useRef(null),[jt,he]=b.useState([1]),Me=b.useRef(null),Ye=b.useRef(null),[tt,Nt]=b.useState(null),[zt,Pt]=b.useState(null),It=b.useMemo(()=>me.filter(Z=>Z.areaId===zt),[me,zt]),Vt=b.useMemo(()=>new Set(It.map(Z=>Z.buildingId)),[It]),mt=b.useRef(new Map);b.useEffect(()=>{try{const Z=localStorage.getItem("tide:bottom-panels-v2");if(Z){const Te=JSON.parse(Z);mt.current=new Map(Te.map(([le,We])=>[le,We.map(gt=>({id:gt.id??wf(),type:gt.type,buildingId:gt.buildingId}))]))}else{const Te=localStorage.getItem("tide:bottom-terminals");if(Te){const le=JSON.parse(Te);for(const[We,gt]of le)mt.current.set(We,[{id:wf(),type:"terminal",buildingId:gt}])}}}catch{}},[]);const ct=b.useCallback(Z=>{if(!k)return;const Te=H.getAreaForAgent(k);if(Te)try{Z.length>0?mt.current.set(Te.id,Z.map(We=>({id:We.id,type:We.type,buildingId:We.buildingId}))):mt.current.delete(Te.id);const le=Array.from(mt.current.entries());localStorage.setItem("tide:bottom-panels-v2",JSON.stringify(le))}catch{}},[k]),xt=b.useCallback(()=>{if(!k)return null;const Z=H.getAreaForAgent(k);return(Z==null?void 0:Z.id)??null},[k]),Dt=b.useCallback((Z,Te)=>{const le=xt();Qe({}),ve(We=>{for(const tn of We)tn.areaId===le&&tn.type==="pm2-logs"&&H.stopLogStreaming(tn.buildingId);const gt=We.filter(tn=>tn.areaId!==le),Tt={id:wf(),type:Te,buildingId:Z,areaId:le??void 0},Cn=[...gt,Tt];return ct([Tt]),Cn})},[ct,xt]),Sn=b.useCallback((Z,Te,le)=>{const We=xt();st(le);try{localStorage.setItem("tide:bottom-split-direction",le)}catch{}ve(gt=>{const Tt=gt.filter($n=>$n.areaId===We);if(Tt.length>=4||Tt.some($n=>$n.buildingId===Z))return gt;const Cn={id:wf(),type:Te,buildingId:Z,areaId:We??void 0},tn=[...gt,Cn];return ct(Tt.concat(Cn)),tn})},[ct,xt]),cn=b.useCallback(Z=>{Qe(Te=>{if(!(Z in Te))return Te;const le={...Te};return delete le[Z],le}),ve(Te=>{const le=Te.find(Tt=>Tt.id===Z);(le==null?void 0:le.type)==="pm2-logs"&&H.stopLogStreaming(le.buildingId);const We=Te.filter(Tt=>Tt.id!==Z),gt=le==null?void 0:le.areaId;return gt&&ct(We.filter(Tt=>Tt.areaId===gt)),We})},[ct]);b.useCallback(()=>{Qe({}),ve(Z=>{for(const Te of Z)Te.type==="pm2-logs"&&H.stopLogStreaming(Te.buildingId);return ct([]),[]})},[ct]),b.useEffect(()=>{if(!k){Pt(null);return}const Z=H.getAreaForAgent(k);if(!Z){Pt(null);return}Pt(Z.id),ve(Te=>{if(Te.filter(Tt=>Tt.areaId===Z.id).length>0)return Te;const We=mt.current.get(Z.id);if(!We||We.length===0)return Te;const gt=We.map(Tt=>({id:Tt.id,type:Tt.type,buildingId:Tt.buildingId,areaId:Z.id}));return[...Te,...gt]})},[k]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&Dt(le.buildingId,"terminal")};return window.addEventListener("tide:open-bottom-terminal",Z),()=>window.removeEventListener("tide:open-bottom-terminal",Z)},[Dt]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&Dt(le.buildingId,"pm2-logs")};return window.addEventListener("tide:open-bottom-pm2-logs",Z),()=>window.removeEventListener("tide:open-bottom-pm2-logs",Z)},[Dt]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&Dt(le.buildingId,"database")};return window.addEventListener("tide:open-bottom-database",Z),()=>window.removeEventListener("tide:open-bottom-database",Z)},[Dt]),b.useEffect(()=>{const Z=Te=>{const le=Te.detail;le!=null&&le.buildingId&&(le!=null&&le.type)&&(le!=null&&le.direction)&&(It.length===0?Dt(le.buildingId,le.type):Sn(le.buildingId,le.type,le.direction))};return window.addEventListener("tide:split-bottom-panel",Z),()=>window.removeEventListener("tide:split-bottom-panel",Z)},[It.length,Dt,Sn]),b.useEffect(()=>{he(Z=>Z.length===It.length?Z:It.length<=1?[1]:(It.length>Z.length,Array(It.length).fill(1)))},[It.length]);const cs=b.useCallback((Z,Te)=>{var $n;Z.preventDefault();const le=ot==="horizontal";Me.current={index:Te,startPos:le?Z.clientX:Z.clientY,startRatios:[...jt]},document.body.style.cursor=le?"col-resize":"row-resize",document.body.style.userSelect="none";const We=($n=Ye.current)==null?void 0:$n.querySelectorAll("iframe");We==null||We.forEach(ts=>ts.style.pointerEvents="none");const gt=Ye.current,Tt=gt?le?gt.offsetWidth:gt.offsetHeight:1,Cn=ts=>{const Ds=Me.current;if(!Ds||!gt)return;const Up=(le?ts.clientX:ts.clientY)-Ds.startPos,Hu=Ds.startRatios.reduce((Wp,qp)=>Wp+qp,0),Uu=Up/Tt*Hu,Oi=[...Ds.startRatios],Wu=.1*Hu;Oi[Te]=Math.max(Wu,Ds.startRatios[Te]+Uu),Oi[Te+1]=Math.max(Wu,Ds.startRatios[Te+1]-Uu),he(Oi)},tn=()=>{Me.current=null,document.body.style.cursor="",document.body.style.userSelect="",We==null||We.forEach(ts=>ts.style.pointerEvents=""),document.removeEventListener("mousemove",Cn),document.removeEventListener("mouseup",tn)};document.addEventListener("mousemove",Cn),document.addEventListener("mouseup",tn)},[ot,jt]),Ba=b.useRef(new Set);b.useEffect(()=>{const Z=new Set(me.filter(Te=>Te.type==="pm2-logs").map(Te=>Te.buildingId));for(const Te of Z)Ba.current.has(Te)||H.startLogStreaming(Te,200);Ba.current=Z},[me]);const Es=b.useRef(new Set);b.useEffect(()=>{var le;const Z=me.filter(We=>We.type==="terminal");for(const We of Z){const gt=E.get(We.buildingId);!!((le=gt==null?void 0:gt.terminalStatus)!=null&&le.url)?Es.current.add(We.buildingId):Es.current.has(We.buildingId)&&(Es.current.delete(We.buildingId),cn(We.id))}const Te=new Set(Z.map(We=>We.buildingId));for(const We of Es.current)Te.has(We)||Es.current.delete(We)},[me,E,cn]);const Us=b.useCallback(Z=>{Z.preventDefault(),ht.current={startY:Z.clientY,startH:lt};let Te=lt;const le=gt=>{if(!ht.current)return;const Tt=ht.current.startY-gt.clientY;Te=Math.max(120,Math.min(600,ht.current.startH+Tt)),rt(Te)},We=()=>{ht.current=null,document.removeEventListener("mousemove",le),document.removeEventListener("mouseup",We);try{localStorage.setItem("tide:bottom-terminal-height",String(Te))}catch{}};document.addEventListener("mousemove",le),document.addEventListener("mouseup",We)},[lt]),[Fa,Ss]=b.useState(!1),es=b.useRef(0),Mt=r&&C!==null,is=b.useRef([]),fn=b.useRef(-1),ur=b.useRef(!1),Ur=b.useRef(!1),_s=b.useRef(!1),Ms=b.useRef(null),[_i,wo]=b.useState(!1),[Wr,Il]=b.useState(!1),bs=b.useCallback(()=>{const Z=is.current,Te=fn.current;wo(Te>0),Il(Te>=0&&Te<Z.length-1)},[]),ja=b.useCallback(Z=>{const Te=is.current;if(Te.length===0)return;let le=fn.current+Z;for(;le>=0&&le<Te.length;){const We=Te[le];if(s.has(We)){ur.current=!0,fn.current=le,bs(),H.selectAgent(We);return}le+=Z}},[s,bs]),us=b.useCallback(()=>{ja(-1)},[ja]),Gn=b.useCallback(()=>{ja(1)},[ja]),qr=b.useCallback((Z,Te)=>{if(typeof window>"u")return;const le=window.history.state,gt={...typeof le=="object"&&le!==null?le:{},__guakeAgentNav:{agentId:Z}};Te==="replace"?window.history.replaceState(gt,"",window.location.href):window.history.pushState(gt,"",window.location.href)},[]),Ae=b.useCallback(()=>{je(Z=>{const Te=!Z;return Qa(ft.TERMINAL_FULLSCREEN,Te),Te})},[]),Je=n6({agents:s,selectedAgentId:k,isOpen:Mt,overviewPanelOpen:de,loadingHistory:((dr=W.current)==null?void 0:dr.historyLoader.fetchingHistory)??!1,hasModalOpen:!!(oe||Fe||Oe||c||d),outputRef:(($l=W.current)==null?void 0:$l.outputScrollRef)??{current:null}});b.useEffect(()=>{const Z=U.current;if(!Z||!Mt)return;const Te=We=>{We.button===3?(We.preventDefault(),We.stopPropagation(),us()):We.button===4&&(We.preventDefault(),We.stopPropagation(),Gn())},le=We=>{(We.button===3||We.button===4)&&We.preventDefault()};return Z.addEventListener("mouseup",Te),Z.addEventListener("mousedown",le),()=>{Z.removeEventListener("mouseup",Te),Z.removeEventListener("mousedown",le)}},[Mt,us,Gn]);const Ct=b.useCallback(Z=>{H.setLastSelectionViaDirectClick(!0),H.selectAgent(Z)},[]),en=typeof window<"u"&&window.innerWidth<=768&&de&&Mt,Ln=aR({gestureRef:((So=W.current)==null?void 0:So.outputScrollRef)??{current:null},agentListRef:be,enabled:en,onSelect:Ct});b.useEffect(()=>{Ne&&!pe&&(Ge(!0),ms.setEnabled(!0))},[Ne,pe]),b.useEffect(()=>{Mt||se(!1)},[Mt]),b.useEffect(()=>{var Te;if(!(Fe!=null&&Fe.isLive)||!Fe.command)return;const Z=((Te=W.current)==null?void 0:Te.getDedupedHistory())??[];for(const le of Z)if(le._bashCommand===Fe.command&&le._bashOutput){Ve({command:Fe.command,output:le._bashOutput,isLive:!1});return}},[Fe]);const $t=b.useCallback((Z,Te)=>{Ee({url:Z,name:Te})},[]),At=b.useCallback((Z,Te)=>{const le=_p(Z,C==null?void 0:C.cwd),We=le.line?{...Te||{},targetLine:le.line}:Te;H.setFileViewerPath(le.path,We,C==null?void 0:C.cwd)},[C==null?void 0:C.cwd]),Nn=b.useCallback((Z,Te)=>{Ve({command:Z,output:Te,isLive:Te==="Running..."})},[]),Cs=b.useCallback(Z=>{te(Z)},[]),Pn=b.useCallback(()=>{se(Z=>!Z)},[]),[Ws,Na]=b.useState(0),[oa,Bl]=b.useState(!1),Fu=b.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(Bl(!0),Na(kW),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),setTimeout(()=>{H.setMobileView("3d"),Bl(!1),Na(0)},SW))},[]),zu=b.useCallback(Z=>{oa||Na(Z)},[oa]);b.useEffect(()=>{Na(0),Bl(!1)},[k]),b.useEffect(()=>{if(!k){is.current=[],fn.current=-1,bs(),_s.current=!1,Ms.current=null;return}const Z=is.current;if(ur.current){ur.current=!1,bs();return}const Te=fn.current;if(Te>=0&&Z[Te]===k){bs();return}const le=Te<Z.length-1?Z.slice(0,Te+1):Z.slice();le.push(k),le.length>100&&le.shift(),is.current=le,fn.current=le.length-1,bs()},[k,bs]),b.useEffect(()=>{if(!(!Mt||!k)){if(!_s.current){qr(k,"replace"),_s.current=!0,Ms.current=k;return}if(Ur.current){Ur.current=!1,Ms.current=k;return}Ms.current!==k&&(qr(k,"push"),Ms.current=k)}},[Mt,k,qr]),b.useEffect(()=>{if(!Mt)return;const Z=Te=>{var Tt,Cn;const le=(Cn=(Tt=Te.state)==null?void 0:Tt.__guakeAgentNav)==null?void 0:Cn.agentId;if(!le||typeof le!="string"||!s.has(le)||le===v)return;Ur.current=!0,ur.current=!0;const We=is.current,gt=We.lastIndexOf(le);gt>=0?fn.current=gt:(We.push(le),fn.current=We.length-1),bs(),H.selectAgent(le)};return window.addEventListener("popstate",Z),()=>window.removeEventListener("popstate",Z)},[Mt,s,v,bs]),b.useEffect(()=>{Mt&&v&&H.clearUnseenForAgent(v)},[Mt,v]);const ko=b.useRef(null);b.useLayoutEffect(()=>{const Z=ko.current;Z!==null&&Z!==v&&H.getState().currentSnapshot&&H.setCurrentSnapshot(null),ko.current=v},[v]),b.useEffect(()=>{const Z=Te=>{if(Te.key==="`"&&!Te.ctrlKey&&!Te.altKey&&C){const le=Te.target;le.tagName!=="INPUT"&&le.tagName!=="TEXTAREA"&&(Te.preventDefault(),H.toggleTerminal())}};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[C]),b.useEffect(()=>{if(!Mt)return;const Z=Te=>{Te.altKey&&(Te.key!=="ArrowLeft"&&Te.key!=="ArrowRight"||(Te.key==="ArrowLeft"&&_i?(Te.preventDefault(),us()):Te.key==="ArrowRight"&&Wr&&(Te.preventDefault(),Gn())))};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[Mt,_i,Wr,us,Gn]),b.useEffect(()=>{const Z=Te=>{var le;Te.key==="Escape"&&(c?(Te.stopImmediatePropagation(),H.clearFileViewerPath()):d?(Te.stopImmediatePropagation(),H.closeContextModal()):Oe?(Te.stopImmediatePropagation(),te(null)):Fe?(Te.stopImmediatePropagation(),Ve(null)):oe?(Te.stopImmediatePropagation(),Ee(null)):(le=W.current)!=null&&le.search.searchMode&&(Te.stopImmediatePropagation(),W.current.search.closeSearch()))};return document.addEventListener("keydown",Z,!0),()=>document.removeEventListener("keydown",Z,!0)},[oe,Fe,Oe,c,d]);const $u=b.useRef(Mt),Mi=b.useRef(!1);b.useEffect(()=>{$u.current=Mt},[Mt]),b.useEffect(()=>{if(window.innerWidth<=768)return;const Te=gt=>{var $n;if(!(gt instanceof Element))return!1;const Tt=($n=U.current)==null?void 0:$n.contains(gt),Cn=gt.closest(".agent-bar"),tn=!!gt.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!!Tt||!!Cn||tn},le=gt=>{if(!$u.current){Mi.current=!1;return}if(eR("terminal")){Mi.current=!1;return}Mi.current=!Te(gt.target)},We=gt=>{Mi.current&&(Te(gt.target)||H.setTerminalOpen(!1),Mi.current=!1)};return document.addEventListener("mousedown",le,!0),document.addEventListener("mouseup",We,!0),()=>{document.removeEventListener("mousedown",le,!0),document.removeEventListener("mouseup",We,!0)}},[]),b.useEffect(()=>{const Z=()=>{document.hidden&&V.cleanup()};return document.addEventListener("visibilitychange",Z),()=>document.removeEventListener("visibilitychange",Z)},[V]),b.useEffect(()=>()=>V.cleanup(),[k,V]);const Vr=typeof window<"u"&&window.innerWidth<=768;if(!C)return Vr&&i==="terminal"&&a.size===0?o.jsx("div",{ref:U,className:`guake-terminal open ${xe?"fullscreen":""}`,style:{"--terminal-height":`${P}%`},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")})]})})})}):Vr&&i==="terminal"&&a.size>0?o.jsx("div",{ref:U,className:`guake-terminal open ${xe?"fullscreen":""}`,style:{"--terminal-height":`${P}%`},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(!k)return null;const Ta=Z=>{Z.preventDefault(),Z.stopPropagation(),es.current++,Z.dataTransfer.types.includes("Files")&&Ss(!0)},Fl=Z=>{Z.preventDefault(),Z.stopPropagation()},zl=Z=>{Z.preventDefault(),Z.stopPropagation(),es.current--,es.current===0&&Ss(!1)},Gr=async Z=>{var le,We;Z.preventDefault(),Z.stopPropagation(),es.current=0,Ss(!1);const Te=Z.dataTransfer.files;if(Te.length)for(const gt of Te){const Tt=await((le=W.current)==null?void 0:le.terminalInput.uploadFile(gt));Tt&&((We=W.current)==null||We.terminalInput.setAttachedFiles(Cn=>[...Cn,Tt]))}};return o.jsxs("div",{ref:U,className:`guake-terminal ${Mt?"open":"collapsed"} ${xe&&Mt?"fullscreen":""} ${Ne&&Mt?"with-debug-panel":""} ${it&&Mt?"with-git-panel":""} ${X&&Mt?"with-buildings-panel":""} ${ee&&Mt?"with-workflow-panel":""} ${N&&Mt?"with-tracking-board":""} ${de&&Mt?"with-overview-panel":""} ${Fa?"drag-over":""} ${Ws>0?"mobile-swipe-close-active":""} ${oa?"mobile-swipe-close-closing":""}`,style:{"--terminal-height":`${P}%`,"--mobile-swipe-close-offset":`${Ws}px`,"--guake-side-panel-width":`${G}px`,...z>0?{"--guake-mobile-overview-height":`${z}px`}:{}},onDragEnter:Ta,onDragOver:Fl,onDragLeave:zl,onDrop:Gr,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")})]}),!h&&Ne&&Mt&&k&&o.jsx(O6,{agentId:k,onClose:()=>_e(!1)}),!h&&it&&Mt&&k&&o.jsx(G6,{agentId:k,agents:s,onClose:()=>ce(!1),branchInfoMap:T,fetchRemote:M,fetchingDirs:R}),!h&&X&&Mt&&k&&o.jsx(rW,{agentId:k,onClose:()=>ke(!1)}),!h&&ee&&Mt&&k&&o.jsx(lW,{agentId:k,onClose:()=>Ie(!1)}),!h&&N&&Mt&&k&&o.jsxs("div",{className:"guake-tracking-board-panel",children:[o.jsxs("div",{className:"guake-tracking-board-header",children:[o.jsxs("div",{className:"guake-tracking-board-title",children:[o.jsx("span",{className:"guake-tracking-board-icon",children:"▥"}),o.jsx("span",{children:"Tracking Board"})]}),o.jsx("button",{type:"button",className:"guake-tracking-board-close",onClick:()=>H.setTrackingBoardVisible(!1),title:"Close tracking board",children:"✕"})]}),o.jsx("div",{className:"guake-tracking-board-body",children:o.jsx(vW,{activeAgentId:k,onSelectAgent:Z=>{H.setLastSelectionViaDirectClick(!0),H.selectAgent(Z)}})})]}),!h&&(Ne||it||X||ee||N)&&Mt&&o.jsx("div",{className:"guake-side-panel-resize right",onMouseDown:Z=>K(Z,"right")}),!h&&de&&Mt&&k&&o.jsx(d5,{activeAgentId:k,onClose:()=>re(!1),onSelectAgent:Z=>{H.setLastSelectionViaDirectClick(!0),H.selectAgent(Z)},agentListRef:be,twoFingerState:Ln}),!h&&de&&Mt&&k&&o.jsx("div",{className:"guake-side-panel-resize left",onMouseDown:Z=>K(Z,"left")}),!h&&de&&Mt&&k&&o.jsx("div",{className:"aop-resize-handle",onMouseDown:F,onTouchStart:$}),o.jsxs("div",{className:"guake-content",children:[o.jsx(C6,{selectedAgent:C,selectedAgentId:k,sortedAgents:Je.sortedAgents,swipeOffset:Je.swipeOffset,viewMode:fe,setViewMode:J,searchMode:((Hl=W.current)==null?void 0:Hl.search.searchMode)??!1,toggleSearch:((Yr=W.current)==null?void 0:Yr.search.toggleSearch)??(()=>{}),closeSearch:((la=W.current)==null?void 0:la.search.closeSearch)??(()=>{}),debugPanelOpen:Ne,setDebugPanelOpen:_e,debuggerEnabled:pe,setDebuggerEnabled:Ge,gitPanelOpen:it,setGitPanelOpen:ce,buildingsPanelOpen:X,setBuildingsPanelOpen:ke,workflowPanelOpen:ee,setWorkflowPanelOpen:Ie,hasWorkflow:He,trackingBoardVisible:N,setTrackingBoardVisible:Z=>H.setTrackingBoardVisible(Z),overviewPanelOpen:de,setOverviewPanelOpen:re,agentInfoOpen:$e,onToggleAgentInfo:Pn,isFullscreen:xe,onToggleFullscreen:Ae,onNavigateBack:us,onNavigateForward:Gn,canNavigateBack:_i,canNavigateForward:Wr,outputsLength:((Co=W.current)==null?void 0:Co.outputsLength)??0,setContextConfirm:ge,headerRef:Je.headerRef,onSaveSnapshot:h?void 0:e,isSnapshotView:h}),o.jsxs("div",{className:`guake-swipe-container ${Je.swipeAnimationClass}`,style:Je.swipeOffset!==0?{transform:`translateX(${Je.swipeOffset*40}%)`}:void 0,children:[Je.sortedAgents.length>1&&Je.swipeOffset!==0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`swipe-indicator left ${Je.swipeOffset>.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-icon",children:"←"}),o.jsx("span",{className:"indicator-name",children:(Kr=Je.nextAgent)==null?void 0:Kr.name})]}),o.jsxs("div",{className:`swipe-indicator right ${Je.swipeOffset<-.3?"visible":""}`,children:[o.jsx("span",{className:"indicator-name",children:(Ea=Je.prevAgent)==null?void 0:Ea.name}),o.jsx("span",{className:"indicator-icon",children:"→"})]})]}),Je.sortedAgents.length>1&&Je.sortedAgents.length<=8&&Je.swipeOffset!==0&&o.jsx("div",{className:`swipe-dots ${Math.abs(Je.swipeOffset)>.1?"visible":""}`,children:Je.sortedAgents.map((Z,Te)=>o.jsx("div",{className:`swipe-dot ${Te===Je.currentAgentIndex?"active":""}`},Z.id))}),o.jsx(sW,{activeAgentId:k,activeAgent:C,paneRef:W,viewMode:fe,isOpen:Mt,isSnapshotView:h,currentSnapshot:f,onImageClick:$t,onFileClick:At,onBashClick:Nn,onViewMarkdown:Cs,keyboard:V,onSaveSnapshot:h?void 0:e,canSwipeClose:Vr&&i==="terminal"&&!((Ao=W.current)!=null&&Ao.search.searchMode)&&!((Di=W.current)!=null&&Di.historyLoader.fetchingHistory),onSwipeCloseOffsetChange:zu,onSwipeClose:Fu,hasModalOpen:!!(oe||Fe||Oe||c)})]}),o.jsxs("div",{className:"guake-agent-status-bar",children:[!h&&(C==null?void 0:C.isDetached)&&o.jsx(Zn,{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")]})}),(C==null?void 0:C.cwd)&&o.jsxs("span",{className:"guake-agent-cwd",title:C.cwd,children:["📁 ",C.cwd.split("/").filter(Boolean).slice(-2).join("/")||C.cwd]}),D&&D.map(({areaId:Z,areaName:Te,dir:le})=>{const We=T.get(le),gt=R.has(le);return o.jsxs("span",{className:"guake-agent-area-dir",title:`${Te}: ${le}${We?` (${We.branch}${We.ahead?` ↑${We.ahead}`:""}${We.behind?` ↓${We.behind}`:""})`:""}`,onClick:()=>H.openFileExplorerForAreaFolder(Z,le),children:["📂 ",le.split("/").filter(Boolean).pop()||le,We&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"guake-agent-area-branch",children:[" ⎇ ",We.branch]}),We.ahead>0&&o.jsxs("span",{className:"guake-branch-ahead",title:`${We.ahead} ahead`,children:["↑",We.ahead]}),We.behind>0&&o.jsxs("span",{className:"guake-branch-behind",title:`${We.behind} behind`,children:["↓",We.behind]}),o.jsx("span",{className:`guake-area-fetch-btn ${gt?"fetching":""}`,title:"Git fetch",onClick:Tt=>{Tt.stopPropagation(),M(le)},children:gt?"⏳":"⇣"})]})]},`${Z}:${le}`)}),!h&&C&&(()=>{const Z=C.contextStats,Te=!!Z,le=Z?Z.totalTokens:C.contextUsed||0,We=Z?Z.contextWindow:C.contextLimit||2e5,gt=Z?Z.usedPercent:Math.round(le/We*100),Tt=Math.max(0,Math.min(100,gt)),Cn=Math.max(0,100-Tt),tn=Tt>=80?"#ff4a4a":Tt>=60?"#ff9e4a":Tt>=40?"#ffd700":"#4aff9e",$n=(le/1e3).toFixed(1),ts=(We/1e3).toFixed(1);return o.jsxs("span",{className:"guake-agent-context",onClick:()=>H.setContextModalAgentId(k),title:n(Te?"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,Tt)}%`,backgroundColor:tn}})}),o.jsxs("span",{className:"context-tokens",style:{color:tn},children:[$n,"k/",ts,"k"]}),o.jsxs("span",{className:"context-free",children:["(",n("terminal:context.percentFree",{percent:Cn}),")"]}),!Te&&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(Z=>{const Te=Vt.has(Z.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""} ${Z.hasUrl?"":"offline"}`,title:`${Te?"Hide":"Show"} terminal: ${Z.name}${Z.hasUrl?"":" (starting...)"}`,onClick:()=>{if(Te){const le=me.find(We=>We.buildingId===Z.id);le&&cn(le.id)}else Z.hasUrl||H.sendBuildingCommand(Z.id,"start"),Dt(Z.id,"terminal")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Vt.has(Z.id)||Nt({position:{x:le.clientX,y:le.clientY},buildingId:Z.id,type:"terminal"})},children:"💻"},Z.id)})}),I.length>0&&o.jsx("span",{className:"guake-status-terminals",children:I.map(Z=>{const Te=Vt.has(Z.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} logs: ${Z.name}`,onClick:()=>{if(Te){const le=me.find(We=>We.buildingId===Z.id);le&&cn(le.id)}else Dt(Z.id,"pm2-logs")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Vt.has(Z.id)||Nt({position:{x:le.clientX,y:le.clientY},buildingId:Z.id,type:"pm2-logs"})},children:"📜"},Z.id)})}),O.length>0&&o.jsx("span",{className:"guake-status-terminals",children:O.map(Z=>{const Te=Vt.has(Z.id);return o.jsx("button",{className:`guake-status-terminal-btn ${Te?"active":""}`,title:`${Te?"Hide":"Show"} database: ${Z.name}`,onClick:()=>{if(Te){const le=me.find(We=>We.buildingId===Z.id);le&&cn(le.id)}else Dt(Z.id,"database")},onContextMenu:le=>{le.preventDefault(),le.stopPropagation(),Vt.has(Z.id)||Nt({position:{x:le.clientX,y:le.clientY},buildingId:Z.id,type:"database"})},children:"🗄️"},Z.id)})}),o.jsx(hW,{})]})]}),(()=>{const Z=[];return tt&&(Z.push({id:"open",label:"Open",icon:"⬇",onClick:()=>Dt(tt.buildingId,tt.type)}),It.length>0&&(Z.push({id:"split-right",label:"Split Right",icon:"↔",onClick:()=>Sn(tt.buildingId,tt.type,"horizontal")}),Z.push({id:"split-below",label:"Split Below",icon:"↕",onClick:()=>Sn(tt.buildingId,tt.type,"vertical")}))),o.jsx(or,{children:o.jsx(go,{isOpen:tt!==null,position:(tt==null?void 0:tt.position)||{x:0,y:0},worldPosition:{x:0,z:0},actions:Z,onClose:()=>Nt(null)})})})(),It.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:Us}),o.jsx("div",{ref:Ye,className:`guake-bottom-panels-container ${ot}`,style:{height:lt},onWheel:Z=>Z.stopPropagation(),children:It.map((Z,Te)=>{const le=E.get(Z.buildingId);if(!le)return null;const We=jt[Te]??1,gt=(()=>{var Tt;if(Z.type==="terminal")return(Tt=le.terminalStatus)!=null&&Tt.url?o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>cn(Z.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(Kb,{terminalUrl:le.terminalStatus.url,visible:!0})]},Z.id):o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["💻 ",le.name," (starting...)"]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>cn(Z.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..."})})]},Z.id);if(Z.type==="pm2-logs"){const Cn=Ue[Z.id]||"";return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["📜 ",le.name]}),o.jsxs("div",{className:"guake-bottom-terminal-controls",children:[o.jsx("input",{type:"text",className:"guake-bottom-terminal-filter",value:Cn,onChange:tn=>{const $n=tn.target.value;Qe(ts=>{if(!$n.trim()){if(!(Z.id in ts))return ts;const Ds={...ts};return delete Ds[Z.id],Ds}return{...ts,[Z.id]:$n}})},placeholder:"Filter logs","aria-label":`Filter logs for ${le.name}`,spellCheck:!1}),o.jsx("select",{className:"guake-bottom-terminal-retention",value:ze===null?"unlimited":String(ze),onChange:tn=>{const $n=tn.target.value==="unlimited"?null:Number(tn.target.value);nt($n),BO($n)},"aria-label":`Max log retention for ${le.name}`,children:IO.map(tn=>o.jsx("option",{value:tn===null?"unlimited":String(tn),children:tn===null?"Unlimited":`${tn.toLocaleString()} lines`},tn===null?"unlimited":tn))}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>H.clearStreamingLogs(Z.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:()=>H.sendBuildingCommand(Z.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:()=>cn(Z.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(jW,{buildingId:Z.buildingId,filterText:Cn,maxRetention:ze})]},Z.id)}return o.jsxs("div",{className:"guake-bottom-panel",style:{flex:We},children:[o.jsxs("div",{className:"guake-bottom-terminal-header",children:[o.jsxs("span",{className:"guake-bottom-terminal-title",children:["🗄️ ",le.name]}),o.jsx("button",{className:"guake-bottom-terminal-close",onClick:()=>cn(Z.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(QU,{building:le})]},Z.id)})();return Te>0?o.jsxs(Ce.Fragment,{children:[o.jsx("div",{className:`guake-split-divider ${ot}`,onMouseDown:Tt=>cs(Tt,Te-1)}),gt]},Z.id):gt})})]}),me.filter(Z=>Z.areaId!==zt&&Z.type==="terminal").map(Z=>{var le;const Te=E.get(Z.buildingId);return(le=Te==null?void 0:Te.terminalStatus)!=null&&le.url?o.jsx(Kb,{terminalUrl:Te.terminalStatus.url,visible:!1},Z.id):null})]}),Mt&&!xe&&o.jsx("div",{className:"guake-resize-handle",onMouseDown:q,title:n("common:rightPanel.dragToResize")}),!(Mt&&xe)&&o.jsxs("div",{className:"guake-handle",onClick:()=>{Mt&&H.toggleTerminal()},onDoubleClick:()=>{Mt||H.toggleTerminal()},style:{top:Mt?`min(${P}%, calc(100vh - 72px))`:"0"},children:[o.jsx("span",{className:"guake-handle-icon",children:Mt?"▲":"▼"}),o.jsx("span",{className:"guake-handle-text",children:C.name})]}),oe&&o.jsx(N6,{url:oe.url,name:oe.name,onClose:()=>Ee(null)}),Fe&&o.jsx(T6,{state:Fe,onClose:()=>Ve(null)}),De&&o.jsx(E6,{action:De,selectedAgentId:k,subordinateCount:((Ul=C==null?void 0:C.subordinateIds)==null?void 0:Ul.length)||0,onClose:()=>ge(null),onClearHistory:((Ri=W.current)==null?void 0:Ri.historyLoader.clearHistory)??(()=>{})}),o.jsx(_6,{}),o.jsx(M6,{}),o.jsx(R6,{agent:C,isOpen:$e,onClose:()=>se(!1)}),!h&&o.jsx(D6,{agent:C,content:Oe,onClose:()=>te(null)})]})});function TW(t){return t.trim().replace(/^v/i,"")}function MA(t){const n=TW(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 EW(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 _W(t,e){const n=MA(t),s=MA(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 EW(n.prerelease,s.prerelease)}function MW(t,e){const n=_W(t,e);return n===null?"unknown":n<0?"behind":n>0?"ahead":"equal"}async function DW(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 RW(t,e,n={}){const s=await DW(t,n);return s?{currentVersion:e,latestVersion:s,relation:MW(e,s)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const OW="tide-commander",tb="1.49.0";function LW(){const[t,e]=b.useState({currentVersion:tb,latestVersion:null,relation:"unknown",isChecking:!1}),n=b.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const s=await RW(OW,tb);e({currentVersion:tb,latestVersion:s.latestVersion,relation:s.relation,isChecking:!1})},[]);return b.useEffect(()=>{n()},[n]),{...t,refresh:n}}const PW=b.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:x,onDragOver:y,onDragEnter:v,onDragLeave:S,onDrop:C,onAgentClick:k,onAgentDoubleClick:N,onTouchStart:A,onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onHoverEnter:I,onHoverLeave:O,onItemRef:T}){const M=!a||r,R=b.useCallback(P=>{T(e.id,P)},[e.id,T]);return o.jsxs("div",{ref:R,className:`agent-bar-item ${i?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${d?"dragging":""} ${f?"drag-over":""} ${r?"touch-drag-enabled":""}`,draggable:M,onDragStart:P=>m(P,e),onDragEnd:x,onDragOver:P=>y(P,s),onDragEnter:P=>v(P,s),onDragLeave:S,onDrop:P=>C(P,s),onTouchStart:P=>A(P,e.id),onTouchMove:E,onTouchEnd:D,onTouchCancel:_,onClick:P=>k(e,P),onDoubleClick:()=>N(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(Vn,{classId:e.class,size:"100%",className:"agent-bar-icon"}),o.jsx("span",{className:"agent-bar-status",style:{backgroundColor:Zb(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:Jb(e.lastActivity)},title:xp(e.lastActivity),children:"⏱"})]}),o.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${n+1}`,children:["^",n+1]})]})}),IW=b.memo(function({onFocusAgent:e,onSpawnClick:n,onSpawnBossClick:s,onNewBuildingClick:a,onNewAreaClick:r}){const{t:i}=pt(["common"]),c=Dl(),d=rr(),f=fx(),h=JO(),m=px(),x=Fr(),y=Aa(),v=Uj(),[S]=lx(),[C,k]=b.useState(!1);mj("AgentBar");const N=b.useRef(null),A=b.useRef(null),E=b.useRef(null),D=b.useRef(new Map);b.useEffect(()=>{{k(!1);return}},[x.experimental2DView]),b.useEffect(()=>{const ve=A.current;if(!ve)return;const Ue=Qe=>{ve.scrollWidth<=ve.clientWidth||(Qe.preventDefault(),Math.abs(Qe.deltaX)>Math.abs(Qe.deltaY)?ve.scrollLeft+=Qe.deltaX:ve.scrollLeft+=Qe.deltaY)};return ve.addEventListener("wheel",Ue,{passive:!1}),()=>ve.removeEventListener("wheel",Ue)},[]);const[_,I]=b.useState(null),[O,T]=b.useState(new Map),[M,R]=b.useState(null),[P,U]=b.useState(null),q=b.useRef(0),[z,F]=b.useState(null),$=b.useRef(null),V=b.useRef(null),G=b.useRef(null),B=b.useRef(null),Q=350,K=8,W=b.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),be=b.useMemo(()=>Array.from(c.values()).filter(ve=>{if(H.isAgentInArchivedArea(ve.id))return!1;if(S){const Ue=H.getAreaForAgent(ve.id);if(!vp((Ue==null?void 0:Ue.id)??null))return!1}return!0}).sort((ve,Ue)=>(ve.createdAt||0)-(Ue.createdAt||0)),[c,d,S]),{orderedAgents:fe,moveAgent:J}=kO(be),xe=fe,je=b.useMemo(()=>{const ve=new Map;for(const Ue of xe)ve.set(Ue.id,H.getAreaForAgent(Ue.id));return ve},[xe,d]),oe=b.useMemo(()=>{const ve=new Map;for(const Qe of xe){const ze=je.get(Qe.id)||null,nt=(ze==null?void 0:ze.id)||null;ve.has(nt)||ve.set(nt,{area:ze,agents:[]}),ve.get(nt).agents.push(Qe)}const Ue=Array.from(ve.values());return Ue.sort((Qe,ze)=>{var nt,ot;return!Qe.area&&ze.area?1:Qe.area&&!ze.area?-1:!Qe.area&&!ze.area?0:(((nt=Qe.area)==null?void 0:nt.name)||"").localeCompare(((ot=ze.area)==null?void 0:ot.name)||"")}),Ue},[xe,je]),Ee=b.useRef(e);Ee.current=e;const Fe=b.useRef(M);Fe.current=M;const Ve=b.useRef(xe);Ve.current=xe;const De=b.useRef(je);De.current=je;const ge=b.useRef(J);ge.current=J,b.useEffect(()=>{const ve=new Map(O);let Ue=!1;for(const Qe of xe){const ze=O.get(Qe.id);Qe.currentTool?(!ze||ze.tool!==Qe.currentTool)&&(ve.set(Qe.id,{tool:Qe.currentTool,key:Date.now()}),Ue=!0):ze&&setTimeout(()=>{T(nt=>{const ot=new Map(nt);return ot.delete(Qe.id),ot})},1500)}Ue&&T(ve)},[xe.map(ve=>ve.currentTool).join(",")]),b.useEffect(()=>{const ve=h;if(!ve)return;const Ue=D.current.get(ve),Qe=A.current;Ue&&Qe&&requestAnimationFrame(()=>{const ze=Ue.getBoundingClientRect(),nt=Qe.getBoundingClientRect(),st=ze.left-nt.left+Qe.scrollLeft+ze.width/2,lt=Qe.clientWidth;Qe.scrollTo({left:st-lt/2,behavior:"smooth"})})},[h]);const Oe=b.useCallback((ve,Ue)=>{if(G.current===ve.id){G.current=null,Ue.preventDefault(),Ue.stopPropagation();return}H.setLastSelectionViaDirectClick(!0),Ue.shiftKey?H.addToSelection(ve.id):H.selectAgent(ve.id),H.setTerminalOpen(!0)},[]),te=b.useCallback(ve=>{var Ue;(Ue=Ee.current)==null||Ue.call(Ee,ve.id),H.setTerminalOpen(!0)},[]),$e=b.useCallback(()=>I(null),[]),se=b.useCallback((ve,Ue)=>{Ue?D.current.set(ve,Ue):D.current.delete(ve)},[]),Ne=b.useCallback((ve,Ue)=>{R(Ue),F(Ue.id),ve.dataTransfer.effectAllowed="move",ve.dataTransfer.setData("text/plain",Ue.id),requestAnimationFrame(()=>{ve.target.classList.add("dragging")})},[]),_e=b.useCallback(ve=>{R(null),U(null),F(null),q.current=0,ve.target.classList.remove("dragging")},[]),pe=b.useCallback((ve,Ue)=>{ve.preventDefault();const Qe=Fe.current;if(Qe){const ze=De.current.get(Qe.id),nt=Ve.current[Ue],ot=nt?De.current.get(nt.id):null,st=(ze==null?void 0:ze.id)??null,lt=(ot==null?void 0:ot.id)??null;ve.dataTransfer.dropEffect=st===lt?"move":"none"}else ve.dataTransfer.dropEffect="move"},[]),Ge=b.useCallback((ve,Ue)=>{ve.preventDefault(),q.current++;const Qe=Fe.current;if(Qe){const ze=De.current.get(Qe.id),nt=Ve.current[Ue],ot=nt?De.current.get(nt.id):null,st=(ze==null?void 0:ze.id)??null,lt=(ot==null?void 0:ot.id)??null;U(st===lt?Ue:null)}else U(Ue)},[]),it=b.useCallback(ve=>{q.current--,q.current===0&&U(null)},[]),dt=b.useCallback((ve,Ue)=>{ve.preventDefault();const Qe=Fe.current;if(!Qe)return;const ze=Ve.current,nt=De.current,ot=ze.findIndex(st=>st.id===Qe.id);if(ot!==-1&&ot!==Ue){const st=nt.get(Qe.id),lt=ze[Ue],rt=lt?nt.get(lt.id):null,ht=(st==null?void 0:st.id)??null,jt=(rt==null?void 0:rt.id)??null;ht===jt&&ge.current(ot,Ue)}R(null),U(null),F(null),q.current=0},[]),ce=b.useCallback(()=>{$.current&&(clearTimeout($.current),$.current=null)},[]),X=b.useCallback(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),ne=b.useCallback((ve,Ue)=>{if(!W||ve.touches.length!==1)return;ce(),X(),F(null);const Qe=ve.touches[0];V.current={agentId:Ue,x:Qe.clientX,y:Qe.clientY},$.current=setTimeout(()=>{F(Ue),G.current=Ue,$.current=null},Q)},[ce,X,W]),ke=b.useCallback(ve=>{if(!W||ve.touches.length!==1)return;const Ue=V.current;if(!Ue||!$.current)return;const Qe=ve.touches[0],ze=Qe.clientX-Ue.x,nt=Qe.clientY-Ue.y;Math.sqrt(ze*ze+nt*nt)>K&&(ce(),V.current=null)},[ce,W]),ee=b.useCallback(()=>{ce(),V.current=null,Fe.current||F(null),X(),B.current=setTimeout(()=>{G.current=null,B.current=null},450)},[ce,X]);b.useEffect(()=>()=>{ce(),X()},[ce,X]);const ye=ve=>{const Ue=`common:status.${ve}`;return i(Ue,{defaultValue:i("common:status.unknown")})},{currentVersion:Ie,latestVersion:He,relation:ue,isChecking:de}=LW(),re=Ie;let me=0;return o.jsxs("div",{className:"agent-bar",ref:N,children:[o.jsxs("div",{className:"agent-bar-scroll",ref:A,children:[o.jsxs("div",{className:"agent-bar-version",title:He?`Tide Commander v${re} (npm: v${He})`:`Tide Commander v${re}`,children:[o.jsxs("span",{children:["v",re]}),ue==="behind"&&He?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${He}`,children:["npm v",He]}):ue==="ahead"&&He?o.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${He}`,children:["npm v",He]}):null,ue==="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)"})}):ue==="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)"})}):ue==="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")}):de?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)"})}),C&&o.jsx(Zn,{content:"Refresh 3D Scene (HMR changes pending)",position:"bottom",children:o.jsx("button",{className:"agent-bar-hmr-refresh",onClick:jj,children:"↻"})})]}),o.jsxs("div",{className:"agent-bar-list",ref:E,children:[o.jsx(Zn,{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(Zn,{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(Zn,{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(Zn,{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")})]})}),oe.map(ve=>{var ze,nt,ot,st,lt;const Ue=ve.agents,Qe=!ve.area;return o.jsxs("div",{className:`agent-bar-group ${Qe?"unassigned":""}`,style:{borderColor:((ze=ve.area)==null?void 0:ze.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:((nt=ve.area)==null?void 0:nt.color)||"#888"},children:((ot=ve.area)==null?void 0:ot.name)||i("common:agentBar.unassigned")})}),((st=ve.area)==null?void 0:st.directories)&&ve.area.directories.length>0&&o.jsx("div",{className:"agent-bar-folders",children:ve.area.directories.map((rt,ht)=>o.jsxs("div",{className:"agent-bar-folder-item",onClick:jt=>{jt.stopPropagation(),H.openFileExplorer(rt)},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:rt}),o.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},ht))}),Ue.map(rt=>{const ht=me++,jt=xe.findIndex(he=>he.id===rt.id);return o.jsx(PW,{agent:rt,currentIndex:ht,agentIndex:jt,isTouchInput:W,isTouchDragEnabled:z===rt.id,isSelected:f.has(rt.id),hasUnseenOutput:v.has(rt.id),isDragging:(M==null?void 0:M.id)===rt.id,isDragOver:P===jt,customClasses:y,onDragStart:Ne,onDragEnd:_e,onDragOver:pe,onDragEnter:Ge,onDragLeave:it,onDrop:dt,onAgentClick:Oe,onAgentDoubleClick:te,onTouchStart:ne,onTouchMove:ke,onTouchEnd:ee,onTouchCancel:ee,onHoverEnter:I,onHoverLeave:$e,onItemRef:se},rt.id)})]},((lt=ve.area)==null?void 0:lt.id)||"unassigned")})]})]}),Array.from(O.entries()).map(([ve,Ue])=>{const Qe=D.current.get(ve);if(!Qe)return null;const ze=Qe.getBoundingClientRect(),nt=ls[Ue.tool]||ls.default;return o.jsxs("div",{className:"agent-bar-tool-bubble",title:Ue.tool,style:{position:"fixed",left:ze.left+ze.width/2,bottom:window.innerHeight-ze.top+8},children:[o.jsx("span",{className:"agent-bar-tool-icon",children:nt}),o.jsx("span",{className:"agent-bar-tool-name",children:Ue.tool})]},`tool-${ve}-${Ue.key}`)}),_&&(()=>{const ve=H.getAreaForAgent(_.id),Ue=m.get(_.id),Qe=ir(_.class,y),ze=H.getAgentSupervisorHistory(_.id),nt=ze.length>0?ze[ze.length-1]:void 0,ot=Date.now()-(_.createdAt||Date.now()),st=Math.floor(ot/6e4),lt=Math.floor(st/60),rt=lt>0?`${lt}h ${st%60}m`:`${st}m`,ht=tt=>tt>=1e6?`${(tt/1e6).toFixed(1)}M`:tt>=1e3?`${(tt/1e3).toFixed(1)}K`:tt.toString(),jt=_.contextLimit>0?Math.round(_.contextUsed/_.contextLimit*100):0,he=tt=>{switch(tt){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Me=D.current.get(_.id),Ye={};if(Me){const tt=Me.getBoundingClientRect();Ye.position="fixed",Ye.left=tt.left+tt.width/2,Ye.bottom=window.innerHeight-tt.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:o.jsx(Vn,{classId:_.class,size:18})}),o.jsxs("span",{className:"agent-bar-tooltip-name",children:[o.jsx("img",{src:_.provider==="codex"?"/assets/codex.png":_.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:_.provider,className:"agent-bar-provider-icon",title:_.provider==="codex"?"Codex Agent":_.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),_.name]}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Zb(_.status)},children:ye(_.status)})]}),o.jsxs("div",{className:"agent-bar-tooltip-info",children:[o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.class"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.class," — ",Qe.description]})]}),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:_.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:rt})]}),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:[ht(_.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:jt>80?"#ff4a4a":jt>60?"#ff9e4a":void 0},children:[ht(_.contextUsed)," / ",ht(_.contextLimit)," (",jt,"%)"]})]}),_.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:[ls[_.currentTool]||ls.default," ",_.currentTool]})]}),_.taskLabel&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsx("span",{className:"agent-bar-tooltip-label",children:"📋 Task:"}),o.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:_.taskLabel})]}),_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.task"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value",children:[_.currentTask.substring(0,150),_.currentTask.length>150?"...":""]})]}),_.lastAssignedTask&&!_.currentTask&&o.jsxs("div",{className:"agent-bar-tooltip-row",children:[o.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.assignedTask"),":"]}),o.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[_.lastAssignedTask.substring(0,200),_.lastAssignedTask.length>200?"...":""]})]}),Ue&&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:[Ue.text.substring(0,300),Ue.text.length>300?"...":""]})]}),nt&&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:he(nt.analysis.progress)},children:nt.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:nt.analysis.statusDescription})]}),nt.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:[nt.analysis.recentWorkSummary.substring(0,300),nt.analysis.recentWorkSummary.length>300?"...":""]})]}),nt.analysis.concerns&&nt.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:nt.analysis.concerns.join("; ")})]})]})]})]})})()]})});function BW({activeTool:t,onExit:e}){const{t:n}=pt(["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 FW={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},nb=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),zW=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"}},$W=b.memo(function({agent:e,screenPos:n,onClose:s}){const{t:a}=pt(["common"]),r=Aa(),i=H.getAreaForAgent(e.id),c=H.getState().lastPrompts.get(e.id),d=ir(e.class,r),f=H.getAgentSupervisorHistory(e.id),h=f.length>0?f[f.length-1]:void 0,m=Date.now()-(e.createdAt||Date.now()),x=Math.floor(m/6e4),y=Math.floor(x/60),v=y>0?`${y}h ${x%60}m`:`${x}m`,S=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,C=b.useMemo(()=>{let A=n.x-150,E=n.y-320-10;return typeof window<"u"&&(A<10?A=10:A+300>window.innerWidth-10&&(A=window.innerWidth-300-10),E<10&&(E=n.y+10)),{position:"fixed",left:A,top:E,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[n.x,n.y]);return o.jsxs("div",{className:"agent-hover-popup",style:C,onMouseLeave:s,children:[o.jsxs("div",{className:"agent-bar-tooltip-header",children:[o.jsx("span",{className:"agent-bar-tooltip-icon",children:o.jsx(Vn,{agent:e,size:18})}),o.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),o.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Zb(e.status)},children:a(FW[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:v})]}),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:[nb(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:S>80?"#ff4a4a":S>60?"#ff9e4a":void 0},children:[nb(e.contextUsed)," / ",nb(e.contextLimit)," (",S,"%)"]})]}),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:[ls[e.currentTool]||ls.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:zW(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 DA(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 RA(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 OA={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 HW(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:OA[c]&&(a=OA[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 UW=b.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){var F,$,V,G,B,Q,K,W,be,fe,J,xe,je,oe,Ee,Fe,Ve,De,ge,Oe;const{t:c}=pt(["terminal","common"]),[d,f]=b.useState(!1),[h,m]=b.useState(null),[x,y]=b.useState(!1),v=b.useRef(null),S=b.useRef(h);S.current=h;const{buildingLogs:C}=ws(),k=H.getBuildingLogs(e.id),N=(F=e.pm2)==null?void 0:F.enabled,A=($=e.docker)==null?void 0:$.enabled,E=b.useRef(null),D=b.useRef(null),_=b.useCallback(te=>{te.preventDefault();const $e=S.current?S.current.x:0,se=S.current?S.current.y:0;v.current={mouseX:te.clientX,mouseY:te.clientY,popupX:$e,popupY:se},y(!0),E.current=Ne=>{if(!v.current)return;const _e=Ne.clientX-v.current.mouseX,pe=Ne.clientY-v.current.mouseY;m({x:v.current.popupX+_e,y:v.current.popupY+pe})},D.current=()=>{y(!1),v.current=null,E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",E.current),document.addEventListener("mouseup",D.current)},[]);b.useEffect(()=>()=>{E.current&&document.removeEventListener("mousemove",E.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const I=te=>{if(te==="logs"){if((N||A)&&r){r();return}H.sendBuildingCommand(e.id,te),f(!0)}else H.sendBuildingCommand(e.id,te)},O=(te,$e)=>{if(te){const se=`http://localhost:${te}`;$e&&i?i(se):window.open(se,"_blank")}},T=((V=e.pm2Status)==null?void 0:V.ports)||[],M=((B=(G=e.dockerStatus)==null?void 0:G.ports)==null?void 0:B.map(te=>te.host))||[],R=N?T:A?M:[],P=N?!!((Q=e.pm2)!=null&&Q.script):A?!!((K=e.docker)!=null&&K.image)||((W=e.docker)==null?void 0:W.mode)==="compose"||((be=e.docker)==null?void 0:be.mode)==="existing":!!((fe=e.commands)!=null&&fe.start),U=N?!!((J=e.pm2)!=null&&J.script):A?!0:!!((xe=e.commands)!=null&&xe.stop),q=N?!!((je=e.pm2)!=null&&je.script):A?!0:!!((oe=e.commands)!=null&&oe.restart),z=b.useMemo(()=>{const $e=d?400:250;let se=n.x+20,Ne=n.y-80;return typeof window<"u"&&!h&&(n.x+20+280>window.innerWidth&&(se=n.x-280-20),n.y-80<0?Ne=10:n.y-80+$e>window.innerHeight&&(Ne=window.innerHeight-$e-10)),{position:"fixed",left:se+((h==null?void 0:h.x)||0),top:Ne+((h==null?void 0:h.y)||0),zIndex:1e3,cursor:x?"grabbing":void 0}},[n.x,n.y,d,h,x]);return o.jsxs("div",{className:"building-action-popup",style:z,onClick:te=>te.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header ${x?"dragging":""}`,onMouseDown:_,children:[o.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&o.jsx("span",{className:"building-popup-ports",children:R.map(te=>o.jsxs("a",{href:`http://localhost:${te}`,className:"building-popup-port-link",onClick:$e=>{$e.preventDefault(),$e.stopPropagation(),O(te,$e.altKey)},onMouseDown:$e=>$e.stopPropagation(),title:`Open http://localhost:${te} (Alt+Click for modal)`,children:[":",te]},te))}),o.jsx("span",{className:"building-popup-status",style:{backgroundColor:mb[e.status]},children:e.status}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),N&&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:[((Ee=e.pm2Status.cpu)==null?void 0:Ee.toFixed(1))||"0","%"]})]}),o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:DA(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:RA(e.pm2Status.uptime)})]})]}),A&&e.dockerStatus&&o.jsxs("div",{className:"building-popup-metrics",children:[o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"ID"}),o.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"CPU"}),o.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&o.jsxs("span",{className:"metric",children:[o.jsx("span",{className:"label",children:"MEM"}),o.jsx("span",{className:"value",children:DA(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:RA(e.dockerStatus.startedAt)})]})]}),A&&((Fe=e.dockerStatus)==null?void 0:Fe.services)&&e.dockerStatus.services.length>0&&o.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((te,$e)=>o.jsxs("span",{className:"service-item",title:`${te.name}: ${te.status}`,children:[o.jsx("span",{className:"service-indicator",style:{backgroundColor:te.status==="running"?"#4ade80":"#f87171"}}),o.jsx("span",{className:"service-name",children:te.name})]},$e))}),(e.lastError||N&&((Ve=e.pm2Status)==null?void 0:Ve.status)==="errored"||A&&((De=e.dockerStatus)==null?void 0:De.status)==="dead")&&o.jsxs("div",{className:"building-popup-error",children:[e.lastError||c("terminal:building.processFailedToStart"),N&&((ge=e.pm2Status)==null?void 0:ge.restarts)&&e.pm2Status.restarts>5&&o.jsxs("span",{className:"error-hint",children:[" - ",c("terminal:building.checkLogsOrConfig")]}),A&&((Oe=e.dockerStatus)==null?void 0:Oe.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:!P||e.status==="running"||e.status==="starting",title:c(P?"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:!U||e.status==="stopped"||e.status==="stopping",title:c(U?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:buildingAction.stop")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>I("restart"),disabled:!q,title:c(q?"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:te=>O(R[0],te.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(te=>o.jsxs("button",{className:"action-btn open-url port-btn",onClick:$e=>O(te,$e.altKey),title:`Open http://localhost:${te} (Alt+Click for modal)`,children:[":",te]},te))]})]}),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:()=>H.clearBuildingLogs(e.id),children:c("terminal:logs.clear")})]}),o.jsx("div",{className:"logs-content",children:k.slice(-50).map((te,$e)=>o.jsx("pre",{children:HW(te)},$e))})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:buildingAction.fullSettings")})]})});function WW(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 qW(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 VW=b.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenLogsModal:r,onOpenUrlInModal:i}){const{t:c}=pt(["terminal","common"]),[d,f]=b.useState(null),[h,m]=b.useState(!1),x=b.useRef(null),y=b.useRef(d);y.current=d;const{buildings:v}=ws(),C=(e.subordinateBuildingIds||[]).map(T=>v.get(T)).filter(T=>T!==void 0),k=b.useRef(null),N=b.useRef(null),A=b.useCallback(T=>{T.preventDefault();const M=y.current?y.current.x:0,R=y.current?y.current.y:0;x.current={mouseX:T.clientX,mouseY:T.clientY,popupX:M,popupY:R},m(!0),k.current=P=>{if(!x.current)return;const U=P.clientX-x.current.mouseX,q=P.clientY-x.current.mouseY;f({x:x.current.popupX+U,y:x.current.popupY+q})},N.current=()=>{m(!1),x.current=null,k.current&&document.removeEventListener("mousemove",k.current),N.current&&document.removeEventListener("mouseup",N.current)},document.addEventListener("mousemove",k.current),document.addEventListener("mouseup",N.current)},[]);b.useEffect(()=>()=>{k.current&&document.removeEventListener("mousemove",k.current),N.current&&document.removeEventListener("mouseup",N.current)},[]);const E=T=>{H.sendBossBuildingCommand(e.id,T)},D=C.reduce((T,M)=>(T[M.status]=(T[M.status]||0)+1,T),{}),_=C.some(T=>{var M;return(M=T.pm2)==null?void 0:M.enabled}),I=(T,M)=>{const R=`http://localhost:${T}`;M&&i?i(R):window.open(R,"_blank")},O=b.useMemo(()=>{let R=n.x+20,P=n.y-80;return typeof window<"u"&&!d&&(n.x+20+340>window.innerWidth&&(R=n.x-340-20),n.y-80<0?P=10:n.y-80+350>window.innerHeight&&(P=window.innerHeight-350-10)),{position:"fixed",left:R+((d==null?void 0:d.x)||0),top:P+((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:T=>T.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header boss-header ${h?"dragging":""}`,onMouseDown:A,children:[o.jsx("span",{className:"boss-icon",children:"👑"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"subordinate-count",children:c("terminal:building.unitsCount",{count:C.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),o.jsxs("div",{className:"boss-status-overview",children:[Object.entries(D).map(([T,M])=>o.jsxs("span",{className:"status-badge",style:{backgroundColor:mb[T]||"#666"},children:[M," ",T]},T)),C.length===0&&o.jsx("span",{className:"no-subordinates",children:c("terminal:building.noSubordinates")})]}),C.length>0&&o.jsx("div",{className:"subordinate-list",children:C.map(T=>{var M,R,P;return o.jsxs("div",{className:"subordinate-item",children:[o.jsx("span",{className:"sub-status-dot",style:{backgroundColor:mb[T.status]}}),o.jsx("span",{className:"sub-name",children:T.name}),((M=T.pm2Status)==null?void 0:M.ports)&&T.pm2Status.ports.length>0&&o.jsx("span",{className:"sub-port",children:T.pm2Status.ports.map(U=>o.jsxs("a",{href:`http://localhost:${U}`,className:"building-popup-port-link",onClick:q=>{q.preventDefault(),q.stopPropagation(),I(U,q.altKey)},title:`Open http://localhost:${U} (Alt+Click for modal)`,children:[":",U]},U))}),T.pm2Status&&o.jsxs("span",{className:"sub-metrics",children:[(R=T.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",WW(T.pm2Status.memory||0)]}),((P=T.pm2Status)==null?void 0:P.uptime)&&o.jsx("span",{className:"sub-uptime",children:qW(T.pm2Status.uptime)})]},T.id)})}),o.jsxs("div",{className:"building-popup-actions boss-actions",children:[o.jsxs("button",{className:"action-btn start",onClick:()=>E("start_all"),disabled:C.length===0,title:c("terminal:building.startAllSubs"),children:[o.jsx("span",{className:"icon",children:"▶"}),c("terminal:building.startAll")]}),o.jsxs("button",{className:"action-btn stop",onClick:()=>E("stop_all"),disabled:C.length===0,title:c("terminal:building.stopAllSubs"),children:[o.jsx("span",{className:"icon",children:"■"}),c("terminal:building.stopAll")]}),o.jsxs("button",{className:"action-btn restart",onClick:()=>E("restart_all"),disabled:C.length===0,title:c("terminal:building.restartAllSubs"),children:[o.jsx("span",{className:"icon",children:"↺"}),c("terminal:building.restartAll")]}),_&&o.jsxs("button",{className:"action-btn logs",onClick:r,title:c("terminal:building.viewUnifiedLogs"),children:[o.jsx("span",{className:"icon",children:"📄"}),c("terminal:building.logs")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:c("terminal:building.fullSettings")})]})}),GW=b.memo(function({building:e,screenPos:n,onClose:s,onOpenSettings:a,onOpenDatabasePanel:r}){var D;const{t:i}=pt(["terminal","common"]),[c,d]=b.useState(null),[f,h]=b.useState(!1),m=b.useRef(null),x=b.useRef(c);x.current=c;const y=xx(e.id),v=((D=e.database)==null?void 0:D.connections)??[],S=b.useRef(null),C=b.useRef(null),k=b.useCallback(_=>{_.preventDefault();const I=x.current?x.current.x:0,O=x.current?x.current.y:0;m.current={mouseX:_.clientX,mouseY:_.clientY,popupX:I,popupY:O},h(!0),S.current=T=>{if(!m.current)return;const M=T.clientX-m.current.mouseX,R=T.clientY-m.current.mouseY;d({x:m.current.popupX+M,y:m.current.popupY+R})},C.current=()=>{h(!1),m.current=null,S.current&&document.removeEventListener("mousemove",S.current),C.current&&document.removeEventListener("mouseup",C.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",C.current)},[]);b.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),C.current&&document.removeEventListener("mouseup",C.current)},[]);const N=_=>{H.testDatabaseConnection(e.id,_)},A=_=>y.connectionStatus.get(_),E=b.useMemo(()=>{let O=n.x+20,T=n.y-80;return typeof window<"u"&&!c&&(n.x+20+320>window.innerWidth&&(O=n.x-320-20),n.y-80<0?T=10:n.y-80+300>window.innerHeight&&(T=window.innerHeight-300-10)),{position:"fixed",left:O+((c==null?void 0:c.x)||0),top:T+((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:E,onClick:_=>_.stopPropagation(),children:[o.jsxs("div",{className:`building-popup-header database-header ${f?"dragging":""}`,onMouseDown:k,children:[o.jsx("span",{className:"database-icon",children:"🗄️"}),o.jsx("span",{className:"building-popup-name",children:e.name}),o.jsx("span",{className:"connection-count",children:i("terminal:building.connCount",{count:v.length})}),o.jsx("button",{className:"building-popup-close",onClick:s,children:"x"})]}),v.length>0?o.jsx("div",{className:"database-connection-list",children:v.map(_=>{var O;const I=A(_.id);return o.jsxs("div",{className:"database-connection-item",children:[o.jsx("span",{className:"conn-engine",children:((O=BL[_.engine])==null?void 0:O.icon)??"🗄️"}),o.jsx("span",{className:"conn-name",children:_.name}),o.jsx("span",{className:"conn-host",children:_.engine==="sqlite"?_.filepath||_.database||":memory:":`${_.host}:${_.port}`}),I&&o.jsx("span",{className:`conn-status ${I.connected?"connected":"disconnected"}`,children:I.connected?"●":"○"}),o.jsx("button",{className:"conn-test-btn",onClick:()=>N(_.id),title:i("terminal:building.testConnection"),children:"↻"})]},_.id)})}):o.jsxs("div",{className:"database-no-connections",children:[o.jsx("p",{children:i("terminal:building.noConnections")}),o.jsx("p",{className:"hint",children:i("terminal:building.clickSettingsToAdd")})]}),o.jsxs("div",{className:"building-popup-actions database-actions",children:[o.jsxs("button",{className:"action-btn query",onClick:r,disabled:v.length===0,title:i("terminal:building.openDbExplorer"),children:[o.jsx("span",{className:"icon",children:"⌨"}),i("terminal:building.query")]}),o.jsxs("button",{className:"action-btn test-all",onClick:()=>v.forEach(_=>N(_.id)),disabled:v.length===0,title:i("terminal:building.testAllConnections"),children:[o.jsx("span",{className:"icon",children:"↻"}),i("terminal:building.testAll")]})]}),o.jsx("button",{className:"building-popup-settings",onClick:a,children:i("common:buttons.settings")})]})});function YW({visible:t=!0,position:e="top-right"}){const[n,s]=b.useState(0),[a,r]=b.useState([]),[i,c]=b.useState(null),[d,f]=b.useState([]),[h,m]=b.useState(null),[x,y]=b.useState(null),[v,S]=b.useState(!1),[C,k]=b.useState("fps"),[N,A]=b.useState(null),[E,D]=b.useState(null),[_,I]=b.useState(null),[O,T]=b.useState(typeof window<"u"?window.innerWidth:1024),[M,R]=b.useState(null);b.useEffect(()=>{const J=()=>T(window.innerWidth);return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]);const P=kp(),U=b.useMemo(()=>{const J=P.filter(je=>je.memoryUsageMB!==void 0&&je.memoryUsageMB>0);return{totalMB:J.reduce((je,oe)=>je+(oe.memoryUsageMB||0),0),agentCount:J.length,agents:J.map(je=>({name:je.name,memoryMB:je.memoryUsageMB||0,status:je.status})).sort((je,oe)=>oe.memoryMB-je.memoryMB)}},[P]),q=b.useRef([]),z=b.useRef(null);if(b.useEffect(()=>{q.current=d},[d]),b.useEffect(()=>{z.current=h},[h]),b.useEffect(()=>{if(!t)return;const J=async()=>{try{const je=await Lt(_t("/api/perf"));if(je.ok){const oe=await je.json();D(oe)}}catch{}};J();const xe=setInterval(J,v?3e3:1e4);return()=>clearInterval(xe)},[t,v]),b.useEffect(()=>{if(!t)return;const J=Dc.getUsage();J&&M===null&&R(J.usedMB);const xe=setInterval(()=>{var $e,se;Xd.update();const je=Xd.getStats();s(je.current),r(Ne=>[...Ne,je.current].slice(-60));const oe=Dc.getUsage();oe&&c(oe);const Ee=window.__tideScene;if(Ee){const Ne=($e=Ee.getMemoryDiagnostics)==null?void 0:$e.call(Ee);Ne!=null&&Ne.threeJs&&m(Ne.threeJs);const _e=Ee.renderer;if((se=_e==null?void 0:_e.info)!=null&&se.memory){const pe=_e.info.memory.textures||0,Ge=Math.round(pe*1);I({count:pe,estimatedMB:Ge})}}const Fe=document.getElementsByTagName("*"),Ve=document.getElementsByTagName("canvas"),De=document.getElementsByTagName("img"),ge=document.getElementsByTagName("video");let Oe=0;for(let Ne=0;Ne<Math.min(Fe.length,500);Ne++){const _e=Fe[Ne];_e.onclick&&Oe++,_e.onmousedown&&Oe++,_e.onkeydown&&Oe++}Oe+=10,A({nodeCount:Fe.length,listenerCount:Oe,canvasCount:Ve.length,imageCount:De.length,videoCount:ge.length}),oe&&f(Ne=>{const _e=z.current,pe={timestamp:Date.now(),heapMB:oe.usedMB,geometries:(_e==null?void 0:_e.geometries)??0,textures:(_e==null?void 0:_e.textures)??0};return[...Ne,pe].slice(-120)});const te=q.current;if(te.length>=10){const Ne=te[0],_e=te[te.length-1],pe=(_e.timestamp-Ne.timestamp)/1e3/60;pe>.1&&y((_e.heapMB-Ne.heapMB)/pe)}},1e3);return()=>{clearInterval(xe)}},[t,M]),!t)return null;const F=J=>{const xe=Math.floor(J/3600),je=Math.floor(J%3600/60),oe=J%60;return xe>0?`${xe}h ${je}m`:je>0?`${je}m ${oe}s`:`${oe}s`},$=J=>J>=55?"#4aff9e":J>=30?"#ffcc00":"#ff4a4a",V=(J,xe)=>{const je=J/xe;return je<.5?"#4aff9e":je<.8?"#ffcc00":"#ff4a4a"},G=J=>J===null?"#888":J<1?"#4aff9e":J<5?"#ffcc00":"#ff4a4a",B=Xd.getStats(),K=O<=768?80:10,W={"top-left":{top:10,left:10},"top-right":{top:10,right:10},"bottom-left":{bottom:K,left:10},"bottom-right":{bottom:K,right:10}},be=M&&i?i.usedMB-M:0,fe=J=>({padding:"2px 8px",fontSize:"9px",border:"none",background:C===J?"rgba(74, 158, 255, 0.4)":"rgba(255, 255, 255, 0.1)",color:C===J?"#4a9eff":"#888",borderRadius:"3px",cursor:"pointer"});return o.jsxs("div",{style:{position:"fixed",...W[e],zIndex:99999,fontFamily:"monospace",fontSize:"11px",background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",padding:"6px 10px",color:"#fff",userSelect:"none",minWidth:v?"260px":"120px",maxWidth:"calc(100vw - 20px)",maxHeight:v?"calc(100vh - 100px)":"auto",overflowY:v?"auto":"visible",transition:"all 0.2s ease"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:()=>S(!v),children:[o.jsx("span",{style:{color:$(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"})]}),x!==null&&Math.abs(x)>.5&&o.jsxs("span",{style:{color:G(x),fontSize:"10px",marginLeft:"4px"},children:[x>0?"+":"",x.toFixed(1),"/m"]}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"#444"},children:"|"}),o.jsx("span",{style:{color:"#ff9e4a",fontWeight:"bold"},children:E.process.rssMB}),o.jsx("span",{style:{color:"#666",fontSize:"10px"},children:"SRV"})]}),o.jsx("span",{style:{color:"#444",marginLeft:"auto",fontSize:"10px"},children:v?"▼":"▶"})]}),v&&o.jsxs("div",{style:{marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px"},children:[o.jsxs("div",{style:{display:"flex",gap:"4px",marginBottom:"8px",flexWrap:"wrap"},children:[o.jsx("button",{style:fe("fps"),onClick:()=>k("fps"),children:"FPS"}),o.jsx("button",{style:fe("memory"),onClick:()=>k("memory"),children:"Memory"}),o.jsx("button",{style:fe("threejs"),onClick:()=>k("threejs"),children:"3D"}),o.jsx("button",{style:fe("dom"),onClick:()=>k("dom"),children:"DOM"}),o.jsx("button",{style:fe("server"),onClick:()=>k("server"),children:"Server"}),o.jsx("button",{style:fe("http"),onClick:()=>k("http"),children:"HTTP"})]}),C==="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:$(B.current)},children:B.current}),o.jsx("span",{style:{color:"#888"},children:"Min:"}),o.jsx("span",{style:{color:$(B.min)},children:B.min}),o.jsx("span",{style:{color:"#888"},children:"Max:"}),o.jsx("span",{style:{color:$(B.max)},children:B.max}),o.jsx("span",{style:{color:"#888"},children:"Avg:"}),o.jsx("span",{style:{color:$(B.avg)},children:B.avg})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"60s History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"30px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:a.slice(-60).map((J,xe)=>o.jsx("div",{style:{width:"3px",height:`${Math.min(100,J/60*100)}%`,background:$(J),opacity:.8}},xe))})]})]}),C==="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(x)},children:x!==null?`${x.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((J,xe)=>{const je=Math.min(...d.map(Ve=>Ve.heapMB)),Ee=Math.max(...d.map(Ve=>Ve.heapMB))-je||1,Fe=(J.heapMB-je)/Ee*100;return o.jsx("div",{style:{width:"3px",height:`${Math.max(5,Fe)}%`,background:J.heapMB>(M??0)+50?"#ff4a4a":"#4a9eff",opacity:.8},title:`${J.heapMB}MB`},xe)})})]}),U.agentCount>0&&o.jsxs("div",{style:{marginTop:"8px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:["Agent Memory (",U.agentCount,"):"]}),o.jsxs("div",{style:{fontSize:"10px"},children:[o.jsxs("div",{style:{color:"#4aff9e",fontWeight:"bold",marginBottom:"2px"},children:["Total: ",U.totalMB,"MB"]}),o.jsx("div",{style:{maxHeight:"50px",overflowY:"auto"},children:U.agents.slice(0,4).map((J,xe)=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":"#666",maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB,"MB"]})]},xe))})]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[i.usedMB," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsxs("span",{style:{color:"#9e4aff"},children:["DOM (",(N==null?void 0:N.nodeCount.toLocaleString())??0," nodes)"]}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",i.usedMB+((_==null?void 0:_.estimatedMB)??0)+Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)," MB"]})]})]})]})]}),C==="threejs"&&o.jsx("div",{children:h?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Geometries:"}),o.jsx("span",{style:{color:"#4aff9e"},children:h.geometries}),o.jsx("span",{style:{color:"#888"},children:"Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:h.textures}),o.jsx("span",{style:{color:"#888"},children:"Programs:"}),o.jsx("span",{style:{color:"#9e4aff"},children:h.programs})]}),d.length>1&&o.jsxs("div",{children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"2px"},children:"Resource History:"}),o.jsx("div",{style:{display:"flex",alignItems:"flex-end",height:"40px",gap:"1px",background:"rgba(0,0,0,0.3)",padding:"2px",borderRadius:"2px"},children:d.slice(-60).map((J,xe)=>{const je=Math.max(...d.map(oe=>oe.textures))||1;return o.jsx("div",{style:{width:"3px",height:`${J.textures/je*100}%`,background:"#ff9e4a",opacity:.8},title:`${J.textures} textures`},xe)})})]}),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."]})}),C==="dom"&&o.jsx("div",{children:N?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:N.nodeCount>5e3?"#ff4a4a":N.nodeCount>2e3?"#ffcc00":"#4aff9e"},children:N.nodeCount.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Canvases:"}),o.jsx("span",{style:{color:"#4a9eff"},children:N.canvasCount}),o.jsx("span",{style:{color:"#888"},children:"Images:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:N.imageCount}),o.jsx("span",{style:{color:"#888"},children:"Videos:"}),o.jsx("span",{style:{color:"#9e4aff"},children:N.videoCount})]}),_&&o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("span",{style:{color:"#888"},children:"GPU Textures:"}),o.jsx("span",{style:{color:"#ff9e4a"},children:_.count}),o.jsx("span",{style:{color:"#888"},children:"Est. VRAM:"}),o.jsxs("span",{style:{color:_.estimatedMB>100?"#ff4a4a":"#4aff9e"},children:["~",_.estimatedMB," MB"]})]}),o.jsxs("div",{style:{marginTop:"8px",padding:"6px",background:"rgba(0,0,0,0.3)",borderRadius:"4px"},children:[o.jsx("div",{style:{color:"#888",fontSize:"9px",marginBottom:"4px"},children:"Memory Breakdown (estimated):"}),o.jsxs("div",{style:{fontSize:"9px"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#4a9eff"},children:"JS Heap"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[(i==null?void 0:i.usedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#ff9e4a"},children:"GPU/Textures"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:["~",(_==null?void 0:_.estimatedMB)??0," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"2px"},children:[o.jsx("span",{style:{color:"#9e4aff"},children:"DOM (~0.5KB/node)"}),o.jsxs("span",{style:{color:"#9e4aff"},children:["~",Math.round(N.nodeCount*.5/1024)," MB"]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"4px",marginTop:"4px"},children:[o.jsx("span",{style:{color:"#fff",fontWeight:"bold"},children:"Est. Total"}),o.jsxs("span",{style:{color:"#fff",fontWeight:"bold"},children:["~",((i==null?void 0:i.usedMB)??0)+((_==null?void 0:_.estimatedMB)??0)+Math.round(N.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..."})}),C==="server"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Uptime:"}),o.jsx("span",{style:{color:"#4aff9e"},children:F(E.uptime)}),o.jsx("span",{style:{color:"#888"},children:"Heap Used:"}),o.jsxs("span",{style:{color:E.process.heapUsedMB>500?"#ff4a4a":"#4aff9e"},children:[E.process.heapUsedMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"Heap Total:"}),o.jsxs("span",{children:[E.process.heapTotalMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"RSS:"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.rssMB," MB"]}),o.jsx("span",{style:{color:"#888"},children:"External:"}),o.jsxs("span",{children:[E.process.externalMB," MB"]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"System:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Load Avg:"}),o.jsx("span",{style:{color:E.system.loadAvg[0]>E.system.cpuCount?"#ff4a4a":"#4aff9e"},children:E.system.loadAvg.join(" ")}),o.jsx("span",{style:{color:"#888"},children:"CPUs:"}),o.jsx("span",{children:E.system.cpuCount}),o.jsx("span",{style:{color:"#888"},children:"Sys Memory:"}),o.jsxs("span",{children:[E.system.totalMemMB-E.system.freeMemMB," / ",E.system.totalMemMB," MB"]})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px",marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"WebSocket:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"Clients:"}),o.jsx("span",{style:{color:"#4a9eff"},children:E.websocket.clients}),o.jsx("span",{style:{color:"#888"},children:"Sent:"}),o.jsx("span",{children:E.websocket.messagesSent.toLocaleString()}),o.jsx("span",{style:{color:"#888"},children:"Received:"}),o.jsx("span",{children:E.websocket.messagesReceived.toLocaleString()})]})]}),E.agents.total>0&&o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsxs("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:["Agents (",E.agents.working,"w / ",E.agents.idle,"i / ",E.agents.total,"t):"]}),o.jsx("div",{style:{maxHeight:"80px",overflowY:"auto",fontSize:"10px"},children:E.agents.processes.map(J=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"1px"},children:[o.jsx("span",{style:{color:J.status==="working"?"#4aff9e":J.status==="idle"?"#888":"#ff4a4a",maxWidth:"100px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J.name}),o.jsxs("span",{style:{color:"#4a9eff"},children:[J.memoryMB!=null?`${J.memoryMB}MB`:"—",J.pid?` (${J.pid})`:""]})]},J.id))})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading server metrics..."})}),C==="http"&&o.jsx("div",{children:E?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px",marginBottom:"8px"},children:[o.jsx("span",{style:{color:"#888"},children:"Req/sec (30s):"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.http.reqPerSec}),o.jsx("span",{style:{color:"#888"},children:"Avg Latency:"}),o.jsxs("span",{style:{color:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e"},children:[E.http.avgLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Max Latency:"}),o.jsxs("span",{style:{color:E.http.maxLatencyMs>500?"#ff4a4a":E.http.maxLatencyMs>200?"#ffcc00":"#4aff9e"},children:[E.http.maxLatencyMs," ms"]}),o.jsx("span",{style:{color:"#888"},children:"Recent Reqs:"}),o.jsx("span",{children:E.http.recentRequests})]}),o.jsxs("div",{style:{marginBottom:"8px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Avg Latency:"}),o.jsx("div",{style:{height:"8px",background:"rgba(255,255,255,0.1)",borderRadius:"4px",overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:`${Math.min(100,E.http.avgLatencyMs/500*100)}%`,background:E.http.avgLatencyMs>100?"#ff4a4a":E.http.avgLatencyMs>50?"#ffcc00":"#4aff9e",transition:"width 0.3s ease"}})}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"8px",color:"#444",marginTop:"2px"},children:[o.jsx("span",{children:"0ms"}),o.jsx("span",{children:"500ms"})]})]}),o.jsxs("div",{style:{borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"6px"},children:[o.jsx("div",{style:{color:"#666",fontSize:"9px",marginBottom:"4px"},children:"Server Process:"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2px 10px",fontSize:"10px"},children:[o.jsx("span",{style:{color:"#888"},children:"CPU (user):"}),o.jsxs("span",{style:{color:"#4a9eff"},children:[E.process.cpuUser," ms"]}),o.jsx("span",{style:{color:"#888"},children:"CPU (system):"}),o.jsxs("span",{style:{color:"#ff9e4a"},children:[E.process.cpuSystem," ms"]}),o.jsx("span",{style:{color:"#888"},children:"WS Clients:"}),o.jsx("span",{style:{color:"#4aff9e"},children:E.websocket.clients})]})]})]}):o.jsx("div",{style:{color:"#666",fontSize:"10px"},children:"Loading HTTP metrics..."})}),o.jsxs("div",{style:{display:"flex",gap:"4px",marginTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",paddingTop:"8px",flexWrap:"wrap"},children:[o.jsx("button",{onClick:J=>{J.stopPropagation();const xe=["=== Tide Commander Performance Stats ===",`Timestamp: ${new Date().toISOString()}`,"","--- FPS ---",`Current: ${B.current}`,`Min: ${B.min}`,`Max: ${B.max}`,`Avg: ${B.avg}`];i&&xe.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: ${x!==null?`${x.toFixed(2)} MB/min`:"N/A"}`),h&&xe.push("","--- Three.js ---",`Geometries: ${h.geometries}`,`Textures: ${h.textures}`,`Programs: ${h.programs}`),U.agentCount>0&&(xe.push("","--- Agent Memory ---",`Total: ${U.totalMB} MB`,`Agents: ${U.agentCount}`),U.agents.slice(0,5).forEach(oe=>{xe.push(` ${oe.name}: ${oe.memoryMB} MB (${oe.status})`)})),N&&xe.push("","--- DOM ---",`DOM Nodes: ${N.nodeCount.toLocaleString()}`,`Canvases: ${N.canvasCount}`,`Images: ${N.imageCount}`,`Videos: ${N.videoCount}`),_&&xe.push("","--- Estimated Memory ---",`GPU Textures: ${_.count}`,`Est. VRAM: ~${_.estimatedMB} MB`,`Est. DOM: ~${Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)} MB`,`Est. Total: ~${((i==null?void 0:i.usedMB)??0)+_.estimatedMB+Math.round(((N==null?void 0:N.nodeCount)??0)*.5/1024)} MB`),E&&(xe.push("","--- Server ---",`Uptime: ${F(E.uptime)}`,`Heap: ${E.process.heapUsedMB}/${E.process.heapTotalMB} MB`,`RSS: ${E.process.rssMB} MB`,`Load Avg: ${E.system.loadAvg.join(" ")}`,`System Memory: ${E.system.totalMemMB-E.system.freeMemMB}/${E.system.totalMemMB} MB`,"","--- WebSocket ---",`Clients: ${E.websocket.clients}`,`Sent: ${E.websocket.messagesSent}`,`Received: ${E.websocket.messagesReceived}`,"","--- HTTP ---",`Req/sec: ${E.http.reqPerSec}`,`Avg Latency: ${E.http.avgLatencyMs} ms`,`Max Latency: ${E.http.maxLatencyMs} ms`),E.agents.processes.length>0&&(xe.push("","--- Agent Processes ---",`Total: ${E.agents.total} (${E.agents.working} working, ${E.agents.idle} idle)`),E.agents.processes.forEach(oe=>{xe.push(` ${oe.name}: ${oe.memoryMB!=null?`${oe.memoryMB}MB`:"N/A"} (${oe.status})${oe.pid?` PID:${oe.pid}`:""}`)})));const je=xe.join(`
|
|
153
|
+
`);navigator.clipboard.writeText(je).then(()=>{const oe=J.currentTarget,Ee=oe.textContent;oe.textContent="Copied!",setTimeout(()=>{oe.textContent=Ee},1e3)})},style:{flex:1,background:"rgba(74, 255, 158, 0.3)",border:"1px solid rgba(74, 255, 158, 0.5)",color:"#4aff9e",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Copy Stats"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),Dc.report();const xe=window.__tideScene;xe!=null&&xe.logMemoryDiagnostics&&xe.logMemoryDiagnostics()},style:{flex:1,background:"rgba(74, 158, 255, 0.3)",border:"1px solid rgba(74, 158, 255, 0.5)",color:"#4a9eff",padding:"4px 6px",borderRadius:"3px",fontSize:"9px",cursor:"pointer"},children:"Console"}),o.jsx("button",{onClick:J=>{J.stopPropagation(),vb.clear(),Xd.reset(),Dc.reset(),r([]),f([]);const xe=Dc.getUsage();xe&&R(xe.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 KW(){const t=Hj(),e=b.useCallback(n=>{H.setViewMode(n)},[]);return[t,e]}const QW=["3d","2d","dashboard"],XW=b.memo(function({className:e=""}){const{t:n}=pt(["common"]),[s,a]=KW(),r=b.useRef(null),[i,c]=b.useState(null);b.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=b.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}}),QW.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 DT({className:t}){const{t:e}=pt(["terminal"]),[n,s]=b.useState(!1),[a,r]=b.useState(null),i=sy(),c=b.useCallback(async y=>{if(y.trim()){console.log("[VoiceAssistant] Transcribed:",y),s(!0),r(null);try{const S=await(await Lt(_t("/api/voice-assistant/process"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:y})})).json();if(S.success&&S.response)console.log("[VoiceAssistant] Response:",S.response),i.speak(S.response);else{const C=S.error||e("terminal:voiceAssistant.failedToProcess");console.error("[VoiceAssistant] Error:",C),r(C),i.speak(C)}}catch(v){console.error("[VoiceAssistant] Request failed:",v);const S=e("terminal:voiceAssistant.unavailable");r(S),i.speak(S)}finally{s(!1)}}},[i]),d=ST({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(" ")},x=()=>{if(r(null),i.speaking){i.stop();return}d.transcribing||n||d.toggleRecording()};return o.jsxs("button",{className:m(),onClick:x,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 JW=b.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:x,mobileView:y}){const{t:v}=pt(["terminal","common"]),S=Fr(),C=k=>{k(),n()};return o.jsxs(o.Fragment,{children:[S.experimentalVoiceAssistant&&o.jsx(DT,{className:"mobile-voice-assistant"}),y!=="terminal"&&o.jsx("button",{className:`mobile-fab-toggle ${e?"open":""}`,onClick:n,onTouchStart:k=>k.stopPropagation(),title:v(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:()=>C(s),onTouchEnd:k=>{k.preventDefault(),C(s)},title:v("terminal:mobileFab.showTerminal"),children:"💬"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(a),onTouchEnd:k=>{k.preventDefault(),C(a)},title:v("terminal:header.openSidebar"),children:"📋"}),x&&o.jsx("button",{className:"mobile-fab-option mobile-fab-option--highlight",onClick:()=>C(m),onTouchEnd:k=>{k.preventDefault(),C(m)},title:v("terminal:mobileFab.takeSnapshot"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(r),onTouchEnd:k=>{k.preventDefault(),C(r)},title:v("common:floatingButtons.settingsAndTools"),children:"⚙️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(i),onTouchEnd:k=>{k.preventDefault(),C(i)},title:v("common:floatingButtons.commanderView"),children:"📊"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(c),onTouchEnd:k=>{k.preventDefault(),C(c)},title:v("common:floatingButtons.supervisorOverview"),children:"🎖️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(d),onTouchEnd:k=>{k.preventDefault(),C(d)},title:v("common:floatingButtons.controls"),children:"⌨️"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(f),onTouchEnd:k=>{k.preventDefault(),C(f)},title:v("common:floatingButtons.manageSkills"),children:"⭐"}),o.jsx("button",{className:"mobile-fab-option",onClick:()=>C(h),onTouchEnd:k=>{k.preventDefault(),C(h)},title:v("common:floatingButtons.viewSnapshots"),children:"📸"})]})]})}),ZW=b.memo(function({onOpenToolbox:e,onOpenCommander:n,onOpenSupervisor:s,onOpenControls:a,onOpenSkills:r,onOpenSnapshots:i,isGeneratingReport:c,pip:d}){const{t:f}=pt(["common","terminal"]),h=Fr();return o.jsxs(o.Fragment,{children:[h.experimentalVoiceAssistant&&o.jsx(DT,{}),o.jsx(Zn,{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(Zn,{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(Zn,{content:f("common:floatingButtons.viewSnapshots"),position:"left",children:o.jsx("button",{className:"snapshots-toggle-btn",onClick:i,children:"📸"})}),o.jsx(Zn,{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(Zn,{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(Zn,{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(Zn,{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"})]})})})]})}),eq=Ce.lazy(()=>vt(()=>import("./SpawnModal-CPTZGYNR.js"),__vite__mapDeps([17,3,1,4])).then(t=>({default:t.SpawnModal}))),tq=Ce.lazy(()=>vt(()=>import("./BossSpawnModal-D7M1JocE.js"),__vite__mapDeps([18,3,1,4])).then(t=>({default:t.BossSpawnModal}))),nq=Ce.lazy(()=>vt(()=>import("./SubordinateAssignmentModal-B2XP8wZU.js"),__vite__mapDeps([19,3,1,4])).then(t=>({default:t.SubordinateAssignmentModal}))),sq=Ce.lazy(()=>vt(()=>import("./index-BIt0Cgpm.js"),__vite__mapDeps([20,3,1,4,21])).then(t=>({default:t.Toolbox}))),aq=Ce.lazy(()=>vt(()=>import("./index-DYwDeYnm.js"),__vite__mapDeps([22,3,1,4])).then(t=>({default:t.BuildingConfigModal}))),rq=Ce.lazy(()=>vt(()=>import("./index-D33VRpYX.js"),__vite__mapDeps([23,24,3,1,4])).then(t=>({default:t.CommanderView}))),iq=Ce.lazy(()=>vt(()=>import("./SupervisorPanel-LlgMdGCQ.js"),__vite__mapDeps([25,3,1,4])).then(t=>({default:t.SupervisorPanel}))),oq=Ce.lazy(()=>vt(()=>import("./index-BM1s5vTS.js").then(t=>t.y),[]).then(t=>({default:t.FileExplorerPanel}))),lq=Ce.lazy(()=>vt(()=>import("./index-CG-I_YeN.js"),__vite__mapDeps([26,3,1,4])).then(t=>({default:t.Spotlight}))),cq=Ce.lazy(()=>vt(()=>import("./ControlsModal-C3-j1E6y.js"),__vite__mapDeps([27,3,1,4])).then(t=>({default:t.ControlsModal}))),uq=Ce.lazy(()=>vt(()=>import("./SkillsPanel-nKzb0E59.js"),__vite__mapDeps([28,3,1,4])).then(t=>({default:t.SkillsPanel}))),dq=Ce.lazy(()=>vt(()=>Promise.resolve().then(()=>H2),void 0).then(t=>({default:t.AgentEditModal}))),fq=Ce.lazy(()=>vt(()=>import("./SnapshotManager-DoQRZCNb.js"),__vite__mapDeps([29,3,1,4])).then(t=>({default:t.SnapshotManager}))),pq=Ce.lazy(()=>vt(()=>import("./RestoreArchivedAreaModal-mwQqJ4qp.js"),__vite__mapDeps([30,3,1,4])).then(t=>({default:t.RestoreArchivedAreaModal}))),hq=Ce.lazy(()=>vt(()=>import("./IntegrationsPanel-iTByepHj.js"),__vite__mapDeps([31,3,1,4])).then(t=>({default:t.IntegrationsPanel}))),mq=Ce.lazy(()=>vt(()=>import("./MonitoringModal-C3NapNrP.js"),__vite__mapDeps([32,3,1,4])).then(t=>({default:t.MonitoringModal}))),gq=Ce.lazy(()=>vt(()=>import("./WorkflowEditorPanel-DPwmjV2f.js"),__vite__mapDeps([33,3,1,4])).then(t=>({default:t.WorkflowEditorPanel}))),bq=Ce.lazy(()=>vt(()=>import("./TriggerManagerPanel-DMiK0_y5.js"),__vite__mapDeps([34,3,1,4])).then(t=>({default:t.TriggerManagerPanel})));function xq({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:x,triggerManagerModal:y,buildingModal:v,agentEditModal:S,snapshotsModal:C,restoreArchivedModal:k,explorerModal:N,contextMenu:A,spawnPosition:E,spawnAreaId:D,explorerFolderPath:_,contextMenuActions:I,buildingInitialPosition:O,sceneConfig:T,onConfigChange:M,onToolChange:R,onOpenAreaExplorer:P,onDeleteSelectedAgents:U,pendingBuildingDelete:q,onCancelBuildingDelete:z,onConfirmBuildingDelete:F,showBackNavModal:$,onCloseBackNavModal:V,onLeave:G,onOpenPM2LogsModal:B,onOpenBossLogsModal:Q,onOpenDatabasePanel:K,onSyncScene:W}){const be=ws(),fe=Array.from(be.snapshots.values()),J=be.snapshotsLoading;be.currentSnapshot,b.useEffect(()=>{C.isOpen&&H.fetchSnapshots()},[C.isOpen]);const xe=q==="selected",je=q&&q!=="selected"?be.buildings.get(q):null,oe=be.selectedBuildingIds.size;return o.jsxs(b.Suspense,{fallback:null,children:[o.jsx(sq,{config:T,onConfigChange:M,onToolChange:R,isOpen:s.isOpen,onClose:s.close,onOpenBuildingModal:Ee=>v.open(Ee||null),onOpenAreaExplorer:P,onOpenIntegrationsModal:Ee=>h.open(Ee),onOpenMonitoringModal:()=>m.open(),onOpenWorkflowEditor:()=>x.open(),onOpenTriggerManager:()=>y.open()}),o.jsx(aq,{isOpen:v.isOpen,onClose:v.close,buildingId:v.data,initialPosition:O||void 0}),o.jsx(eq,{isOpen:t.isOpen,onClose:t.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:E,spawnAreaId:D}),o.jsx(tq,{isOpen:e.isOpen,onClose:e.close,onSpawnStart:()=>{},onSpawnEnd:()=>{},spawnPosition:E}),o.jsx(nq,{isOpen:n.isOpen,bossId:n.data||"",onClose:n.close}),S.isOpen&&S.data&&(()=>{const Ee=be.agents.get(S.data);return Ee?o.jsx(dq,{agent:Ee,isOpen:S.isOpen,onClose:S.close}):null})(),r.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:r.close,onKeyDown:Ee=>{Ee.key==="Escape"&&r.close(),Ee.key==="Enter"&&U()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Ee=>Ee.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:U,autoFocus:!0,children:"Remove"})]})]})}),(je||xe)&&o.jsx("div",{className:"modal-overlay visible",onClick:z,onKeyDown:Ee=>{Ee.key==="Escape"&&z(),Ee.key==="Enter"&&F()},children:o.jsxs("div",{className:"modal confirm-modal",onClick:Ee=>Ee.stopPropagation(),children:[o.jsxs("div",{className:"modal-header",children:["Delete Building",xe&&oe>1?"s":""]}),o.jsxs("div",{className:"modal-body confirm-modal-body",children:[xe?o.jsxs("p",{children:["Delete ",oe," selected building",oe>1?"s":"","?"]}):o.jsxs("p",{children:["Delete ",o.jsx("strong",{children:je==null?void 0:je.name}),"?"]}),o.jsxs("p",{className:"confirm-modal-note",children:["This will permanently remove the building",xe&&oe>1?"s":""," and ",xe&&oe>1?"their":"its"," configuration."]})]}),o.jsxs("div",{className:"modal-footer",children:[o.jsx("button",{className:"btn btn-secondary",onClick:z,children:"Cancel"}),o.jsx("button",{className:"btn btn-danger",onClick:F,autoFocus:!0,children:"Delete"})]})]})}),$&&o.jsx("div",{className:"modal-overlay navigation-confirm-overlay visible",onClick:V,onKeyDown:Ee=>{Ee.key==="Escape"&&V()},children:o.jsxs("div",{className:"modal confirm-modal navigation-confirm-modal",onClick:Ee=>Ee.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(b.Profiler,{id:"CommanderView",onRender:Kc,children:o.jsx(rq,{isOpen:a.isOpen,onClose:a.close})}),o.jsx(iq,{isOpen:i.isOpen,onClose:i.close}),o.jsx(oq,{isOpen:N.isOpen||_!==null||be.explorerAreaId!==null,areaId:N.id||be.explorerAreaId||null,folderPath:_,onChangeArea:Ee=>N.open(Ee),onClose:()=>{N.close(),H.closeFileExplorer()}}),o.jsx(lq,{isOpen:c.isOpen,onClose:c.close,onOpenSpawnModal:()=>t.open(),onOpenCommanderView:()=>a.open(),onOpenToolbox:()=>s.open(),onOpenSupervisor:()=>i.open(),onOpenFileExplorer:Ee=>N.open(Ee),onOpenPM2LogsModal:B,onOpenBossLogsModal:Q,onOpenDatabasePanel:K,onOpenMonitoringModal:()=>m.open()}),o.jsx(cq,{isOpen:d.isOpen,onClose:d.close}),o.jsx(uq,{isOpen:f.isOpen,onClose:f.close}),o.jsx(hq,{isOpen:h.isOpen,onClose:h.close,initialTab:h.data}),o.jsx(mq,{isOpen:m.isOpen,onClose:m.close}),o.jsx(gq,{isOpen:x.isOpen,onClose:x.close}),o.jsx(bq,{isOpen:y.isOpen,onClose:y.close}),o.jsx(pq,{isOpen:k.isOpen,restorePosition:k.data??null,onClose:k.close,onRestored:W}),C.isOpen&&o.jsx("div",{className:"modal-overlay visible",onClick:C.close,children:o.jsx("div",{className:"modal snapshot-manager-modal",onClick:Ee=>Ee.stopPropagation(),children:o.jsx(fq,{snapshots:fe,isLoading:J,onViewSnapshot:async Ee=>{await H.loadSnapshot(Ee),be.selectedAgentIds.clear(),H.setTerminalOpen(!0),C.close()},onDeleteSnapshot:async Ee=>{await H.deleteSnapshot(Ee),await H.fetchSnapshots()},onRestoreSnapshot:async Ee=>{await H.restoreFiles(Ee)},onExportSnapshot:async Ee=>{await H.loadSnapshot(Ee),C.close()},onClose:C.close})})}),o.jsx(go,{isOpen:A.isOpen,position:A.screenPosition,worldPosition:A.worldPosition,actions:I,onClose:A.close})]})}function yq({pip:t,title:e="Tide Commander",children:n}){return b.useEffect(()=>{t.pipWindow&&e&&(t.pipWindow.document.title=e)},[t.pipWindow,e]),!t.isOpen||!t.pipContainer?null:Rl.createPortal(n,t.pipContainer)}function ry(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 oy(t){const e=_u[t.class];return(e==null?void 0:e.icon)||"🤖"}function sb({agent:t,onClick:e}){const n=iy(t.status),s=ry(t.status),a=oy(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 Yc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}const LA={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},PA={systemPrompt:"System Prompt",systemTools:"System Tools",messages:"Messages",freeSpace:"Free Space",autocompactBuffer:"Autocompact Buffer"};function vq({agent:t,onBack:e}){const n=oy(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:ry(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:Yc(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:[Yc(a.totalTokens)," / ",Yc(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:LA[d]},title:`${PA[d]}: ${Yc(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:LA[d]}}),o.jsxs("div",{className:"pip-category-info",children:[o.jsx("div",{className:"pip-category-name",children:PA[d]}),o.jsxs("div",{className:"pip-category-tokens",children:[Yc(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 wq({agentId:t,onBack:e}){const n=dx(t),s=Dj(t),a=zj(),r=$j(),i=px(),c=b.useRef(null),d=b.useRef(null),[f,h]=b.useState(""),[m,x]=b.useState(!1),[y]=b.useState("simple"),v=!!(n!=null&&n.sessionId),S=Nj({selectedAgentId:t,hasSessionId:v,reconnectCount:a,historyRefreshTrigger:r,lastPrompts:i,outputScrollRef:c}),C=dT({outputs:s,viewMode:y}),k=b.useMemo(()=>{const{history:U}=S,q=new Map;for(const F of U)F.type==="tool_result"&&F.toolUseId&&q.set(F.toolUseId,F.content);return(F=>F.map($=>{if($.type==="tool_use"&&$.toolName==="Bash"&&$.toolUseId){const V=q.get($.toolUseId);let G;try{G=($.toolInput||($.content?JSON.parse($.content):{})).command}catch{}return{...$,_bashOutput:V,_bashCommand:G}}return $}))(U.filter(F=>F.type==="user"||F.type==="assistant"||F.type==="tool_use"))},[S.history]),[N,A]=b.useState({top:!1,bottom:!0}),E=b.useCallback(()=>{if(!c.current)return;const{scrollTop:U,scrollHeight:q,clientHeight:z}=c.current;A({top:U>20,bottom:U<q-z-20})},[]);b.useEffect(()=>{c.current&&(c.current.scrollTop=c.current.scrollHeight,E())},[s.length,k.length,E]);const D=b.useCallback(()=>{c.current&&c.current.scrollBy({top:-200,behavior:"smooth"})},[]),_=b.useCallback(()=>{c.current&&c.current.scrollBy({top:200,behavior:"smooth"})},[]),I=b.useCallback(()=>{const U=f.trim();!U||!n||(H.sendCommand(t,U),h(""),setTimeout(()=>{var q;return(q=d.current)==null?void 0:q.focus()},50))},[f,t,n]),O=b.useCallback(U=>{h(U.target.value)},[]),T=b.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),I())},[I]);b.useEffect(()=>{const U=setTimeout(()=>{var q;return(q=d.current)==null?void 0:q.focus()},100);return()=>clearTimeout(U)},[t]);const M=b.useCallback((U,q)=>{const z=_p(U,n==null?void 0:n.cwd),F=z.line?{...q||{},targetLine:z.line}:q;H.setFileViewerPath(z.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=oy(n),P=iy(n.status);return m?o.jsx(vq,{agent:n,onBack:()=>x(!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:P},children:ry(n.status)})]}),o.jsx("div",{className:"pip-context-section",children:o.jsx(Zj,{contextInfo:Cp(n),onClick:()=>x(!0)})}),o.jsxs("div",{className:"pip-conversation-wrapper",children:[o.jsxs("div",{className:"pip-conversation guake-output",ref:c,onScroll:E,children:[!S.loadingHistory&&S.hasMore&&o.jsx("div",{className:"guake-load-more pip-load-more",children:S.loadingMore?o.jsx("span",{children:"Loading older messages..."}):o.jsxs("button",{onClick:S.loadMoreHistory,children:["Load more (",S.totalCount-S.history.length," older)"]})}),S.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((U,q)=>o.jsx(MT,{message:U,agentId:t,simpleView:!0,onFileClick:M},`h-${q}`)),C.map((U,q)=>o.jsx(ay,{output:U,agentId:t,onFileClick:M},`o-${q}`)),!S.loadingHistory&&k.length===0&&C.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:[N.top&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-up",onClick:D,title:"Scroll up",children:"↑"}),N.bottom&&o.jsx("button",{className:"pip-scroll-btn pip-scroll-down",onClick:_,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:T,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 kq({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(sb,{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(sb,{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(sb,{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 Sq(){const[t,e]=b.useState(null),n=a=>{e(a)},s=()=>{e(null)};return t?o.jsx(wq,{agentId:t,onBack:s}):o.jsx(kq,{onSelectAgent:n})}function Cq(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 Aq(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 jq=4e3;function Nq(){const t=Oj(),[e,n]=b.useState(!1),[s,a]=b.useState(!1),[r,i]=b.useState(!0),[c,d]=b.useState(!1),[f,h]=b.useState(()=>nx()),[m,x]=b.useState(!1),[y,v]=b.useState(null),[S,C]=b.useState(null),k=b.useRef(!0),N=b.useRef(!1),A=b.useCallback((O=7e3)=>H.getState().isConnected?Promise.resolve(!0):new Promise(T=>{let M=!1;const R=q=>{M||(M=!0,clearTimeout(U),P(),T(q))},P=H.subscribe(()=>{H.getState().isConnected&&R(!0)}),U=setTimeout(()=>R(!1),O)}),[]);b.useEffect(()=>{const O=setTimeout(()=>i(!1),3e3);return()=>clearTimeout(O)},[]),b.useEffect(()=>{if(t){N.current=!0,d(!1);return}if(N.current){i(!0),d(!0);const O=setTimeout(()=>{i(!1),d(!1)},1e4);return()=>clearTimeout(O)}},[t]),b.useEffect(()=>()=>{k.current=!1},[]),b.useEffect(()=>KD(O=>{h(O)}),[]);const E=b.useCallback(()=>{navigator.clipboard.writeText("bunx tide-commander").then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(()=>{})},[]),D=b.useCallback(async()=>{if(m)return;const O=Date.now(),T=()=>jq-(Date.now()-O);v(null),C("Validating URL");const M=f.trim()||"http://localhost:6200",R=Cq(M);if(!R.ok){C(null),v(R.error||"Invalid backend URL");return}x(!0),C("Checking host reachability");const P=T();if(P<=0){x(!1),C(null),v("Connection timeout after 4 seconds");return}const U=await Aq(R.normalizedUrl,P);if(!U.ok){if(!k.current)return;x(!1),C(null),T()<=0?v("Connection timeout after 4 seconds"):v(U.error||"Failed to reach host");return}YD(R.normalizedUrl),C("Connecting to server"),UR();const q=T();if(q<=0){x(!1),C(null),v("Connection timeout after 4 seconds");return}const z=await A(q);if(k.current){if(!z){x(!1),C(null),T()<=0?v("Connection timeout after 4 seconds"):v("Could not establish WebSocket connection. Verify host and auth token, then retry");return}x(!1),C("Connected"),v(null)}},[f,m,A]),_=b.useCallback(O=>{O.key==="Enter"&&!m&&D()},[D,m]),I=b.useCallback(()=>{n(!0)},[]);return t||e?null:r&&c?o.jsxs("div",{className:"reconnecting-toast",children:[o.jsx("span",{className:"reconnecting-spinner"}),"Reconnecting..."]}):r?null:o.jsx("div",{className:"not-connected-overlay",children:o.jsxs("div",{className:"not-connected-panel",children:[o.jsx("h2",{className:"not-connected-title",children:"Tide Commander"}),o.jsx("p",{className:"not-connected-description",children:"A visual multi-agent orchestrator for Claude Code and Codex. Deploy, control, and monitor your AI team from an RTS-inspired interface."}),o.jsx("p",{className:"not-connected-privacy",children:"Tide Commander syncs with Claude Code instances running on your local machine. No files or code are sent to this server."}),o.jsxs("div",{className:"not-connected-setup",children:[o.jsx("p",{className:"not-connected-setup-label",children:"Get started:"}),o.jsxs("div",{className:"not-connected-code",onClick:E,title:"Click to copy",children:[o.jsx("span",{children:"bunx tide-commander"}),o.jsx("span",{className:"not-connected-copy-icon",children:s?"✓":"⧉"})]})]}),o.jsxs("div",{className:"not-connected-url-section",children:[o.jsx("label",{className:"not-connected-url-label",htmlFor:"backend-url",children:"Backend URL"}),o.jsx("div",{className:"not-connected-url-row",children:o.jsx("input",{id:"backend-url",type:"text",className:"not-connected-url-input",placeholder:"http://localhost:6200",value:f,disabled:m,onChange:O=>{const T=O.target.value;h(T),y&&v(null)},onKeyDown:_})}),o.jsx("span",{className:"config-hint",children:"Leave empty for auto-detect"}),S&&!y&&o.jsx("div",{className:"not-connected-status","aria-live":"polite",children:S}),y&&o.jsx("div",{className:"not-connected-error","aria-live":"assertive",children:y})]}),o.jsxs("div",{className:"not-connected-actions",children:[o.jsx("button",{className:"not-connected-btn not-connected-btn-retry",onClick:()=>{D()},disabled:m,children:m?"Connecting...":"↻ Connect"}),o.jsx("button",{className:"not-connected-btn not-connected-btn-explore",onClick:I,children:"Explore"})]})]})})}const IA="tide-onboarding-dismissed";function Tq({onCreateAgent:t}){const{t:e}=pt("common"),n=Oj(),s=Mj(),[a,r]=b.useState(()=>sessionStorage.getItem(IA)==="1"),i=n&&!a&&s===0,c=b.useCallback(()=>{r(!0),sessionStorage.setItem(IA,"1")},[]),d=b.useCallback(()=>{c(),t()},[c,t]),f=b.useCallback(h=>{h.key==="Escape"&&c()},[c]);return i?o.jsx(or,{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 RT(){return{"Content-Type":"application/json","X-Auth-Token":Ti()}}async function Eq(t){const e=await fetch(`${Ca()}/api/areas/${t}/organize`,{method:"POST",headers:RT()});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 _q(){const t=await fetch(`${Ca()}/api/areas/organize-all`,{method:"POST",headers:RT()});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 OT(t,e){var s,a;const n=H.getState();for(const r of t.organized){const i=n.agents.get(r.agentId);if(i){const c={...i,position:r.position};H.updateAgent(c),(s=e.current)==null||s.updateAgent(c,!0)}}for(const r of t.buildings){const i=n.buildings.get(r.buildingId);i&&(H.updateBuilding(r.buildingId,{position:r.position}),(a=e.current)==null||a.updateBuilding({...i,position:r.position}))}}function Mq(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;H.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:()=>{H.selectAgent(e.id),H.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;H.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:()=>{H.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;H.bringAreaToFront(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),i.push({id:"send-to-back",label:"Send to Back",icon:"⬇️",onClick:()=>{var f;H.sendAreaToBack(e.id),(f=r.sceneRef.current)==null||f.syncAreas()}}),d.assignedAgentIds.length>0&&i.push({id:"organize-area",label:"Organize Area",icon:"✨",onClick:()=>{Eq(e.id).then(f=>{OT(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,x;const f=d.assignedAgentIds.length;H.archiveArea(e.id,y=>H.stopAgent(y)),(m=r.sceneRef.current)==null||m.syncAreas(),(x=r.sceneRef.current)==null||x.syncAgents(Array.from(H.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;H.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:()=>{H.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};H.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:()=>{H.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 Dq=Ce.lazy(()=>vt(()=>import("./index-XXW1ctrV.js"),__vite__mapDeps([35,3,1,4,36])).then(t=>({default:t.DatabasePanel}))),Rq=Ce.lazy(()=>vt(()=>import("./PM2LogsModal-CaacRI13.js"),__vite__mapDeps([37,38,3,1,4])).then(t=>({default:t.PM2LogsModal}))),Oq=Ce.lazy(()=>vt(()=>import("./DockerLogsModal-CA2j24QX.js"),__vite__mapDeps([39,38,3,1,4])).then(t=>({default:t.DockerLogsModal}))),Lq=Ce.lazy(()=>vt(()=>import("./BossLogsModal-buht3LyW.js"),__vite__mapDeps([40,38,3,1,4])).then(t=>({default:t.BossLogsModal}))),Pq=Ce.lazy(()=>vt(()=>import("./Scene2DCanvas-chSGLBlj.js"),__vite__mapDeps([41,3,1,4,42])).then(t=>({default:t.Scene2DCanvas}))),Iq=Ce.lazy(()=>vt(()=>import("./index-CxEHgPe3.js"),__vite__mapDeps([43,3,1,4,44])).then(t=>({default:t.DashboardView}))),Bq=Ce.lazy(()=>vt(()=>import("./IframeModal-CvJ6LEIu.js"),__vite__mapDeps([45,3,1,4,46])).then(t=>({default:t.IframeModal}))),Fq=Ce.lazy(()=>vt(()=>import("./SaveSnapshotModal-Didvj3hf.js"),__vite__mapDeps([47,3,1,4])).then(t=>({default:t.SaveSnapshotModal})));function zq(){const{t}=pt(["common","notifications"]),e=b.useRef(null),n=b.useRef(null),s=ss(),a=ss(),r=ss(),i=ss(),c=ss(),d=ss(),f=ss(),h=ss(),m=ss(),x=ss(),y=ss(),v=ss(),S=ss(),C=ss(),k=ss(),N=ss(),A=ss(),E=ss(),D=ss(),_=QD(),I=fL(),O=XD(),T=lR(),[M,R]=b.useState(null),P=JR(),[U,q]=b.useState(!1),[z,F]=b.useState(null),[$,V]=b.useState(null),[G,B]=b.useState(null),[Q,K]=b.useState(null),[W,be]=b.useState(null),[fe,J]=b.useState(null),[xe,je]=b.useState(null),[oe,Ee]=b.useState(null),[Fe,Ve]=b.useState(null),[De,ge]=b.useState(null),Oe=b.useCallback(Ae=>{ge(Ae),Ae&&localStorage.setItem("tide-commander-last-database-building",Ae)},[]),te=b.useCallback(()=>Oe(null),[Oe]),{handleMouseDown:$e,handleClick:se}=ka(te),Ne=b.useCallback(()=>Ve(null),[]),{handleMouseDown:_e,handleClick:pe}=ka(Ne),Ge=b.useRef(fe);Ge.current=fe;const it=b.useCallback(Ae=>{J(Ae)},[]),dt=b.useCallback(()=>Ge.current,[]),ce=b.useRef(null),[X,ne]=b.useState(Aj),[ke,ee]=b.useState(0),[ye,Ie]=b.useState(!1),[He,ue]=b.useState(()=>localStorage.getItem("tide-commander-sidebar-collapsed")==="true"),[de,re]=b.useState(!1),[me,ve]=b.useState(!1),Ue=Ij(),Qe=Hj(),ze=mx(),nt=gx(),ot=Pj(),{showToast:st}=qj(),{showAgentNotification:lt}=YL(),{showBackNavModal:rt,setShowBackNavModal:ht,handleLeave:jt}=wO();lO({showToast:st,showAgentNotification:lt});const[he,Me]=b.useState(!1);b.useEffect(()=>{const Ae=Je=>{var en;((en=Je.detail)==null?void 0:en.mode)==="3d"&&Me(!0)};return window.addEventListener("tide:viewmode-switch-pressed",Ae),()=>{window.removeEventListener("tide:viewmode-switch-pressed",Ae)}},[]),b.useEffect(()=>{Qe==="3d"&&Me(!0)},[Qe]);const Ye=oO({canvasRef:e,selectionBoxRef:n,viewMode:Qe,sceneMountKey:ke,showToast:st,showAgentNotification:lt,toolboxModal:i,contextMenu:O,setHoveredAgentPopup:be,setBuildingPopup:it,getBuildingPopup:dt,openBuildingModal:Ae=>k.open(Ae),openPM2LogsModal:Ae=>je(Ae),openBossLogsModal:Ae=>Ee(Ae),openDatabasePanel:Ae=>Oe(Ae),onSceneLoadingChange:Me}),tt=Mj(),Nt=rr(),zt=hx(),Pt=fx(),It=rL(),Vt=aL(),mt=sL(),ct=Fr(),xt=oL(),Dt=CL(),Sn=AL(),cn=b.useMemo(()=>Array.from(Pt),[Pt]),cs=b.useRef(!1);mj("AppContent"),cO(Ye),uO(Ye),dO(Ye),CO(),fO(Ye,Vt),pO(Ye,ct.powerSaving),b.useEffect(()=>{var Ae;document.title=((Ae=ct.tabTitle)==null?void 0:Ae.trim())||"Tide Commander"},[ct.tabTitle]),b.useEffect(()=>{var Pn,Ws;if(cs.current||typeof window>"u")return;const Ae=new URLSearchParams(window.location.search),Je=(Pn=Ae.get("agentId"))==null?void 0:Pn.trim(),Ct=(Ws=Ae.get("agentName"))==null?void 0:Ws.trim();if(!Je&&!Ct||tt===0)return;const en=H.getState().agents,Ln=Ae.get("openTerminal"),$t=Ln?["1","true","yes"].includes(Ln.toLowerCase()):!0;let At=Je?en.get(Je):void 0;if(!At&&Ct){const Na=Ct.toLowerCase();At=Array.from(en.values()).find(oa=>oa.name.toLowerCase()===Na)}if(!At){console.warn("[DeepLink] No matching agent found for query params",{rawAgentId:Je,rawAgentName:Ct}),cs.current=!0;return}H.selectAgent(At.id),$t&&H.setTerminalOpen(!0),Ae.delete("agentId"),Ae.delete("agentName"),Ae.delete("openTerminal");const Nn=Ae.toString(),Cs=`${window.location.pathname}${Nn?`?${Nn}`:""}${window.location.hash}`;window.history.replaceState({},document.title,Cs),cs.current=!0},[tt]),vO({sceneRef:Ye,spawnModal:s,commanderModal:c,explorerModal:_,spotlightModal:h,deleteConfirmModal:d,onRequestBuildingDelete:()=>K("selected"),onOpenDatabasePanel:Oe,onCloseDatabasePanel:te,databasePanelOpen:De!==null}),Qt("spawn-modal",s.isOpen,s.close),Qt("boss-spawn-modal",a.isOpen,a.close),Qt("subordinate-modal",r.isOpen,r.close),Qt("toolbox-modal",i.isOpen,i.close),Qt("commander-modal",c.isOpen,c.close),Qt("delete-confirm-modal",d.isOpen,d.close),Qt("supervisor-modal",f.isOpen,f.close),Qt("spotlight-modal",h.isOpen,h.close),Qt("controls-modal",m.isOpen,m.close),Qt("skills-modal",x.isOpen,x.close),Qt("integrations-modal",y.isOpen,y.close),Qt("monitoring-modal",v.isOpen,v.close),Qt("workflow-editor-modal",S.isOpen,S.close),Qt("trigger-manager-modal",C.isOpen,C.close),Qt("building-modal",k.isOpen,k.close),Qt("agent-edit-modal",N.isOpen,N.close),Qt("snapshots-modal",A.isOpen,A.close),Qt("save-snapshot-modal",E.isOpen,E.close),Qt("explorer-modal",_.isOpen||I!==null,()=>{_.close(),H.closeFileExplorer()}),Qt("context-menu",O.isOpen,O.close),Qt("mobile-sidebar",ye,()=>Ie(!1)),Qt("mobile-fab-menu",me,()=>ve(!1)),Qt("file-viewer",ze!==null,()=>H.clearFileViewerPath()),Qt("context-modal",nt!==null,()=>H.closeContextModal()),Qt("terminal",ot,()=>H.setTerminalOpen(!1)),Qt("pm2-logs-modal",xe!==null,()=>je(null)),Qt("boss-logs-modal",oe!==null,()=>Ee(null)),Qt("database-panel",De!==null,te),Qt("terminal-modal",Fe!==null,Ne);const Ba=b.useRef(ot),Es=b.useRef(x),Us=b.useRef(m);Es.current=x,Us.current=m,b.useEffect(()=>{Ba.current&&!ot&&(Es.current.close(),Us.current.close()),Ba.current=ot},[ot]),b.useEffect(()=>{},[]),b.useEffect(()=>{if(Ue!=="3d"||Qe!=="3d")return;const Ae=setTimeout(()=>window.dispatchEvent(new Event("resize")),80);return()=>clearTimeout(Ae)},[Ue,Qe]);const Fa=b.useCallback(Ae=>{var Je,Ct,en,Ln,$t,At,Nn,Cs,Pn,Ws;ne(Ae),rO(Ae),(Je=Ye.current)==null||Je.setCharacterScale(Ae.characterScale),(Ct=Ye.current)==null||Ct.setScale3D(Ae.scale3d),(en=Ye.current)==null||en.setTimeMode(Ae.timeMode),(Ln=Ye.current)==null||Ln.setTerrainConfig(Ae.terrain),($t=Ye.current)==null||$t.setFloorStyle(Ae.terrain.floorStyle),(At=Ye.current)==null||At.setGridVisible(Ae.gridVisible),(Nn=Ye.current)==null||Nn.setAgentModelStyle(Ae.modelStyle),(Cs=Ye.current)==null||Cs.setIdleAnimation(Ae.animations.idleAnimation),(Pn=Ye.current)==null||Pn.setWorkingAnimation(Ae.animations.workingAnimation),(Ws=Ye.current)==null||Ws.setFpsLimit(Ae.fpsLimit)},[Ye]),Ss=b.useCallback(Ae=>{var Je;if((Je=Ye.current)==null||Je.setDrawingTool(Ae),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(Ae),Ae==="rectangle"||Ae==="circle"){const Ct=t(Ae==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool");st("info",Ct,t("notifications:drawing.clickAndDrag"),3e3)}},[Ye,st]),es=b.useCallback(Ae=>{var Je;(Je=Ye.current)==null||Je.focusAgent(Ae)},[Ye]),Mt=b.useCallback(Ae=>{H.killAgent(Ae)},[]),is=b.useCallback(Ae=>{var Je;(Je=Ye.current)==null||Je.callSubordinates(Ae)},[Ye]),fn=b.useCallback(Ae=>{_.open(Ae)},[_]),ur=b.useCallback(()=>{k.open(null)},[k]),Ur=b.useCallback(()=>{var Ae;(Ae=Ye.current)==null||Ae.setDrawingTool("rectangle"),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool("rectangle"),st("info",t("notifications:drawing.rectangleTool"),t("notifications:drawing.clickAndDrag"),3e3)},[Ye,st]),_s=b.useCallback(Ae=>{R(Ae)},[]),Ms=b.useCallback(()=>{R(null)},[]),_i=b.useCallback(()=>{const Ae=Array.from(H.getState().selectedAgentIds);Ae.forEach(Je=>{var Ct;H.removeAgentFromServer(Je),(Ct=Ye.current)==null||Ct.removeAgent(Je)}),d.close(),st("info",t("notifications:toast.agentsRemoved"),t("notifications:toast.agentsRemovedMsg",{count:Ae.length}))},[st,d,Ye,t]),wo=b.useCallback(()=>{var Ae,Je;if(Q==="selected"){const Ct=It.size;H.deleteSelectedBuildings(),(Ae=Ye.current)==null||Ae.syncBuildings(),st("info",t("notifications:toast.buildingsDeleted"),t("notifications:toast.buildingsDeletedMsg",{count:Ct}))}else if(Q){const Ct=zt.get(Q);H.deleteBuilding(Q),(Je=Ye.current)==null||Je.syncBuildings(),st("info",t("notifications:toast.buildingDeleted"),t("notifications:toast.buildingDeletedMsg",{name:(Ct==null?void 0:Ct.name)||"Building"}))}K(null)},[Q,zt,It.size,st,Ye,t]),Wr=b.useMemo(()=>Mq(O.worldPosition,O.target,H.getState().agents,Nt,zt,{showToast:st,openSpawnModal:()=>s.open(),openBossSpawnModal:()=>a.open(),openToolboxModal:()=>i.open(),openCommanderModal:()=>c.open(),openExplorerModal:Ae=>_.open(Ae),openBuildingModal:Ae=>k.open(Ae),openAgentEditModal:Ae=>N.open(Ae),requestBuildingDelete:Ae=>K(Ae),setSpawnPosition:F,openRestoreArchivedModal:Ae=>D.open(Ae),sceneRef:Ye}),[O.worldPosition,O.target,Nt,zt,s,a,k,i,c,_,N,D,st,Ye]);b.useEffect(()=>{!s.isOpen&&!a.isOpen&&(F(null),B(null))},[s.isOpen,a.isOpen]),b.useEffect(()=>{const Ae=$t=>{const At=$t.detail;B((At==null?void 0:At.areaId)||null),F((At==null?void 0:At.position)||null),s.open()},Je=$t=>{var Cs,Pn;const At=$t.detail;if(!(At!=null&&At.buildingId))return;const Nn=H.getState().buildings.get(At.buildingId);Nn&&(Nn.type==="server"&&((Cs=Nn.pm2)!=null&&Cs.enabled)?je(At.buildingId):Nn.type==="boss"?Ee(At.buildingId):Nn.type==="database"?Oe(At.buildingId):Nn.type==="folder"&&Nn.folderPath?H.openFileExplorer(Nn.folderPath):Nn.type==="terminal"&&((Pn=Nn.terminalStatus)!=null&&Pn.url)?Ve(At.buildingId):k.open(At.buildingId))},Ct=$t=>{const At=$t.detail;At!=null&&At.buildingId&&k.open(At.buildingId)},en=$t=>{const At=$t.detail;V((At==null?void 0:At.position)||null),k.open(null)},Ln=$t=>{const At=$t.detail;At!=null&&At.buildingId?Ve(At.buildingId):At!=null&&At.url&&R(At.url)};return window.addEventListener("tide:open-spawn-modal",Ae),window.addEventListener("tide:building-action",Je),window.addEventListener("tide:building-edit",Ct),window.addEventListener("tide:building-create",en),window.addEventListener("tide:open-iframe-modal",Ln),()=>{window.removeEventListener("tide:open-spawn-modal",Ae),window.removeEventListener("tide:building-action",Je),window.removeEventListener("tide:building-edit",Ct),window.removeEventListener("tide:building-create",en),window.removeEventListener("tide:open-iframe-modal",Ln)}},[s,k]);const Il=mt==="rectangle"||mt==="circle",bs=b.useCallback(()=>{var Ae;(Ae=Ye.current)==null||Ae.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null)},[Ye]),ja=b.useCallback(()=>ve(Ae=>!Ae),[]),us=b.useCallback(()=>H.setMobileView("terminal"),[]),Gn=b.useCallback(()=>Ie(!0),[]),qr=cn.length===1&&H.getOutputs(cn[0]).length>0;return o.jsxs("div",{className:`app ${ot?"terminal-open":""} ${Il?"drawing-mode":""} ${He?"sidebar-collapsed":""} mobile-view-${Ue} view-mode-${Qe}`,children:[o.jsx(Nq,{}),o.jsx(Tq,{onCreateAgent:s.open}),o.jsx(YW,{visible:ct.showFPS,position:"bottom-right"}),o.jsxs("div",{className:"app-top-bar",children:[o.jsx(XW,{className:"app-view-mode-toggle"}),o.jsx(kj,{}),o.jsxs("button",{className:"app-organize-all-btn",disabled:U,title:"Auto-organize all agents in their areas",onClick:()=>{q(!0),_q().then(Ae=>{OT(Ae,Ye),st("success","Organized",`Arranged ${Ae.organized.length} agent${Ae.organized.length!==1?"s":""}`)}).catch(Ae=>{console.error("organize all error:",Ae),st("error","Organize Failed",Ae.message||"Failed to organize")}).finally(()=>q(!1))},children:[U?"⏳":"✨"," Organize"]})]}),o.jsxs("main",{className:"main-content",children:[o.jsxs("div",{className:"battlefield-container",children:[P&&o.jsxs("div",{className:"workspace-switch-overlay",children:[o.jsx("div",{className:"workspace-switch-spinner"}),o.jsx("span",{className:"workspace-switch-text",children:"Switching workspace..."})]}),o.jsx(Ce.Suspense,{fallback:null,children:Qe==="dashboard"?o.jsx(Iq,{onSelectAgent:Ae=>H.selectAgent(Ae),onFocusAgent:Ae=>{H.setViewMode("3d"),es(Ae)},onKillAgent:Mt,onSelectBuilding:Ae=>H.selectBuilding(Ae),onOpenTerminal:Ae=>{H.selectAgent(Ae),H.setTerminalOpen(!0)},onFocusZone:Ae=>{H.setViewMode("3d");const Je=H.getState().areas.get(Ae);Je&&Je.assignedAgentIds.length>0&&es(Je.assignedAgentIds[0])}}):Qe==="2d"?o.jsx(Pq,{onAgentClick:(Ae,Je)=>{Je?H.addToSelection(Ae):H.selectAgent(Ae)},onAgentDoubleClick:Ae=>{if(window.innerWidth<=768){H.openTerminalOnMobile(Ae);return}H.selectAgent(Ae),H.setTerminalOpen(!0)},onBuildingClick:(Ae,Je)=>{H.selectBuilding(Ae);const Ct=H.getState().buildings.get(Ae);(Ct==null?void 0:Ct.type)==="folder"&&Ct.folderPath?H.openFileExplorer(Ct.folderPath):((Ct==null?void 0:Ct.type)==="server"||(Ct==null?void 0:Ct.type)==="boss"||(Ct==null?void 0:Ct.type)==="database")&&(ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{it({buildingId:Ae,screenPos:Je,fromClick:!0}),ce.current=null},150))},onBuildingDoubleClick:Ae=>{var Ct;ce.current&&(clearTimeout(ce.current),ce.current=null),it(null);const Je=H.getState().buildings.get(Ae);(Je==null?void 0:Je.type)==="server"&&((Ct=Je.pm2)!=null&&Ct.enabled)?je(Ae):(Je==null?void 0:Je.type)==="boss"?Ee(Ae):(Je==null?void 0:Je.type)==="database"?Oe(Ae):(Je==null?void 0:Je.type)==="folder"&&Je.folderPath?H.openFileExplorer(Je.folderPath):k.open(Ae)},onGroundClick:()=>{H.selectAgent(null),H.selectBuilding(null)},onAreaDoubleClick:Ae=>{H.selectArea(Ae),i.open()},onContextMenu:(Ae,Je,Ct)=>{const en=Ct?{type:Ct.type,id:Ct.id}:{type:"ground"};O.open(Ae,Je,en)},onMoveCommand:(Ae,Je)=>{const en=Ae.length,Ln=[];if(en===1)Ln.push({x:Je.x,y:0,z:Je.z});else if(en<=6){const $t=1.2*Math.max(1,en/3);for(let At=0;At<en;At++){const Nn=At/en*Math.PI*2-Math.PI/2;Ln.push({x:Je.x+Math.cos(Nn)*$t,y:0,z:Je.z+Math.sin(Nn)*$t})}}else{const $t=Math.ceil(Math.sqrt(en)),At=Math.ceil(en/$t),Nn=($t-1)*1.2/2,Cs=(At-1)*1.2/2;for(let Pn=0;Pn<en;Pn++){const Ws=Pn%$t,Na=Math.floor(Pn/$t);Ln.push({x:Je.x+Ws*1.2-Nn,y:0,z:Je.z+Na*1.2-Cs})}}Ae.forEach(($t,At)=>{H.moveAgent($t,Ln[At])})},onBuildingDragMove:(Ae,Je)=>{var en;const Ct=H.getState().buildings.get(Ae);Ct&&(H.getState().buildings.set(Ae,{...Ct,position:{x:Je.x,z:Je.z}}),(en=window.__tideScene2D)==null||en.syncBuildings())},onBuildingDragEnd:(Ae,Je)=>{H.updateBuildingPosition(Ae,Je)},scale2d:X.scale2d,showTaskLabels:X.show2DTaskLabels,showGrid:X.gridVisible,fpsLimit:X.fpsLimit}):o.jsxs(Ce.Fragment,{children:[o.jsx("canvas",{ref:e,id:"battlefield",tabIndex:0}),o.jsx("div",{ref:n,id:"selection-box"})]},ke)}),he&&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(JW,{isOpen:me,onToggle:ja,onShowTerminal:us,onOpenSidebar:Gn,onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:x.open,onOpenSnapshots:A.open,onTakeSnapshot:E.open,canTakeSnapshot:qr,mobileView:Ue}),ye&&o.jsx("div",{className:"sidebar-overlay",onClick:()=>Ie(!1)}),!1,o.jsx("button",{className:`sidebar-collapse-edge-btn ${He?"is-collapsed":""} ${de?"can-pin":""}`,onClick:()=>{if(window.innerWidth<=768)Ie(!ye);else{const Je=!He;ue(Je),localStorage.setItem("tide-commander-sidebar-collapsed",String(Je))}},title:He?"Open sidebar":"Close sidebar",children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:de?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:He?"15 18 9 12 15 6":"9 18 15 12 9 6"})})}),o.jsxs("aside",{className:`sidebar ${ye?"sidebar-open":""} ${He?"sidebar-collapsed":""}`,children:[o.jsx("button",{className:"sidebar-close-btn show-on-mobile",onClick:()=>Ie(!1),title:"Close sidebar",children:"✕"}),cn.length>0?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(b.Profiler,{id:"UnitPanel",onRender:Kc,children:o.jsx(fS,{onFocusAgent:es,onKillAgent:Mt,onCallSubordinates:is,onOpenAreaExplorer:fn})})}),o.jsx("div",{className:"sidebar-section tool-history-section",children:o.jsx(b.Profiler,{id:"ToolHistory",onRender:Kc,children:o.jsx(K4,{agentIds:cn})})})]}):o.jsx("div",{className:"sidebar-section unit-section",children:o.jsx(b.Profiler,{id:"UnitPanel",onRender:Kc,children:o.jsx(fS,{onFocusAgent:es,onKillAgent:Mt,onCallSubordinates:is,onOpenAreaExplorer:fn})})})]}),o.jsx(b.Profiler,{id:"GuakeOutputPanel",onRender:Kc,children:o.jsx(NW,{onSaveSnapshot:E.open})})]}),o.jsx(ZW,{onOpenToolbox:i.open,onOpenCommander:c.open,onOpenSupervisor:f.open,onOpenControls:m.open,onOpenSkills:x.open,onOpenSnapshots:A.open,isGeneratingReport:xt,pip:T}),o.jsx(BW,{activeTool:mt,onExit:bs}),W&&(()=>{const Ae=H.getState().agents.get(W.agentId);return Ae?o.jsx($W,{agent:Ae,screenPos:W.screenPos,onClose:()=>be(null)}):null})(),fe&&(()=>{const Ae=zt.get(fe.buildingId);if(!Ae)return null;const Je=()=>it(null);return Ae.type==="boss"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(VW,{building:Ae,screenPos:fe.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(fe.buildingId)},onOpenLogsModal:()=>{Je(),Ee(fe.buildingId)},onOpenUrlInModal:_s})]}):Ae.type==="database"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(GW,{building:Ae,screenPos:fe.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(fe.buildingId)},onOpenDatabasePanel:()=>{Je(),Oe(fe.buildingId)}})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"building-popup-backdrop",onClick:Je}),o.jsx(UW,{building:Ae,screenPos:fe.screenPos,onClose:Je,onOpenSettings:()=>{Je(),k.open(fe.buildingId)},onOpenLogsModal:()=>{je(fe.buildingId)},onOpenUrlInModal:_s})]})})(),xe&&(()=>{var Je;const Ae=zt.get(xe);return Ae?(Je=Ae.docker)!=null&&Je.enabled?o.jsx(Oq,{building:Ae,isOpen:!0,onClose:()=>je(null)}):o.jsx(Rq,{building:Ae,isOpen:!0,onClose:()=>je(null)}):null})(),oe&&(()=>{const Ae=zt.get(oe);return Ae?o.jsx(Lq,{building:Ae,isOpen:!0,onClose:()=>Ee(null)}):null})(),De&&(()=>{const Ae=zt.get(De);return Ae?o.jsx("div",{className:"modal-overlay visible",onMouseDown:$e,onClick:se,children:o.jsx("div",{className:"database-panel-modal",children:o.jsx(Dq,{building:Ae,onClose:te})})}):null})(),Fe&&(()=>{var Je;const Ae=zt.get(Fe);return!Ae||!((Je=Ae.terminalStatus)!=null&&Je.url)?null:o.jsx("div",{className:"modal-overlay visible",onMouseDown:_e,onClick:pe,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 - ",Ae.name]}),o.jsx("button",{className:"terminal-modal-close",onClick:Ne,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(Kb,{terminalUrl:Ae.terminalStatus.url,visible:!0})]})})})(),o.jsx(yq,{pip:T,title:"Tide Commander - Agents",children:o.jsx(Sq,{})}),o.jsx(Bq,{url:M||"",title:M?`Preview - ${M}`:"",isOpen:!!M,onClose:Ms}),E.isOpen&&cn.length===1&&(()=>{const Ae=cn[0],Je=H.getState().agents.get(Ae);if(!Je)return null;const Ct=H.getOutputs(Ae);return o.jsx(Fq,{isOpen:E.isOpen,onClose:E.close,agent:Je,outputCount:Ct.length,onSave:async en=>{try{const Ln=Ct.map($t=>({type:"message",content:$t.text,timestamp:new Date($t.timestamp).toISOString()}));await H.createSnapshot(en.agentId,Je.name,en.title,en.description,Ln,[]),E.close(),st("success",t("notifications:toast.snapshotSaved"),t("notifications:toast.snapshotSavedMsg"))}catch(Ln){const $t=Ln instanceof Error?Ln.message:t("notifications:toast.snapshotFailedMsg");st("error",t("notifications:toast.snapshotFailed"),$t)}},isSaving:Dt,error:Sn||void 0})})(),o.jsx(IW,{onFocusAgent:es,onSpawnClick:s.open,onSpawnBossClick:a.open,onNewBuildingClick:ur,onNewAreaClick:Ur}),o.jsx(xq,{spawnModal:s,bossSpawnModal:a,subordinateModal:r,toolboxModal:i,commanderModal:c,deleteConfirmModal:d,supervisorModal:f,spotlightModal:h,controlsModal:m,skillsModal:x,integrationsModal:y,monitoringModal:v,workflowEditorModal:S,triggerManagerModal:C,buildingModal:k,buildingInitialPosition:$,agentEditModal:N,snapshotsModal:A,restoreArchivedModal:D,explorerModal:_,contextMenu:O,spawnPosition:z,spawnAreaId:G,explorerFolderPath:I,contextMenuActions:Wr,sceneConfig:X,onConfigChange:Fa,onToolChange:Ss,onOpenAreaExplorer:fn,onDeleteSelectedAgents:_i,pendingBuildingDelete:Q,onCancelBuildingDelete:()=>K(null),onConfirmBuildingDelete:wo,showBackNavModal:rt,onCloseBackNavModal:()=>ht(!1),onLeave:jt,onOpenPM2LogsModal:Ae=>je(Ae),onOpenBossLogsModal:Ae=>Ee(Ae),onOpenDatabasePanel:Ae=>Oe(Ae),onSyncScene:()=>{var Ae,Je;(Ae=Ye.current)==null||Ae.syncAreas(),(Je=Ye.current)==null||Je.syncAgents(Array.from(H.getState().agents.values()))}})]})}function $q(){return o.jsx(PL,{children:o.jsx(GL,{children:o.jsx(zq,{})})})}class Hq extends b.Component{constructor(n){super(n);et(this,"handleReload",()=>{window.location.reload()});et(this,"handleDismiss",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(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:"💥"}),En.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:En.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:En.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:En.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:En.t("common:buttons.tryToContinue")})]}),o.jsx("div",{style:{marginTop:"24px",color:"#666",fontSize:"12px"},children:En.t("errors:crash.checkConsole")})]})})}return this.props.children}}S6();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 LT=document.getElementById("app");if(!LT)throw new Error("Could not find #app container");const Uq=jM.createRoot(LT);Uq.render(o.jsx(Ce.StrictMode,{children:o.jsx(b.Suspense,{fallback:o.jsx("div",{style:{background:"#0a0a0a",height:"100vh"}}),children:o.jsx(Hq,{children:o.jsx($q,{})})})}));console.log("[Tide] Tide Commander initialized");export{Lc as $,FL as A,Uj as B,Vn as C,BL as D,GD as E,AV as F,xp as G,Jb as H,Dl as I,hx as J,rr as K,fx as L,pL as M,Aa as N,aV as O,zL as P,TV as Q,YU as R,ft as S,ls as T,wa as U,yV as V,Lt as W,Qj as X,NV as Y,$2 as Z,ou as _,xx as a,go as a$,nf as a0,fg as a1,er as a2,Sp as a3,xV as a4,dx as a5,Wf as a6,Kq as a7,IL as a8,mb as a9,_p as aA,VD as aB,Q5 as aC,N6 as aD,T6 as aE,D6 as aF,oV as aG,Dj as aH,cV as aI,uV as aJ,ex as aK,tx as aL,jf as aM,EV as aN,vt as aO,i1 as aP,jV as aQ,o1 as aR,l1 as aS,du as aT,Rr as aU,Or as aV,L6 as aW,P6 as aX,qj as aY,Yg as aZ,I6 as a_,hV as aa,Ti as ab,Yq as ac,dV as ad,Xx as ae,Zs as af,fu as ag,up as ah,Ca as ai,or as aj,nx as ak,KD as al,En as am,UR as an,YD as ao,mV as ap,gV as aq,bV as ar,pV as as,zj as at,Hk as au,sV as av,Rj as aw,Qt as ax,x5 as ay,uT as az,wL as b,zp as b0,r1 as b1,ra as b2,f1 as b3,z6 as b4,Jx as b5,Fb as b6,z4 as b7,Bj as b8,Sb as b9,rV as ba,iV as bb,bO as bc,xO as bd,z2 as be,nV as bf,eV as bg,lV as bh,kp as bi,t2 as bj,P2 as bk,B2 as bl,vV as bm,_u as bn,Tu as bo,$L as bp,wV as bq,CV as br,kV as bs,tV as bt,Zq as bu,SV as bv,WR as bw,qR as bx,Dc as by,sx as bz,fV as c,kL as d,Qx as e,ws as f,KU as g,ka as h,Sl as i,o as j,$f as k,_t as l,nS as m,kn as n,na as o,Xq as p,Qq as q,b as r,H as s,Xd as t,pt as u,vp as v,Jq as w,QR as x,XR as y,Ce as z};
|