tide-commander 1.121.0 → 1.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/assets/{BossLogsModal-B2YfEJEZ.js → BossLogsModal-CXoqZDpN.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-DM48J6B4.js → BossSpawnModal-CzX1QYrG.js} +1 -1
  3. package/dist/assets/{ControlsModal-DA4RhL4J.js → ControlsModal-DGNNBjod.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-sBpMzoBW.js → DockerLogsModal-DnQ7dM9v.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-B4DsIOre.js → EmbeddedEditor-BsSDGP8s.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-P5i2x2nw.js → GmailOAuthSetup-B4XdOuww.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-DMT3PAQT.js → GoogleOAuthSetup-DLK6CRbP.js} +1 -1
  8. package/dist/assets/{IframeModal-De15ZrD-.js → IframeModal-DiZEnwCM.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-DnnqQ9jg.js → IntegrationsPanel-Qi4tM5pG.js} +2 -2
  10. package/dist/assets/{LogViewerModal-CxqxaPTn.js → LogViewerModal-DLItZUS9.js} +1 -1
  11. package/dist/assets/{MonitoringModal-Sx_u2A3-.js → MonitoringModal-D7vwpchO.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-BVUiu0y3.js → PM2LogsModal-BqaAvixz.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-nhGd5mU0.js → RestoreArchivedAreaModal-DRQ3vjtW.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-H4ZMjV2J.js → Scene2DCanvas-BOOWcRHw.js} +1 -1
  15. package/dist/assets/{SceneManager-Cxww9Amy.js → SceneManager-DcVy331q.js} +1 -1
  16. package/dist/assets/{SkillsPanel-w_4Yp-3y.js → SkillsPanel-DDxbEo7q.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-1AODop87.js → SlackMultiInstanceSetup-DvvrKuof.js} +1 -1
  18. package/dist/assets/{SpawnModal-ByT366Qe.js → SpawnModal-BZDbLxV7.js} +1 -1
  19. package/dist/assets/{StatisticsModal-C2AtvNBi.js → StatisticsModal-BVZjfNbI.js} +1 -1
  20. package/dist/assets/{SubordinateAssignmentModal-Djuc1Qzv.js → SubordinateAssignmentModal-DDmo0X2v.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-CZqweJiZ.js → TriggerManagerPanel-03nnNSkO.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-CdFuJVr6.js → WorkflowEditorPanel-BKfimm1J.js} +1 -1
  23. package/dist/assets/{area-logos-CAaQMgNQ.js → area-logos-TTN-zbpE.js} +1 -1
  24. package/dist/assets/{index-D1URvPh1.js → index-B8r8AK3g.js} +1 -1
  25. package/dist/assets/{index-TX8bidMy.js → index-BdEYVGMt.js} +3 -3
  26. package/dist/assets/{index-D8kPhHUs.js → index-BftfIEt1.js} +1 -1
  27. package/dist/assets/{index-CNtNymjx.js → index-CGDp5q4m.js} +2 -2
  28. package/dist/assets/{index-Dudpmrz0.js → index-CfmHEtZW.js} +1 -1
  29. package/dist/assets/{index-CIZTb6i1.js → index-CzbbjcrH.js} +1 -1
  30. package/dist/assets/{index-tpgIJsjD.js → index-D-bj9X5i.js} +1 -1
  31. package/dist/assets/{index-Bthl5h2s.js → index-DL-EeCs7.js} +1 -1
  32. package/dist/assets/{index-CBHWkTIB.js → index-DcLk1GKO.js} +1 -1
  33. package/dist/assets/main-AIql1MLY.css +1 -0
  34. package/dist/assets/{main-B8YPZvpg.js → main-C7U_3QQV.js} +84 -84
  35. package/dist/assets/{web-BlddCYpD.js → web-C6f8mogx.js} +1 -1
  36. package/dist/assets/{web-BgeuoMBy.js → web-CQes4LC8.js} +1 -1
  37. package/dist/assets/{web-B9FRdWR_.js → web-CuJsjt2R.js} +1 -1
  38. package/dist/index.html +2 -2
  39. package/dist/src/packages/server/codex/backend.js +22 -7
  40. package/dist/src/packages/server/data/builtin-skills/browser-control.js +185 -0
  41. package/dist/src/packages/server/data/builtin-skills/index.js +2 -0
  42. package/dist/src/packages/server/opencode/backend.js +22 -6
  43. package/dist/src/packages/server/routes/agents.js +8 -0
  44. package/dist/src/packages/server/routes/browser.js +45 -8
  45. package/dist/src/packages/server/services/instruction-refresh.js +55 -0
  46. package/dist/src/packages/server/services/skill-service.js +5 -0
  47. package/package.json +1 -1
  48. package/dist/assets/main-C7Dsh8es.css +0 -1
@@ -1,4 +1,4 @@
1
- import{r as l,b1 as Re,b2 as Ye,j as e,I as L,u as Y,b3 as as,ab as ns,f as Ve,s as T,b4 as hs,b5 as ms,aW as gs,b6 as fs,C as he,G as oe,H as Z,h as je,i as ke,m as xs,b7 as bs,b8 as js,b9 as vs,ba as ws,P as Ns,bb as Se,a6 as ys,bc as is,bd as ks,be as Be,bf as Ss,bg as Cs,bh as As,bi as Ts,bj as _s,bk as Is,bl as Es,aQ as Ps,W as Ls,S as ye,bm as $s,bn as Ds,aS as Fs,bo as Ue,X as Ee,a_ as Os,bp as ze,bq as Rs}from"./main-B8YPZvpg.js";import{g as Us,d as zs,u as Ms}from"./area-logos-CAaQMgNQ.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ke="deivid11/tide-commander",Bs=`https://api.github.com/repos/${Ke}/releases/latest`,Vs=`https://api.github.com/repos/${Ke}/releases?per_page=3`,Ks=3600*1e3,Je="app_update_dismissed_version",Ze="1.121.0";function Hs(){var y,C;const[s,i]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Ze}),t=((C=(y=Re)==null?void 0:y.getPlatform)==null?void 0:C.call(y))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),d=(u,p)=>{const g=o(u),v=o(p),j=Math.max(g.length,v.length);for(let m=0;m<j;m++){const k=g[m]||0,$=v[m]||0;if(k>$)return 1;if(k<$)return-1}return 0},r=async u=>{var g,v;if(Re&&Ye&&((v=(g=Re).isNativePlatform)==null?void 0:v.call(g))===!0){const j=await Ye.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:j.data,status:j.status}}else{const j=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return j.ok?{data:await j.json(),status:j.status}:{data:null,status:j.status}}},c=l.useCallback(async(u=!1)=>{i(p=>({...p,isChecking:!0,error:null}));try{const[p,g]=await Promise.all([r(Bs),r(Vs)]);if(p.status!==200)throw new Error(`GitHub API error: ${p.status}`);const v=p.data,j=v.tag_name;let m=[];g.status===200&&g.data&&(m=g.data.map(w=>({version:w.tag_name,name:w.name,publishedAt:w.published_at,releaseUrl:w.html_url})));const k=localStorage.getItem(Je);if(!u&&k===j)return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;if(!(d(j,Ze)>0))return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;const I=v.assets.find(w=>w.name.endsWith(".apk")&&w.content_type==="application/vnd.android.package-archive"),V={version:j,name:v.name,changelog:v.body,releaseUrl:v.html_url,apkUrl:(I==null?void 0:I.browser_download_url)||null,apkSize:(I==null?void 0:I.size)||null,publishedAt:v.published_at};return i(w=>({...w,isChecking:!1,updateAvailable:!0,updateInfo:V,recentReleases:m})),V}catch(p){const g=p instanceof Error?p.message:"Failed to check for updates";return i(v=>({...v,isChecking:!1,error:g})),null}},[]),f=l.useCallback(async()=>{var u,p,g;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(p=s.updateInfo)!=null&&p.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),i(v=>({...v,error:null}))}catch(v){const j=v instanceof Error?v.message:"Failed to open download";i(m=>({...m,error:j}))}},[s.updateInfo,t]),a=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Je,s.updateInfo.version),i(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),x=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Ke}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),p=setInterval(()=>{c()},Ks);return()=>{clearTimeout(u),clearInterval(p)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:f,dismissUpdate:a,openReleasePage:x}}const os="tide-toolbox-collapse";function Ws(s,i){try{const t=localStorage.getItem(`${os}-${s}`);if(t!==null)return t==="true"}catch{}return i}function qs(s,i){try{localStorage.setItem(`${os}-${s}`,String(i))}catch{}}function K({title:s,storageKey:i,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,f]=l.useState(()=>i?Ws(i,t):t),a=()=>{const y=!c;f(y),i&&qs(i,y)},x=o||c;return e.jsxs("div",{className:`collapsible-section ${x?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:a,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[r,e.jsx("span",{className:"collapsible-arrow",children:e.jsx(L,{name:x?"caret-down":"caret-right",size:10})})]})]}),x&&e.jsx("div",{className:"collapsible-content",children:d})]})}function Gs({area:s,isSelected:i,onClick:t,onDelete:o}){const{t:d}=Y(["config","common"]),r=s.assignedAgentIds.length,c=s.type==="rectangle"?d("config:areas.rect"):d("config:areas.circle");return e.jsxs("div",{className:`area-item ${i?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"area-color-dot",style:{backgroundColor:s.color}}),e.jsxs("div",{className:"area-info",children:[e.jsx("div",{className:"area-name",children:s.name}),e.jsxs("div",{className:"area-meta",children:[c," ",r>0&&`• ${r} ${r>1?d("common:labels.agents").toLowerCase():d("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:o,title:d("config:areas.deleteArea"),children:"×"})]})}function Ys({building:s,isSelected:i,onClick:t,onEdit:o}){var f;const{t:d}=Y(["config"]),r=((f=s.pm2Status)==null?void 0:f.ports)||[],c=(a,x)=>{a.stopPropagation(),window.open(`http://${window.location.hostname}:${x}`,"_blank")};return e.jsxs("div",{className:`building-item ${i?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:as[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(L,{name:ns(s.type),size:16})}),e.jsxs("div",{className:"building-info",children:[e.jsx("div",{className:"building-name",children:s.name}),e.jsxs("div",{className:"building-meta",children:[s.type,r.length>0&&e.jsx("span",{className:"building-ports",children:r.map(a=>e.jsxs("a",{href:`http://${window.location.hostname}:${a}`,className:"building-port-link",onClick:x=>c(x,a),title:`Open :${a}`,children:[":",a]},a))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:a=>{a.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx(L,{name:"gear",size:14})})]})}function Js({building:s,onClose:i,onOpenModal:t}){var x,y,C,u,p,g,v,j;const{t:o}=Y(["config","common"]),{buildingLogs:d}=Ve(),r=T.getBuildingLogs(s.id),c=hs[s.style||"server-rack"],f=m=>{T.sendBuildingCommand(s.id,m)},a=m=>{window.open(m,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx(L,{name:ns(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:as[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:i,children:"×"})]}),e.jsx("div",{className:"building-editor-section",children:e.jsxs("div",{className:"building-editor-info-grid",children:[e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("common:labels.type")}),e.jsx("span",{className:"building-editor-info-value",children:s.type})]}),e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:c.label})]}),s.cwd&&e.jsxs("div",{className:"building-editor-info-item building-editor-info-wide",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.directory")}),e.jsx("span",{className:"building-editor-info-value building-editor-cwd",title:s.cwd,children:s.cwd.split("/").pop()||s.cwd})]})]})}),s.type==="server"&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>f("start"),disabled:!((x=s.commands)!=null&&x.start)||s.status==="running",title:((y=s.commands)==null?void 0:y.start)||o("config:buildings.noStartCommand"),children:[e.jsx(L,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>f("stop"),disabled:!((C=s.commands)!=null&&C.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx(L,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>f("restart"),disabled:!((p=s.commands)!=null&&p.restart),title:((g=s.commands)==null?void 0:g.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx(L,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>f("healthCheck"),disabled:!((v=s.commands)!=null&&v.healthCheck),title:((j=s.commands)==null?void 0:j.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx(L,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((m,k)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>a(m.url),title:m.url,children:[e.jsx(L,{name:"link",size:12})," ",m.label||m.url]},k))})]}),r.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[o("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>T.clearBuildingLogs(s.id),title:o("common:buttons.clear"),children:o("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:r.slice(-5).map((m,k)=>e.jsx("div",{className:"building-editor-log-entry",children:m},k))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx(L,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const Zs=[{key:"center",labelKey:"posCenter"},{key:"top-left",labelKey:"posTopLeft"},{key:"top-right",labelKey:"posTopRight"},{key:"bottom-left",labelKey:"posBottomLeft"},{key:"bottom-right",labelKey:"posBottomRight"}];function Xs({area:s,onClose:i,onOpenFolder:t}){var Q;const{t:o}=Y(["config","common"]),[d,r]=l.useState(s.name),[c,f]=l.useState(s.prompt||""),[a,x]=l.useState(!1),[y,C]=l.useState(""),[u,p]=l.useState(!1),g=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{f(s.prompt||"")},[s.id,s.prompt]);const v=N=>{const D=N.target.value;r(D),T.updateArea(s.id,{name:D})},j=N=>{T.updateArea(s.id,{color:N})},m=N=>{const D=N.target.value;f(D),T.updateArea(s.id,{prompt:D})},k=()=>{y.trim()&&(T.addDirectoryToArea(s.id,y.trim()),C(""),x(!1))},$=(N,D)=>{D.stopPropagation(),T.removeDirectoryFromArea(s.id,N)},I=()=>{T.bringAreaToFront(s.id)},V=()=>{T.sendAreaToBack(s.id)},w=l.useCallback(()=>{let N=2,D=2;s.type==="rectangle"&&s.width&&s.height?(N=s.width,D=s.height):s.type==="circle"&&s.radius&&(N=s.radius*1.414,D=s.radius*1.414);const B=Math.min(N,D)*.4;return{width:Math.round(B*10)/10,height:Math.round(B*10)/10}},[s.type,s.width,s.height,s.radius]),O=async N=>{var B;const D=(B=N.target.files)==null?void 0:B[0];if(D){p(!0);try{const h=await Ms(s.id,D),E=w();T.updateArea(s.id,{logo:{filename:h.filename,position:"center",width:E.width,height:E.height,keepAspectRatio:!0,opacity:.8}})}catch(h){console.error("Failed to upload logo:",h)}finally{p(!1),g.current&&(g.current.value="")}}},z=async()=>{try{await zs(s.id),T.updateArea(s.id,{logo:void 0})}catch(N){console.error("Failed to remove logo:",N)}},H=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,position:N}})},S=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const B=s.logo.height/s.logo.width;T.updateArea(s.id,{logo:{...s.logo,width:D,height:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,width:D}})},R=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const B=s.logo.width/s.logo.height;T.updateArea(s.id,{logo:{...s.logo,height:D,width:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,height:D}})},W=()=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},J=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(N.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:o("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:i,children:"×"})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:d,onChange:v,placeholder:o("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:ms.map(N=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===N?"selected":""}`,style:{backgroundColor:N},onClick:()=>j(N),"aria-label":`Set area color ${N}`,"aria-pressed":s.color===N,title:N},N))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:I,title:o("config:areas.bringToFront"),children:[e.jsx(L,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:V,title:o("config:areas.sendToBack"),children:[e.jsx(L,{name:"arrow-down",size:12})," ",o("config:areas.back")]})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(Q=s.logo)!=null&&Q.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:Us(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:z,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":e.jsx(L,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Zs.map(({key:N,labelKey:D})=>{var B;return e.jsx("button",{className:`area-logo-pos-btn ${((B=s.logo)==null?void 0:B.position)===N?"active":""}`,onClick:()=>H(N),children:o(`config:areas.${D}`)},N)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:S,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:R,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:o("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:W}),o("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoOpacity")}),e.jsxs("div",{className:"area-logo-opacity-row",children:[e.jsx("input",{type:"range",min:0,max:1,step:.05,value:s.logo.opacity??.8,onChange:J,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:g,type:"file",accept:"image/*",style:{display:"none"},onChange:O})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(N=>e.jsxs("div",{className:"area-folder-item",title:N,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx(L,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:N.split("/").pop()||N}),e.jsx("button",{className:"area-folder-remove",onClick:D=>$(N,D),title:o("config:areas.removeFolder"),children:"×"})]},N)),a?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(gs,{value:y,onChange:C,onSubmit:k,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:k,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>x(!0),children:o("config:areas.addFolder")})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:c,onChange:m,placeholder:o("config:areas.promptPlaceholder","System prompt for agents in this area..."),rows:4,style:{resize:"vertical",fontFamily:"monospace",fontSize:12}}),e.jsx("div",{style:{fontSize:11,color:"var(--text-secondary)",marginTop:4},children:o("config:areas.promptHint","This prompt is injected into agents assigned to this area. Takes effect on next context refresh.")})]}),s.assignedAgentIds.length>0&&e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:o("config:areas.rightClickUnassign")})]})]})}function Qs(){const{t:s}=Y(["config","common"]),i=fs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,f]=l.useState({name:"",key:"",value:"",description:""}),[a,x]=l.useState(null),y=()=>{o(!0),r(null),f({name:"",key:"",value:"",description:""})},C=m=>{r(m.id),o(!1),f({name:m.name,key:m.key,value:m.value,description:m.description||""})},u=()=>{o(!1),r(null),f({name:"",key:"",value:"",description:""})},p=()=>{!c.name.trim()||!c.key.trim()||(d?T.updateSecret(d,{name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}):T.createSecret({name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}),u())},g=m=>{x(m)},v=()=>{a&&(T.deleteSecret(a),d===a&&u())},j=m=>{navigator.clipboard.writeText(`{{${m}}}`)};return e.jsxs("div",{className:"secrets-section",children:[e.jsx("div",{className:"secrets-description",children:s("config:secrets.description",{placeholder:"{{KEY}}"})}),e.jsx("div",{className:"secrets-list",children:i.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):i.map(m=>e.jsxs("div",{className:`secret-item ${d===m.id?"editing":""}`,children:[e.jsxs("div",{className:"secret-item-header",children:[e.jsxs("div",{className:"secret-item-info",children:[e.jsx("span",{className:"secret-item-name",children:m.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>j(m.key),title:s("config:secrets.copyPlaceholder"),children:`{{${m.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>C(m),title:s("common:buttons.edit"),children:e.jsx(L,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>g(m.id),title:s("common:buttons.delete"),children:"×"})]})]}),m.description&&e.jsx("div",{className:"secret-item-description",children:m.description})]},m.id))}),(t||d)&&e.jsxs("div",{className:"secret-form",children:[e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.name")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.namePlaceholder"),value:c.name,onChange:m=>f({...c,name:m.target.value}),autoFocus:!0})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:"Key"}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.keyPlaceholder"),value:c.key,onChange:m=>f({...c,key:m.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${c.key||"KEY"}}}`})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("config:secrets.secretValue")}),e.jsx("input",{type:"password",className:"secret-form-input",placeholder:s("config:secrets.valuePlaceholder"),value:c.value,onChange:m=>f({...c,value:m.target.value})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.description")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.descriptionPlaceholder"),value:c.description,onChange:m=>f({...c,description:m.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:u,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:p,disabled:!c.name.trim()||!c.key.trim(),children:s(d?"config:secrets.update":"common:buttons.add")})]})]}),!t&&!d&&e.jsx("button",{className:"secrets-add-btn",onClick:y,children:s("config:secrets.addSecret")}),e.jsx(he,{isOpen:a!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:v,onClose:()=>x(null)})]})}async function et(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch echo prompt setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function st(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function tt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch codex binary path: ${i.statusText}`);return(await i.json()).path||""}async function at(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function nt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch tmux mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function it(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function ot(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch interactive mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function lt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function ct(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch backup status: ${i.statusText}`);return i.json()}async function rt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||`Failed to update backup setting: ${t.statusText}`)}return t.json()}function dt({checked:s,onChange:i,disabled:t}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:t,onChange:o=>i(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function ut(){const{t:s}=Y(["config","common"]),[i,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[f,a]=l.useState(!1),[x,y]=l.useState(!1),[C,u]=l.useState(null),[p,g]=l.useState(null),[v,j]=l.useState(null),[m,k]=l.useState(null),[$,I]=l.useState(!1),[V,w]=l.useState(null);l.useEffect(()=>{je(ke("/api/config/categories")).then(h=>h.json()).then(h=>{const E=Array.isArray(h)?h:[];t(E),d(new Set(E.map(F=>F.id)))}).catch(h=>console.error("Failed to fetch config categories:",h))},[]),l.useEffect(()=>{ct().then(k).catch(h=>{console.error("Failed to fetch backup status:",h),w(h.message||"Failed to fetch backup status")})},[]);const O=async h=>{if(!$){I(!0),w(null);try{const E=await rt(h);k(E)}catch(E){w(E.message||"Failed to update backup setting")}finally{I(!1)}}},z=h=>{d(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},H=h=>{c(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},S=()=>d(new Set(i.map(h=>h.id))),R=()=>d(new Set),W=()=>{p&&c(new Set(p.categories.map(h=>h.id)))},J=()=>c(new Set),Q=async()=>{var h;if(o.size!==0){a(!0),j(null);try{const E=Array.from(o).join(","),F=await je(ke(`/api/config/export?categories=${E}`));if(!F.ok)throw new Error("Export failed");const ee=await F.blob(),se=window.URL.createObjectURL(ee),X=document.createElement("a");X.href=se;const A=F.headers.get("Content-Disposition"),q=((h=A==null?void 0:A.match(/filename="(.+)"/))==null?void 0:h[1])||"tide-commander-config.zip";X.download=q,document.body.appendChild(X),X.click(),document.body.removeChild(X),window.URL.revokeObjectURL(se),j({type:"success",text:s("config:data.exportSuccess")})}catch(E){j({type:"error",text:E.message||"Export failed"})}finally{a(!1)}}},N=async h=>{var F;const E=(F=h.target.files)==null?void 0:F[0];if(E){u(E),j(null),g(null),c(new Set);try{const ee=await je(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await E.arrayBuffer()});if(!ee.ok){const A=await ee.json();throw new Error(A.error||"Failed to preview config file")}const se=await ee.json(),X=Array.isArray(se.categories)?se.categories:[];g({...se,categories:X}),c(new Set(X.map(A=>A.id)))}catch(ee){j({type:"error",text:ee.message||"Failed to read config file"}),u(null)}}},D=async()=>{if(!(!C||r.size===0)){y(!0),j(null);try{const h=Array.from(r).join(","),E=await je(ke(`/api/config/import?categories=${h}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await C.arrayBuffer()}),F=await E.json();if(!E.ok)throw new Error(F.error||"Import failed");j({type:"success",text:F.message||s("config:data.importSuccess")}),u(null),g(null),c(new Set)}catch(h){j({type:"error",text:h.message||"Import failed"})}finally{y(!1)}}},B=()=>{u(null),g(null),c(new Set),j(null)};return e.jsxs("div",{className:"data-section",children:[v&&e.jsx("div",{className:`data-message data-message-${v.type}`,children:v.text}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:"Hourly Backups"}),e.jsx(dt,{checked:!!(m!=null&&m.enabled),disabled:$||!m,onChange:O})]}),e.jsxs("div",{className:"data-backup-info",children:[m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:m.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!m.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:m.scriptPath})]}),m.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(m.lastRunAt).toLocaleString(),m.lastRunOk===!0&&" — ok",m.lastRunOk===!1&&m.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",m.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),V&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:V})]})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:s("config:data.exportData")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:S,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:R,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:i.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(h.id),onChange:()=>z(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name})]},h.id))}),e.jsx("button",{className:"data-action-btn export",onClick:Q,disabled:f||o.size===0,children:f?s("config:data.exporting"):s("config:data.exportCount",{count:o.size})})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsx("div",{className:"data-subsection-header",children:e.jsx("span",{className:"data-subsection-title",children:s("config:data.importData")})}),C?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:C.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(p.exportedAt).toLocaleDateString()]})]}),e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-subtitle",children:s("config:data.selectToImport")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:W,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:J,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:p.categories.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(h.id),onChange:()=>H(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name}),h.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",h.fileCount," ",s("config:data.files"),")"]})]},h.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:B,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:D,disabled:x||r.size===0,children:x?s("config:data.importing"):s("config:data.importCount",{count:r.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:N,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function pt(){const s=await je(`${Z()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function ht(s,i){const t=new AbortController;return(async()=>{try{const o=await fetch(xs(`${Z()}/api/system/self-update`),{method:"POST",signal:t.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const f=await o.text().catch(()=>"");let a=null;try{a=JSON.parse(f)}catch{}const x=a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"?a.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:x}),i(new Error(x));return}const d=o.body.getReader(),r=new TextDecoder("utf-8");let c="";for(;;){const{value:f,done:a}=await d.read();if(a)break;c+=r.decode(f,{stream:!0});let x=c.indexOf(`
1
+ import{r as l,b1 as Re,b2 as Ye,j as e,I as L,u as Y,b3 as as,ab as ns,f as Ve,s as T,b4 as hs,b5 as ms,aW as gs,b6 as fs,C as he,G as oe,H as Z,h as je,i as ke,m as xs,b7 as bs,b8 as js,b9 as vs,ba as ws,P as Ns,bb as Se,a6 as ys,bc as is,bd as ks,be as Be,bf as Ss,bg as Cs,bh as As,bi as Ts,bj as _s,bk as Is,bl as Es,aQ as Ps,W as Ls,S as ye,bm as $s,bn as Ds,aS as Fs,bo as Ue,X as Ee,a_ as Os,bp as ze,bq as Rs}from"./main-C7U_3QQV.js";import{g as Us,d as zs,u as Ms}from"./area-logos-TTN-zbpE.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ke="deivid11/tide-commander",Bs=`https://api.github.com/repos/${Ke}/releases/latest`,Vs=`https://api.github.com/repos/${Ke}/releases?per_page=3`,Ks=3600*1e3,Je="app_update_dismissed_version",Ze="1.123.0";function Hs(){var y,C;const[s,i]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Ze}),t=((C=(y=Re)==null?void 0:y.getPlatform)==null?void 0:C.call(y))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),d=(u,p)=>{const g=o(u),v=o(p),j=Math.max(g.length,v.length);for(let m=0;m<j;m++){const k=g[m]||0,$=v[m]||0;if(k>$)return 1;if(k<$)return-1}return 0},r=async u=>{var g,v;if(Re&&Ye&&((v=(g=Re).isNativePlatform)==null?void 0:v.call(g))===!0){const j=await Ye.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:j.data,status:j.status}}else{const j=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return j.ok?{data:await j.json(),status:j.status}:{data:null,status:j.status}}},c=l.useCallback(async(u=!1)=>{i(p=>({...p,isChecking:!0,error:null}));try{const[p,g]=await Promise.all([r(Bs),r(Vs)]);if(p.status!==200)throw new Error(`GitHub API error: ${p.status}`);const v=p.data,j=v.tag_name;let m=[];g.status===200&&g.data&&(m=g.data.map(w=>({version:w.tag_name,name:w.name,publishedAt:w.published_at,releaseUrl:w.html_url})));const k=localStorage.getItem(Je);if(!u&&k===j)return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;if(!(d(j,Ze)>0))return i(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:m})),null;const I=v.assets.find(w=>w.name.endsWith(".apk")&&w.content_type==="application/vnd.android.package-archive"),V={version:j,name:v.name,changelog:v.body,releaseUrl:v.html_url,apkUrl:(I==null?void 0:I.browser_download_url)||null,apkSize:(I==null?void 0:I.size)||null,publishedAt:v.published_at};return i(w=>({...w,isChecking:!1,updateAvailable:!0,updateInfo:V,recentReleases:m})),V}catch(p){const g=p instanceof Error?p.message:"Failed to check for updates";return i(v=>({...v,isChecking:!1,error:g})),null}},[]),f=l.useCallback(async()=>{var u,p,g;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(p=s.updateInfo)!=null&&p.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),i(v=>({...v,error:null}))}catch(v){const j=v instanceof Error?v.message:"Failed to open download";i(m=>({...m,error:j}))}},[s.updateInfo,t]),a=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Je,s.updateInfo.version),i(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),x=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Ke}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),p=setInterval(()=>{c()},Ks);return()=>{clearTimeout(u),clearInterval(p)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:f,dismissUpdate:a,openReleasePage:x}}const os="tide-toolbox-collapse";function Ws(s,i){try{const t=localStorage.getItem(`${os}-${s}`);if(t!==null)return t==="true"}catch{}return i}function qs(s,i){try{localStorage.setItem(`${os}-${s}`,String(i))}catch{}}function K({title:s,storageKey:i,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,f]=l.useState(()=>i?Ws(i,t):t),a=()=>{const y=!c;f(y),i&&qs(i,y)},x=o||c;return e.jsxs("div",{className:`collapsible-section ${x?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:a,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[r,e.jsx("span",{className:"collapsible-arrow",children:e.jsx(L,{name:x?"caret-down":"caret-right",size:10})})]})]}),x&&e.jsx("div",{className:"collapsible-content",children:d})]})}function Gs({area:s,isSelected:i,onClick:t,onDelete:o}){const{t:d}=Y(["config","common"]),r=s.assignedAgentIds.length,c=s.type==="rectangle"?d("config:areas.rect"):d("config:areas.circle");return e.jsxs("div",{className:`area-item ${i?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"area-color-dot",style:{backgroundColor:s.color}}),e.jsxs("div",{className:"area-info",children:[e.jsx("div",{className:"area-name",children:s.name}),e.jsxs("div",{className:"area-meta",children:[c," ",r>0&&`• ${r} ${r>1?d("common:labels.agents").toLowerCase():d("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:o,title:d("config:areas.deleteArea"),children:"×"})]})}function Ys({building:s,isSelected:i,onClick:t,onEdit:o}){var f;const{t:d}=Y(["config"]),r=((f=s.pm2Status)==null?void 0:f.ports)||[],c=(a,x)=>{a.stopPropagation(),window.open(`http://${window.location.hostname}:${x}`,"_blank")};return e.jsxs("div",{className:`building-item ${i?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:as[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(L,{name:ns(s.type),size:16})}),e.jsxs("div",{className:"building-info",children:[e.jsx("div",{className:"building-name",children:s.name}),e.jsxs("div",{className:"building-meta",children:[s.type,r.length>0&&e.jsx("span",{className:"building-ports",children:r.map(a=>e.jsxs("a",{href:`http://${window.location.hostname}:${a}`,className:"building-port-link",onClick:x=>c(x,a),title:`Open :${a}`,children:[":",a]},a))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:a=>{a.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx(L,{name:"gear",size:14})})]})}function Js({building:s,onClose:i,onOpenModal:t}){var x,y,C,u,p,g,v,j;const{t:o}=Y(["config","common"]),{buildingLogs:d}=Ve(),r=T.getBuildingLogs(s.id),c=hs[s.style||"server-rack"],f=m=>{T.sendBuildingCommand(s.id,m)},a=m=>{window.open(m,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx(L,{name:ns(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:as[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:i,children:"×"})]}),e.jsx("div",{className:"building-editor-section",children:e.jsxs("div",{className:"building-editor-info-grid",children:[e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("common:labels.type")}),e.jsx("span",{className:"building-editor-info-value",children:s.type})]}),e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:c.label})]}),s.cwd&&e.jsxs("div",{className:"building-editor-info-item building-editor-info-wide",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.directory")}),e.jsx("span",{className:"building-editor-info-value building-editor-cwd",title:s.cwd,children:s.cwd.split("/").pop()||s.cwd})]})]})}),s.type==="server"&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>f("start"),disabled:!((x=s.commands)!=null&&x.start)||s.status==="running",title:((y=s.commands)==null?void 0:y.start)||o("config:buildings.noStartCommand"),children:[e.jsx(L,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>f("stop"),disabled:!((C=s.commands)!=null&&C.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx(L,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>f("restart"),disabled:!((p=s.commands)!=null&&p.restart),title:((g=s.commands)==null?void 0:g.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx(L,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>f("healthCheck"),disabled:!((v=s.commands)!=null&&v.healthCheck),title:((j=s.commands)==null?void 0:j.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx(L,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((m,k)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>a(m.url),title:m.url,children:[e.jsx(L,{name:"link",size:12})," ",m.label||m.url]},k))})]}),r.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[o("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>T.clearBuildingLogs(s.id),title:o("common:buttons.clear"),children:o("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:r.slice(-5).map((m,k)=>e.jsx("div",{className:"building-editor-log-entry",children:m},k))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx(L,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const Zs=[{key:"center",labelKey:"posCenter"},{key:"top-left",labelKey:"posTopLeft"},{key:"top-right",labelKey:"posTopRight"},{key:"bottom-left",labelKey:"posBottomLeft"},{key:"bottom-right",labelKey:"posBottomRight"}];function Xs({area:s,onClose:i,onOpenFolder:t}){var Q;const{t:o}=Y(["config","common"]),[d,r]=l.useState(s.name),[c,f]=l.useState(s.prompt||""),[a,x]=l.useState(!1),[y,C]=l.useState(""),[u,p]=l.useState(!1),g=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{f(s.prompt||"")},[s.id,s.prompt]);const v=N=>{const D=N.target.value;r(D),T.updateArea(s.id,{name:D})},j=N=>{T.updateArea(s.id,{color:N})},m=N=>{const D=N.target.value;f(D),T.updateArea(s.id,{prompt:D})},k=()=>{y.trim()&&(T.addDirectoryToArea(s.id,y.trim()),C(""),x(!1))},$=(N,D)=>{D.stopPropagation(),T.removeDirectoryFromArea(s.id,N)},I=()=>{T.bringAreaToFront(s.id)},V=()=>{T.sendAreaToBack(s.id)},w=l.useCallback(()=>{let N=2,D=2;s.type==="rectangle"&&s.width&&s.height?(N=s.width,D=s.height):s.type==="circle"&&s.radius&&(N=s.radius*1.414,D=s.radius*1.414);const B=Math.min(N,D)*.4;return{width:Math.round(B*10)/10,height:Math.round(B*10)/10}},[s.type,s.width,s.height,s.radius]),O=async N=>{var B;const D=(B=N.target.files)==null?void 0:B[0];if(D){p(!0);try{const h=await Ms(s.id,D),E=w();T.updateArea(s.id,{logo:{filename:h.filename,position:"center",width:E.width,height:E.height,keepAspectRatio:!0,opacity:.8}})}catch(h){console.error("Failed to upload logo:",h)}finally{p(!1),g.current&&(g.current.value="")}}},z=async()=>{try{await zs(s.id),T.updateArea(s.id,{logo:void 0})}catch(N){console.error("Failed to remove logo:",N)}},H=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,position:N}})},S=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const B=s.logo.height/s.logo.width;T.updateArea(s.id,{logo:{...s.logo,width:D,height:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,width:D}})},R=N=>{if(!s.logo)return;const D=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const B=s.logo.width/s.logo.height;T.updateArea(s.id,{logo:{...s.logo,height:D,width:Math.round(D*B*10)/10}})}else T.updateArea(s.id,{logo:{...s.logo,height:D}})},W=()=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},J=N=>{s.logo&&T.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(N.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:o("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:i,children:"×"})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:d,onChange:v,placeholder:o("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:ms.map(N=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===N?"selected":""}`,style:{backgroundColor:N},onClick:()=>j(N),"aria-label":`Set area color ${N}`,"aria-pressed":s.color===N,title:N},N))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:I,title:o("config:areas.bringToFront"),children:[e.jsx(L,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:V,title:o("config:areas.sendToBack"),children:[e.jsx(L,{name:"arrow-down",size:12})," ",o("config:areas.back")]})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(Q=s.logo)!=null&&Q.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:Us(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:z,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":e.jsx(L,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Zs.map(({key:N,labelKey:D})=>{var B;return e.jsx("button",{className:`area-logo-pos-btn ${((B=s.logo)==null?void 0:B.position)===N?"active":""}`,onClick:()=>H(N),children:o(`config:areas.${D}`)},N)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:S,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:R,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:o("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:W}),o("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoOpacity")}),e.jsxs("div",{className:"area-logo-opacity-row",children:[e.jsx("input",{type:"range",min:0,max:1,step:.05,value:s.logo.opacity??.8,onChange:J,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var N;return(N=g.current)==null?void 0:N.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:g,type:"file",accept:"image/*",style:{display:"none"},onChange:O})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(N=>e.jsxs("div",{className:"area-folder-item",title:N,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx(L,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:N.split("/").pop()||N}),e.jsx("button",{className:"area-folder-remove",onClick:D=>$(N,D),title:o("config:areas.removeFolder"),children:"×"})]},N)),a?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(gs,{value:y,onChange:C,onSubmit:k,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:k,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>x(!0),children:o("config:areas.addFolder")})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:c,onChange:m,placeholder:o("config:areas.promptPlaceholder","System prompt for agents in this area..."),rows:4,style:{resize:"vertical",fontFamily:"monospace",fontSize:12}}),e.jsx("div",{style:{fontSize:11,color:"var(--text-secondary)",marginTop:4},children:o("config:areas.promptHint","This prompt is injected into agents assigned to this area. Takes effect on next context refresh.")})]}),s.assignedAgentIds.length>0&&e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:o("config:areas.rightClickUnassign")})]})]})}function Qs(){const{t:s}=Y(["config","common"]),i=fs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,f]=l.useState({name:"",key:"",value:"",description:""}),[a,x]=l.useState(null),y=()=>{o(!0),r(null),f({name:"",key:"",value:"",description:""})},C=m=>{r(m.id),o(!1),f({name:m.name,key:m.key,value:m.value,description:m.description||""})},u=()=>{o(!1),r(null),f({name:"",key:"",value:"",description:""})},p=()=>{!c.name.trim()||!c.key.trim()||(d?T.updateSecret(d,{name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}):T.createSecret({name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}),u())},g=m=>{x(m)},v=()=>{a&&(T.deleteSecret(a),d===a&&u())},j=m=>{navigator.clipboard.writeText(`{{${m}}}`)};return e.jsxs("div",{className:"secrets-section",children:[e.jsx("div",{className:"secrets-description",children:s("config:secrets.description",{placeholder:"{{KEY}}"})}),e.jsx("div",{className:"secrets-list",children:i.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):i.map(m=>e.jsxs("div",{className:`secret-item ${d===m.id?"editing":""}`,children:[e.jsxs("div",{className:"secret-item-header",children:[e.jsxs("div",{className:"secret-item-info",children:[e.jsx("span",{className:"secret-item-name",children:m.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>j(m.key),title:s("config:secrets.copyPlaceholder"),children:`{{${m.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>C(m),title:s("common:buttons.edit"),children:e.jsx(L,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>g(m.id),title:s("common:buttons.delete"),children:"×"})]})]}),m.description&&e.jsx("div",{className:"secret-item-description",children:m.description})]},m.id))}),(t||d)&&e.jsxs("div",{className:"secret-form",children:[e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.name")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.namePlaceholder"),value:c.name,onChange:m=>f({...c,name:m.target.value}),autoFocus:!0})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:"Key"}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.keyPlaceholder"),value:c.key,onChange:m=>f({...c,key:m.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${c.key||"KEY"}}}`})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("config:secrets.secretValue")}),e.jsx("input",{type:"password",className:"secret-form-input",placeholder:s("config:secrets.valuePlaceholder"),value:c.value,onChange:m=>f({...c,value:m.target.value})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.description")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.descriptionPlaceholder"),value:c.description,onChange:m=>f({...c,description:m.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:u,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:p,disabled:!c.name.trim()||!c.key.trim(),children:s(d?"config:secrets.update":"common:buttons.add")})]})]}),!t&&!d&&e.jsx("button",{className:"secrets-add-btn",onClick:y,children:s("config:secrets.addSecret")}),e.jsx(he,{isOpen:a!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:v,onClose:()=>x(null)})]})}async function et(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch echo prompt setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function st(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function tt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch codex binary path: ${i.statusText}`);return(await i.json()).path||""}async function at(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function nt(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch tmux mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function it(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function ot(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch interactive mode setting: ${i.statusText}`);return(await i.json()).enabled||!1}async function lt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function ct(){const s=oe(),i=await fetch(`${Z()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Failed to fetch backup status: ${i.statusText}`);return i.json()}async function rt(s){const i=oe(),t=await fetch(`${Z()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({enabled:s})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||`Failed to update backup setting: ${t.statusText}`)}return t.json()}function dt({checked:s,onChange:i,disabled:t}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:t,onChange:o=>i(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function ut(){const{t:s}=Y(["config","common"]),[i,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[f,a]=l.useState(!1),[x,y]=l.useState(!1),[C,u]=l.useState(null),[p,g]=l.useState(null),[v,j]=l.useState(null),[m,k]=l.useState(null),[$,I]=l.useState(!1),[V,w]=l.useState(null);l.useEffect(()=>{je(ke("/api/config/categories")).then(h=>h.json()).then(h=>{const E=Array.isArray(h)?h:[];t(E),d(new Set(E.map(F=>F.id)))}).catch(h=>console.error("Failed to fetch config categories:",h))},[]),l.useEffect(()=>{ct().then(k).catch(h=>{console.error("Failed to fetch backup status:",h),w(h.message||"Failed to fetch backup status")})},[]);const O=async h=>{if(!$){I(!0),w(null);try{const E=await rt(h);k(E)}catch(E){w(E.message||"Failed to update backup setting")}finally{I(!1)}}},z=h=>{d(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},H=h=>{c(E=>{const F=new Set(E);return F.has(h)?F.delete(h):F.add(h),F})},S=()=>d(new Set(i.map(h=>h.id))),R=()=>d(new Set),W=()=>{p&&c(new Set(p.categories.map(h=>h.id)))},J=()=>c(new Set),Q=async()=>{var h;if(o.size!==0){a(!0),j(null);try{const E=Array.from(o).join(","),F=await je(ke(`/api/config/export?categories=${E}`));if(!F.ok)throw new Error("Export failed");const ee=await F.blob(),se=window.URL.createObjectURL(ee),X=document.createElement("a");X.href=se;const A=F.headers.get("Content-Disposition"),q=((h=A==null?void 0:A.match(/filename="(.+)"/))==null?void 0:h[1])||"tide-commander-config.zip";X.download=q,document.body.appendChild(X),X.click(),document.body.removeChild(X),window.URL.revokeObjectURL(se),j({type:"success",text:s("config:data.exportSuccess")})}catch(E){j({type:"error",text:E.message||"Export failed"})}finally{a(!1)}}},N=async h=>{var F;const E=(F=h.target.files)==null?void 0:F[0];if(E){u(E),j(null),g(null),c(new Set);try{const ee=await je(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await E.arrayBuffer()});if(!ee.ok){const A=await ee.json();throw new Error(A.error||"Failed to preview config file")}const se=await ee.json(),X=Array.isArray(se.categories)?se.categories:[];g({...se,categories:X}),c(new Set(X.map(A=>A.id)))}catch(ee){j({type:"error",text:ee.message||"Failed to read config file"}),u(null)}}},D=async()=>{if(!(!C||r.size===0)){y(!0),j(null);try{const h=Array.from(r).join(","),E=await je(ke(`/api/config/import?categories=${h}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await C.arrayBuffer()}),F=await E.json();if(!E.ok)throw new Error(F.error||"Import failed");j({type:"success",text:F.message||s("config:data.importSuccess")}),u(null),g(null),c(new Set)}catch(h){j({type:"error",text:h.message||"Import failed"})}finally{y(!1)}}},B=()=>{u(null),g(null),c(new Set),j(null)};return e.jsxs("div",{className:"data-section",children:[v&&e.jsx("div",{className:`data-message data-message-${v.type}`,children:v.text}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:"Hourly Backups"}),e.jsx(dt,{checked:!!(m!=null&&m.enabled),disabled:$||!m,onChange:O})]}),e.jsxs("div",{className:"data-backup-info",children:[m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:m.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!m.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:m.scriptPath})]}),m.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(m.lastRunAt).toLocaleString(),m.lastRunOk===!0&&" — ok",m.lastRunOk===!1&&m.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",m.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),V&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:V})]})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:s("config:data.exportData")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:S,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:R,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:i.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(h.id),onChange:()=>z(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name})]},h.id))}),e.jsx("button",{className:"data-action-btn export",onClick:Q,disabled:f||o.size===0,children:f?s("config:data.exporting"):s("config:data.exportCount",{count:o.size})})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsx("div",{className:"data-subsection-header",children:e.jsx("span",{className:"data-subsection-title",children:s("config:data.importData")})}),C?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:C.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(p.exportedAt).toLocaleDateString()]})]}),e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-subtitle",children:s("config:data.selectToImport")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:W,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:J,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:p.categories.map(h=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(h.id),onChange:()=>H(h.id)}),e.jsx("span",{className:"data-category-name",children:h.name}),h.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",h.fileCount," ",s("config:data.files"),")"]})]},h.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:B,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:D,disabled:x||r.size===0,children:x?s("config:data.importing"):s("config:data.importCount",{count:r.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:N,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function pt(){const s=await je(`${Z()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function ht(s,i){const t=new AbortController;return(async()=>{try{const o=await fetch(xs(`${Z()}/api/system/self-update`),{method:"POST",signal:t.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const f=await o.text().catch(()=>"");let a=null;try{a=JSON.parse(f)}catch{}const x=a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"?a.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:x}),i(new Error(x));return}const d=o.body.getReader(),r=new TextDecoder("utf-8");let c="";for(;;){const{value:f,done:a}=await d.read();if(a)break;c+=r.decode(f,{stream:!0});let x=c.indexOf(`
2
2
 
3
3
  `);for(;x!==-1;){const y=c.slice(0,x);c=c.slice(x+2);const C=y.split(`
4
4
  `);let u="message",p="";for(const g of C)g.startsWith(":")||(g.startsWith("event:")?u=g.slice(6).trim():g.startsWith("data:")&&(p+=(p?`
@@ -1,4 +1,4 @@
1
- import{bv as Oe,r as t,s as I,i as ye,bw as Ee,h as _e,j as e,I as z,u as fe,bx as ze,by as Pe,bz as Be,bA as Ue,n as We,bB as Ke,bC as De,bD as Ve,af as Ge,ag as qe,ah as Ye,b0 as Je,W as Me,S as oe,aW as Xe,aT as Qe,a6 as Ze,X as Ie,at as et,a1 as tt,bE as st,o as X,bF as nt}from"./main-B8YPZvpg.js";import{FileExplorerPanel as at}from"./index-TX8bidMy.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ne={status:"all",activity:"all",sort:"activity"},lt={"1h":3600*1e3,"6h":360*60*1e3,"24h":1440*60*1e3},Ae=20,me=3,ot={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a"},ct=12e4;function rt(s){return s.trim().replace(/\r\n/g,`
1
+ import{bv as Oe,r as t,s as I,i as ye,bw as Ee,h as _e,j as e,I as z,u as fe,bx as ze,by as Pe,bz as Be,bA as Ue,n as We,bB as Ke,bC as De,bD as Ve,af as Ge,ag as qe,ah as Ye,b0 as Je,W as Me,S as oe,aW as Xe,aT as Qe,a6 as Ze,X as Ie,at as et,a1 as tt,bE as st,o as X,bF as nt}from"./main-C7U_3QQV.js";import{FileExplorerPanel as at}from"./index-BdEYVGMt.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ne={status:"all",activity:"all",sort:"activity"},lt={"1h":3600*1e3,"6h":360*60*1e3,"24h":1440*60*1e3},Ae=20,me=3,ot={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a"},ct=12e4;function rt(s){return s.trim().replace(/\r\n/g,`
2
2
  `)}function $e(s,a){return`${s}:${rt(a)}`}function it(s,a,l,f){if(s.uuid&&a.has(s.uuid))return!1;if(s.uuid)return!0;const p=s.isUserPrompt?"user":"assistant",d=$e(p,s.text),M=s.timestamp||0,A=l.get(d);return A!==void 0&&Math.abs(M-A)<=ct?!1:M>f}function dt({isOpen:s,agents:a}){const l=Oe(),[f,p]=t.useState(new Map),d=t.useRef(new Set);t.useRef(a);const M=t.useMemo(()=>Array.from(a.keys()).sort().join(","),[a]),A=t.useMemo(()=>Array.from(a.values()).map(j=>`${j.id}:${j.sessionId||""}`).sort().join(","),[a]);t.useEffect(()=>{s||(d.current.clear(),p(new Map))},[s]),t.useEffect(()=>{if(!s)return;const j=new Set(Array.from(a.keys()));for(const i of d.current)j.has(i)||d.current.delete(i);let h=null;l>0&&(h=I.preserveOutputs(),d.current.clear());const v=async(i,C,F=0)=>{if(d.current.add(i.id),F>0&&await new Promise(x=>setTimeout(x,F)),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!0,hasMore:!1,totalCount:0}),k}),!i.sessionId){C&&C.length>0&&I.mergeOutputsWithHistory(i.id,[],C),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),k});return}try{const k=await(await _e(ye(`/api/agents/${i.id}/history?limit=${Ee}&offset=0`))).json(),T=k.messages||[],K=T.length>0?Math.max(...T.map(w=>w.timestamp?new Date(w.timestamp).getTime():0)):0,Y=new Set(T.map(w=>w.uuid).filter(w=>!!w)),V=new Map;for(const w of T){if(w.type!=="user"&&w.type!=="assistant")continue;const c=$e(w.type,w.content),L=w.timestamp?new Date(w.timestamp).getTime():0,W=V.get(c)??0;L>W&&V.set(c,L)}const G=I.getOutputs(i.id),U=(C&&C.length>0?[...C,...G]:G).filter(w=>it(w,Y,V,K));I.clearOutputs(i.id);for(const w of U)I.addOutput(i.id,w);p(w=>{const c=new Map(w);return c.set(i.id,{agentId:i.id,messages:T,loading:!1,hasMore:k.hasMore||!1,totalCount:k.totalCount||0}),c})}catch(x){if(console.error(`Failed to load history for ${i.name}:`,x),C&&C.length>0){I.clearOutputs(i.id);for(const k of C)I.addOutput(i.id,k)}p(k=>{const T=new Map(k);return T.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),T})}},u=l>0?500:0,D=Array.from(a.values());for(const i of D)if(!d.current.has(i.id)){const C=h==null?void 0:h.get(i.id);v(i,C,u)}},[s,M,A,l]);const R=t.useRef(a),N=t.useRef(f);R.current=a,N.current=f;const b=t.useCallback(async j=>{const h=R.current.get(j),v=N.current.get(j);if(!(h!=null&&h.sessionId)||!v||!v.hasMore)return;const u=v.messages.length;try{const i=await(await fetch(ye(`/api/agents/${j}/history?limit=${Ee}&offset=${u}`))).json();i.messages&&i.messages.length>0&&p(C=>{const F=new Map(C),x=C.get(j);return x&&F.set(j,{...x,messages:[...i.messages,...x.messages],hasMore:i.hasMore||!1}),F})}catch(D){console.error(`Failed to load more history for agent ${j}:`,D)}},[]),E=t.useCallback(j=>{d.current.delete(j),p(h=>{const v=new Map(h),u=h.get(j);return u&&v.set(j,{...u,messages:[],hasMore:!1,totalCount:0,loading:!1}),v})},[]);return{histories:f,loadMoreHistory:b,clearAgentHistory:E}}function ut({command:s,onCommandChange:a,useTextarea:l,forceTextarea:f,onForceTextarea:p,onSend:d,canSend:M,attachedFiles:A,onAddFile:R,onRemoveFile:N,uploadFile:b,onAddPastedText:E,placeholder:j="Message...",className:h="",compact:v=!1,inputRef:u}){const D=t.useRef(null),i=t.useRef(null),C=t.useRef(l);t.useEffect(()=>{if(l&&!C.current&&i.current){const c=i.current;c.focus(),c.selectionStart=c.selectionEnd=c.value.length}C.current=l},[l]),t.useEffect(()=>{const c=i.current;if(!c||!l)return;c.style.height="auto";const L=v?120:180,W=Math.min(c.scrollHeight,L);c.style.height=`${W}px`},[s,l,v]);const F=t.useCallback(async c=>{const L=c.clipboardData.items;for(const _ of L)if(_.type.startsWith("image/")){c.preventDefault();const $=_.getAsFile();if($){const H=await b($);H&&R(H)}return}const W=c.clipboardData.files;if(W.length>0){c.preventDefault();for(const _ of W){const $=await b(_);$&&R($)}return}const B=c.clipboardData.getData("text"),te=(B.match(/\n/g)||[]).length+1;if(te>5){c.preventDefault();const $=`[Pasted text #${E(B)} +${te} lines]`,H=c.target,se=H.selectionStart||0,ae=H.selectionEnd||0,ne=s.slice(0,se)+$+s.slice(ae);a(ne),l||p(!0)}},[s,a,l,p,b,R,E]),x=t.useCallback(async c=>{const L=c.target.files;if(L){for(const W of L){const B=await b(W);B&&R(B)}D.current&&(D.current.value="")}},[b,R]),k=t.useCallback(c=>{if(c.key==="Enter"&&c.shiftKey){l||(c.preventDefault(),p(!0));return}c.key==="Enter"&&(c.preventDefault(),d())},[l,p,d]),T=t.useCallback(c=>{},[]),K=t.useCallback(c=>{c.button===1&&(c.preventDefault(),c.stopPropagation())},[]),Y=t.useCallback(c=>{i.current=c,u==null||u(c)},[u]),V=v?"agent-panel-input":"guake-input",G=v?"agent-panel-input-container":"guake-input-container",Q=v?"agent-panel-attach-btn":"guake-attach-btn",U=v?"agent-panel-send-btn":"",w=l?v?"agent-panel-input-expanded":"guake-input-expanded":"";return e.jsxs(e.Fragment,{children:[A.length>0&&e.jsx("div",{className:v?"agent-panel-attachments":"guake-attachments",children:A.map(c=>e.jsxs("div",{className:`${v?"agent-panel-attachment":"guake-attachment"} ${c.isImage?"is-image":""}`,children:[e.jsx("span",{className:v?"agent-panel-attachment-icon":"guake-attachment-icon",children:e.jsx(z,{name:c.isImage?"file":"paperclip",size:12})}),e.jsx("span",{className:v?"agent-panel-attachment-name":"guake-attachment-name",title:c.path,children:c.name}),!v&&e.jsxs("span",{className:"guake-attachment-size",children:["(",Math.round(c.size/1024),"KB)"]}),e.jsx("button",{className:v?"agent-panel-attachment-remove":"guake-attachment-remove",onClick:()=>N(c.id),title:"Remove",children:"×"})]},c.id))}),e.jsxs("div",{className:`${V} ${w} ${h}`,children:[e.jsx("input",{ref:D,type:"file",multiple:!0,onChange:x,style:{display:"none"},accept:"*"}),e.jsxs("div",{className:G,onAuxClick:K,children:[e.jsx("button",{className:Q,onClick:()=>{var c;return(c=D.current)==null?void 0:c.click()},title:"Attach file (or paste image)",children:e.jsx(z,{name:"paperclip",size:14})}),l?e.jsx("textarea",{ref:Y,placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:T}):e.jsx("input",{ref:u,type:"text",placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:T}),e.jsx("button",{className:U,onClick:d,disabled:!M,title:"Send",children:e.jsx(z,{name:"send",size:14})})]})]})]})}function mt(s){const a=Math.floor(s/1e3),l=Math.floor(a/60),f=a%60;return`${l}:${f.toString().padStart(2,"0")}`}const ft=t.memo(function({agentId:a,isWorking:l,timestamp:f}){const{t:p}=fe(["terminal"]),[d,M]=t.useState(0);return t.useEffect(()=>{if(!l||!f){M(0);return}M(Date.now()-f);const A=setInterval(()=>{M(Date.now()-f)},1e3);return()=>clearInterval(A)},[l,f]),l?e.jsxs("div",{className:"guake-stop-bar",children:[e.jsx("span",{className:"guake-elapsed-timer",children:mt(d)}),e.jsxs("button",{className:"guake-stop-btn",onClick:()=>I.stopAgent(a),title:p("terminal:input.stopOperation"),children:[e.jsx("span",{className:"stop-icon",children:e.jsx(z,{name:"stop",size:12,weight:"fill"})}),e.jsx("span",{className:"stop-label",children:p("terminal:input.stop")})]})]}):null});function pt({agent:s,history:a,outputs:l,isExpanded:f,isFocused:p,advancedView:d,onExpand:M,onFocus:A,inputRef:R,onLoadMore:N,onClearHistory:b}){const{t:E}=fe(["terminal","common"]),j=ze(s.id),h=t.useRef(null),[v,u]=t.useState(!1),D=t.useRef(0),i=t.useRef(!1),[C,F]=t.useState(!0),[x,k]=t.useState(!1),[T,K]=t.useState(null),[Y,V]=t.useState(null),[G,Q]=t.useState(null);Pe(`commander-image-modal-${s.id}`,T!==null,()=>K(null));const{command:U,setCommand:w,forceTextarea:c,setForceTextarea:L,useTextarea:W,setPastedTexts:B,incrementPastedCount:te,resetPastedCount:_,attachedFiles:$,setAttachedFiles:H,removeAttachedFile:se,uploadFile:ae,expandPastedTexts:ne}=Be({selectedAgentId:s.id}),le=U.trim().length>0||$.length>0,n=Ue({outputs:l,viewMode:d?"advanced":"simple"}),o=t.useMemo(()=>{const S=We(s);return{usedPercent:S.usedPercent,freePercent:S.freePercent,hasData:!!s.contextStats,totalTokens:S.totalTokens,contextWindow:S.contextWindow}},[s.contextStats,s.contextUsed,s.contextLimit]),g=t.useCallback(()=>{!v&&(a!=null&&a.hasMore)&&N&&(u(!0),D.current=h.current?h.current.scrollHeight-h.current.scrollTop:0,N())},[v,a==null?void 0:a.hasMore,N]);t.useEffect(()=>{v&&a&&!a.loading&&u(!1)},[a,v]);const m=t.useCallback(()=>{i.current=!0,F(!1)},[]),P=t.useRef(f),Z=t.useRef(p);t.useEffect(()=>{(f&&!P.current||p&&!Z.current)&&(i.current=!1,F(!0),k(!0)),P.current=f,Z.current=p},[f,p]);const ee=t.useRef(a==null?void 0:a.loading);t.useEffect(()=>{ee.current&&!(a!=null&&a.loading)&&(i.current=!1,F(!0),k(!0)),ee.current=a==null?void 0:a.loading},[a==null?void 0:a.loading]),t.useEffect(()=>{if(!x)return;const S=h.current;if(!S)return;const y=performance.now();let O=0,ue=-1,ke;const Re=()=>{const{scrollTop:Fe,scrollHeight:Se,clientHeight:Le}=S,He=Se-Fe-Le<=2;if(Math.abs(Se-ue)<=1&&He?O+=1:O=0,ue=Se,O>=3){k(!1);return}if(performance.now()-y>5e3){k(!1);return}ke=requestAnimationFrame(Re)};return ke=requestAnimationFrame(Re),()=>cancelAnimationFrame(ke)},[x]),t.useEffect(()=>{i.current||F(!0)},[n.length]);const q=t.useCallback(()=>!1,[]),ie=t.useCallback(S=>{const y=te();return B(O=>new Map(O).set(y,S)),y},[te,B]),he=t.useCallback(S=>{H(y=>[...y,S])},[H]),xe=t.useCallback(()=>{if(!le)return;if(U.trim()==="/clear"&&$.length===0){I.clearContext(s.id),b(),w(""),L(!1),B(new Map),H([]),_();return}let S=ne(U.trim());if($.length>0){const y=$.map(O=>O.isImage?`[Image: ${O.path}]`:`[File: ${O.path}]`).join(`
3
3
  `);S=S?`${S}
4
4
 
@@ -1,2 +1,2 @@
1
- import{r as a,B as pn,E as $t,G as Gt,H as qt,j as e,J as Yt,K as mn,u as Pt,L as fn,M as hn,N as gn,O as xn,V as bn,P as _n,U as wn,W as zt,S,X as Ot,Y as Tt,Z as Bt,_ as pt,$ as de,a0 as vn,s as v,a1 as Kt,a2 as Zt,a3 as Cn,w as Ft,x as Wt,I as f,a4 as jn,n as Nn,a5 as kn,a6 as Jt,a7 as Qt,a8 as yn,a9 as An,aa as Sn,ab as En,ac as Mn,ad as In,ae as Tn,af as Pn,ag as Ln,ah as Dn,ai as Rn,aj as $n,ak as Ht,C as zn,al as On,am as Bn,an as Fn,ao as Wn,ap as Hn,aq as Un,ar as Vn,as as Xn,at as Gn,au as qn,av as Yn,aw as Kn,ax as Zn,ay as Jn,az as Qn,aA as ea,aB as ta}from"./main-B8YPZvpg.js";import{g as na}from"./area-logos-CAaQMgNQ.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function aa(d){const l=a.useRef(d);l.current=d,a.useEffect(()=>{if(!pn())return;let m=null,h=!1;return $t.addListener("backButton",()=>{l.current()==="exit"&&$t.exitApp()}).then(N=>{h?N.remove():m=N}),()=>{h=!0,m&&(m.remove(),m=null)}},[])}async function sa(d){const l=Gt(),m=await fetch(`${qt()}/api/agents/${d}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${l}`}});if(!m.ok){const h=await m.json().catch(()=>({}));throw new Error((h==null?void 0:h.error)||`Failed to start terminal (${m.status})`)}return m.json()}async function ia(d){const l=Gt();await fetch(`${qt()}/api/agents/${d}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}})}const qe=new Map;function la({agentId:d}){const[l,m]=a.useState(null),[h,N]=a.useState(null);return a.useEffect(()=>{let T=!1;const M=qe.get(d);return M&&(clearTimeout(M),qe.delete(d)),m(null),N(null),sa(d).then(L=>{T||m(L.url)}).catch(L=>{T||N(L instanceof Error?L.message:"Failed to start terminal")}),()=>{T=!0;const L=qe.get(d);L&&clearTimeout(L),qe.set(d,setTimeout(()=>{qe.delete(d),ia(d)},2500))}},[d]),h?e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:h})}):l?e.jsx("div",{className:"flat-classic-terminal",children:e.jsx(Yt,{terminalUrl:l,visible:!0})}):e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:"Attaching to interactive session…"})})}const Mt=new Map,ra=6e4;function oa({agentId:d,contextSummary:l}){const{t:m}=Pt(["terminal","common"]),[h,N]=a.useState(()=>{var P;return((P=Mt.get(d))==null?void 0:P.snapshot)??null}),[T,M]=a.useState(!1),[L,Z]=a.useState(null),b=a.useRef(0);a.useEffect(()=>{const P=Mt.get(d);if(P&&Date.now()-P.fetchedAt<ra){N(P.snapshot);return}const X=++b.current;M(!0),Z(null),fn(d).then(K=>{X===b.current&&(Mt.set(d,{snapshot:K,fetchedAt:Date.now()}),N(K),M(!1))}).catch(K=>{X===b.current&&(Z(K.message||"Failed to load plan limits"),M(!1))})},[d]);const V=[];if(h!=null&&h.rateLimits){const P=[{key:"fiveHour",label:m("terminal:usage.currentSession"),window:h.rateLimits.fiveHour},{key:"sevenDay",label:m("terminal:usage.currentWeekAll"),window:h.rateLimits.sevenDay},{key:"sevenDayOpus",label:m("terminal:usage.currentWeekOpus"),window:h.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:m("terminal:usage.currentWeekSonnet"),window:h.rateLimits.sevenDaySonnet}];for(const X of P)X.window&&V.push({...X,window:X.window})}return e.jsxs("div",{className:"plan-limits-tooltip",children:[l&&e.jsx("div",{className:"plan-limits-tooltip__context",children:l}),e.jsx("div",{className:"plan-limits-tooltip__title",children:m("terminal:usage.limits")}),T&&!h&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[m("common:status.loading"),"…"]}),!T&&L&&!h&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:m("terminal:usage.limitsError",{message:L})}),V.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:V.map(({key:P,label:X,window:K})=>{const ue=Math.max(0,Math.min(100,K.utilization)),te=gn(ue);return e.jsxs("div",{className:"plan-limits-tooltip__gauge",children:[e.jsxs("div",{className:"plan-limits-tooltip__gauge-head",children:[e.jsx("span",{className:"plan-limits-tooltip__gauge-label",children:X}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:te},children:m("terminal:usage.percentUsed",{percent:Math.round(ue)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${ue}%`,background:te}})}),e.jsx("div",{className:"plan-limits-tooltip__reset",children:m("terminal:usage.resets",{time:hn(K.resetsAt)})})]},P)})}):h&&!T&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:h.rateLimitsError?m("terminal:usage.limitsError",{message:h.rateLimitsError}):h.cliHint})]})}function ca({agentId:d,disabled:l,contextSummary:m,children:h}){return e.jsx(mn,{position:"top",maxWidth:320,disabled:l,className:"plan-limits-tooltip-wrapper",triggerStyle:{display:"inline-flex",alignItems:"center"},content:e.jsx(oa,{agentId:d,contextSummary:m}),children:h})}const da=a.memo(function({className:l=""}){const{t:m}=Pt(["common"]),[h,N]=xn(),T=a.useRef(null),[M,L]=a.useState(null);a.useLayoutEffect(()=>{const b=T.current;if(!b)return;const V=b.querySelector(".view-mode-toggle__btn--active");V&&L({left:V.offsetLeft,width:V.offsetWidth})},[h]);const Z=a.useCallback(b=>{if(b!==h){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:b}})),b==="3d"){requestAnimationFrame(()=>N(b));return}N(b)}},[h,N]);return e.jsxs("div",{className:`view-mode-toggle ${l}`,ref:T,children:[M&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:M.left,width:M.width}}),bn.map(b=>e.jsxs("button",{className:`view-mode-toggle__btn ${h===b?"view-mode-toggle__btn--active":""}`,onClick:()=>Z(b),title:m(`common:viewMode.descriptions.${b}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[b==="2d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),b==="3d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}),b==="flat"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]}),b==="dashboard"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),e.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),e.jsx("span",{className:"view-mode-toggle__label",children:m(`common:viewMode.labels.${b}`)})]},b))]})}),mt=3,ft=280,Ut=320,It=240,Vt=64,ua=["simple","chat","advanced"],pa={simple:"Simple",chat:"Chat",advanced:"Advanced"},ma={simple:"○",chat:"◐",advanced:"◉"},fa={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Xt="flat-clear-context";function ha(d){const l=d.split("/").filter(Boolean);return l.length===0?d:l.slice(-2).join("/")}function ga(d){if(d.provider==="codex"){const T=d.codexModel||"gpt-5.3-codex",M=Qn[T];return{model:(M==null?void 0:M.label)||T}}if(d.provider==="opencode")return{model:d.opencodeModel||"opencode"};const l=d.model||"sonnet",m=ta[l],h=d.effort,N=h?ea[h]:void 0;return{model:(m==null?void 0:m.label)||l,effort:N==null?void 0:N.label}}function xa(d,l){if(l.type==="rectangle"&&l.width&&l.height){const m=l.width/2,h=l.height/2;return d.x>=l.center.x-m&&d.x<=l.center.x+m&&d.z>=l.center.z-h&&d.z<=l.center.z+h}if(l.type==="circle"&&l.radius){const m=d.x-l.center.x,h=d.z-l.center.z;return m*m+h*h<=l.radius*l.radius}return!1}const ba=On.memo(function({agentId:l,terminalViewMode:m,onTerminalViewModeChange:h,inspectorOpen:N,onToggleInspector:T,onImageClick:M,onFileClick:L,onBashClick:Z,onViewMarkdown:b,onRequestClearSubordinates:V,onOpenBuilding:P,keyboard:X,canNavigateBack:K,canNavigateForward:ue,onNavigateBack:te,onNavigateForward:pe,agentInfoOpen:je,onToggleAgentInfo:Ye,onHeaderContextMenu:se,onBuildingContextMenu:Ne}){var nt,at,Be,Xe;const p=Bn(l),J=Zt(),me=Fn(),ke=a.useRef(null),Re=a.useRef(null),fe=!!me.interactiveMode&&((p==null?void 0:p.provider)??"claude")==="claude"&&!!(p!=null&&p.sessionId),[ie,$e]=a.useState(!1);a.useEffect(()=>{$e(!1)},[l]),a.useEffect(()=>{!fe&&ie&&$e(!1)},[fe,ie]),a.useEffect(()=>{const i=Re.current;if(!i)return;const r=c=>{c.button===3?(c.preventDefault(),c.stopPropagation(),te()):c.button===4&&(c.preventDefault(),c.stopPropagation(),pe())},u=c=>{(c.button===3||c.button===4)&&c.preventDefault()};return i.addEventListener("mouseup",r),i.addEventListener("mousedown",u),()=>{i.removeEventListener("mouseup",r),i.removeEventListener("mousedown",u)}},[te,pe]),a.useEffect(()=>{const i=Re.current;if(!i)return;let r=0,u=0,c=0;const Ce=250,Pe=600,Fe=80,st=1.5,it=Y=>{let z=Y instanceof HTMLElement?Y:null;for(;z&&z!==i;){const ae=window.getComputedStyle(z).overflowX;if((ae==="auto"||ae==="scroll")&&z.scrollWidth>z.clientWidth)return!0;z=z.parentElement}return!1},lt=Y=>{const z=Date.now();if(z<c){Y.preventDefault();return}if(Math.abs(Y.deltaX)<=Math.abs(Y.deltaY)*st){r=0;return}if(it(Y.target)){r=0;return}z-u>Ce&&(r=0),u=z,r+=Y.deltaX,r<=-Fe?(r=0,c=z+Pe,Y.preventDefault(),te()):r>=Fe&&(r=0,c=z+Pe,Y.preventDefault(),pe())};return i.addEventListener("wheel",lt,{passive:!1}),()=>i.removeEventListener("wheel",lt)},[te,pe]);const We=Kt(),ze=a.useMemo(()=>{if(!p)return null;const i=new Set,r=[];for(const u of We.values())u.archived||u.directories.length===0||u.assignedAgentIds.includes(l)&&(i.add(u.id),r.push(u));for(const u of We.values())u.archived||u.directories.length===0||i.has(u.id)||xa({x:p.position.x,z:p.position.z},u)&&(i.add(u.id),r.push(u));return r.length===0?null:r.flatMap(u=>u.directories.filter(c=>c&&c.trim().length>0).map(c=>({areaId:u.id,areaName:u.name,dir:c})))},[p,l,We]),{branches:Ke,fetchRemote:ye,fetchingDirs:he}=Wn(ze),Q=a.useMemo(()=>{var u;const i=v.getAreaForAgent(l);if(!i)return[];const r=[];for(const c of J.values())c.type==="terminal"&&v.isPositionInArea(c.position,i)&&r.push({id:c.id,name:c.name,hasUrl:!!((u=c.terminalStatus)!=null&&u.url)});return r},[l,J]),le=a.useMemo(()=>{var u;const i=v.getAreaForAgent(l);if(!i)return[];const r=[];for(const c of J.values())c.type==="server"&&((u=c.pm2)!=null&&u.enabled)&&v.isPositionInArea(c.position,i)&&r.push({id:c.id,name:c.name});return r},[l,J]),Ze=a.useMemo(()=>{const i=v.getAreaForAgent(l);if(!i)return[];const r=[];for(const u of J.values())u.type==="database"&&u.database&&v.isPositionInArea(u.position,i)&&r.push({id:u.id,name:u.name});return r},[l,J]),[,ht]=a.useReducer(i=>i+1,0),re=((nt=ke.current)==null?void 0:nt.search.searchMode)??!1,Ae=a.useCallback(()=>{var i;(i=ke.current)==null||i.search.toggleSearch(),ht()},[]),ge=Hn(),xe=ge.isPending(Xt),[R,oe]=a.useState(null),G=R?J.get(R):null,{height:be,onResizeStart:gt}=Un(),{sidePanelWidth:xt,handleSidePanelResizeStart:Je}=Vn(),[ne,Qe]=a.useState(()=>Tt(S.GIT_PANEL_OPEN,!1)),[Se,_e]=a.useState(()=>Tt(S.BUILDINGS_PANEL_OPEN,!1)),[Ee,He]=a.useState(!1),bt=a.useCallback(()=>{He(i=>{const r=!i;return r&&Xn.setEnabled(!0),r})},[]),Ue=a.useCallback(()=>He(!1),[]),_t=a.useCallback(()=>{Qe(i=>{const r=!i;return de(S.GIT_PANEL_OPEN,r),r})},[]),wt=a.useCallback(()=>{_e(i=>{const r=!i;return de(S.BUILDINGS_PANEL_OPEN,r),r})},[]),vt=a.useCallback(()=>{Qe(!1),de(S.GIT_PANEL_OPEN,!1)},[]),Ct=a.useCallback(()=>{_e(!1),de(S.BUILDINGS_PANEL_OPEN,!1)},[]),jt=Gn();a.useEffect(()=>{if(!R)return;Q.some(r=>r.id===R)||oe(null)},[R,Q]);const[Me,ee]=a.useState(!1),_=a.useRef(null);if(a.useEffect(()=>{if(!Me)return;const i=r=>{_.current&&!_.current.contains(r.target)&&ee(!1)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[Me]),!p)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const $=p.contextStats,q=!!$,Ie=$?$.totalTokens:p.contextUsed||0,Ve=$?$.contextWindow:p.contextLimit||2e5,Nt=$?$.usedPercent:Math.round(Ie/Ve*100),we=Math.max(0,Math.min(100,Nt)),et=Math.round(we*10)/10,kt=Math.round((100-we)*10)/10,Oe=we>=80?"#ff4a4a":we>=60?"#ff9e4a":we>=40?"#ffd700":"#4aff9e",ce=(Ie/1e3).toFixed(1),Te=(Ve/1e3).toFixed(1),B=p.cwd,tt=B?ha(B):null,F=((at=p.subordinateIds)==null?void 0:at.length)||0,ve=F>0;return e.jsxs("div",{ref:Re,className:`flat-terminal-wrapper ${ne||Se||Ee?"flat-terminal-wrapper--with-side-panel":""}`,style:{"--guake-side-panel-width":`min(${xt}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${je?"flat-terminal-wrapper__header-main--active":""}`,onClick:Ye,onContextMenu:i=>{i.preventDefault(),i.stopPropagation(),se({x:i.clientX,y:i.clientY})},title:je?"Hide agent info":"Show agent info","aria-pressed":je,children:[e.jsx(Jt,{agent:p,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:p.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:Qt(p.status)},children:p.status})]}),p.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:p.taskLabel,children:["📋 ",p.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:p.provider==="codex"?"/assets/codex.png":p.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:p.provider,className:"flat-terminal-wrapper__header-provider-icon",title:p.provider==="codex"?"Codex Agent":p.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:i,effort:r}=ga(p);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:r?`Model: ${i} · Effort: ${r}`:`Model: ${i}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:i}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-sep","aria-hidden":"true",children:"·"}),e.jsx("span",{className:"flat-terminal-wrapper__header-model-effort",children:r})]})]})})()]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__header-meta",children:[e.jsxs("div",{className:"flat-terminal-wrapper__view-mode",role:"group","aria-label":"Message view mode",children:[ua.map(i=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${!ie&&m===i?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{$e(!1),h(i)},title:fa[i],"aria-pressed":!ie&&m===i,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:ma[i]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:pa[i]})]},i)),fe&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${ie?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>$e(i=>!i),title:"Classic TUI — attach to the live interactive claude session in a terminal","aria-pressed":ie,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:e.jsx(f,{name:"terminal",size:13})}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:"Classic TUI"})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__actions",role:"group","aria-label":"Terminal actions",children:[e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:te,disabled:!K,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(f,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:pe,disabled:!ue,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(f,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${re?"flat-terminal-wrapper__action-btn--active":""}`,onClick:Ae,title:re?"Close search":"Search messages","aria-pressed":re,children:e.jsx(f,{name:re?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${xe?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>ge.handleClick(Xt,()=>{var i;v.clearContext(l),(i=ke.current)==null||i.historyLoader.clearHistory()}),title:xe?"Click again to confirm clear context":"Clear context",children:e.jsx(f,{name:xe?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ne?"flat-terminal-wrapper__action-btn--active":""}`,onClick:_t,title:ne?"Hide git panel":"Show git changes","aria-pressed":ne,children:e.jsx(f,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Se?"flat-terminal-wrapper__action-btn--active":""}`,onClick:wt,title:Se?"Hide buildings panel":"Show area buildings","aria-pressed":Se,children:e.jsx(f,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:_,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Me?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>ee(i=>!i),title:"More actions","aria-expanded":Me,children:"⋮"}),Me&&e.jsxs("div",{className:"flat-terminal-wrapper__more-menu",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-terminal-wrapper__more-item ${Ee?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{bt(),ee(!1)},title:Ee?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(f,{name:"bug",size:14}),e.jsx("span",{children:Ee?"Hide Debug Panel":"Show Debug Panel"})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item",onClick:()=>{v.collapseContext(l),ee(!1)},disabled:p.status!=="idle",title:p.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(f,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),ve&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{V(l,F),ee(!1)},children:[e.jsx(f,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",F," subordinate",F===1?"":"s"]})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{v.killAgent(l),ee(!1)},children:[e.jsx(f,{name:"cross",size:14}),e.jsx("span",{children:"Remove agent"})]})]})]})]}),e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__inspector-toggle ${N?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:T,title:N?"Hide inspector panel":"Show inspector panel","aria-label":N?"Hide inspector panel":"Show inspector panel","aria-pressed":N,children:[e.jsx("span",{className:"flat-terminal-wrapper__inspector-icon","aria-hidden":"true",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"}),e.jsx("line",{x1:"10",y1:"2.5",x2:"10",y2:"13.5"})]})}),e.jsx("span",{className:"flat-terminal-wrapper__inspector-label",children:"Inspector"})]}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__close",onClick:()=>v.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(f,{name:"cross",size:14})})]})]}),ie&&fe?e.jsx(la,{agentId:l}):e.jsx(qn,{ref:ke,agentId:l,agent:p,viewMode:m,isOpen:!0,onImageClick:M,onFileClick:L,onBashClick:Z,onViewMarkdown:b,keyboard:X,hasModalOpen:!1}),G&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:gt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${G.name}`,style:{height:be},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(f,{name:"terminal",size:12}),e.jsx("span",{children:G.name}),!((Be=G.terminalStatus)!=null&&Be.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>oe(null),title:"Close embedded terminal","aria-label":"Close embedded terminal",children:e.jsx(f,{name:"cross",size:12})})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:(Xe=G.terminalStatus)!=null&&Xe.url?e.jsx(Yt,{terminalUrl:G.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."})})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[p.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(f,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),B&&tt&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${B}`,"aria-label":`Open ${B} in file explorer`,role:"button",tabIndex:0,onClick:()=>v.openFileExplorer(B),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),v.openFileExplorer(B))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(f,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:tt})]}),ze&&ze.map(({areaId:i,areaName:r,dir:u})=>{const c=Ke.get(u),Ce=he.has(u),Pe=u.split("/").filter(Boolean).pop()||u;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${r}: ${u}${c?` (${c.branch}${c.ahead?` ↑${c.ahead}`:""}${c.behind?` ↓${c.behind}`:""})`:""}`,onClick:()=>v.openFileExplorerForAreaFolder(i,u),children:[e.jsx(f,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:Pe}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(f,{name:"git-branch",size:10})," ",c.branch]}),c.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${c.ahead} ahead`,children:[e.jsx(f,{name:"arrow-up",size:9}),c.ahead]}),c.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${c.behind} behind`,children:[e.jsx(f,{name:"arrow-down",size:9}),c.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${Ce?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Fe=>{Fe.stopPropagation(),ye(u)},children:e.jsx(f,{name:Ce?"hourglass":"download",size:12})})]})]},`${i}:${u}`)}),e.jsx(ca,{agentId:l,disabled:((p==null?void 0:p.provider)??"claude")!=="claude",contextSummary:q?`Context: ${ce}k / ${Te}k tokens (${et}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>v.setContextModalAgentId(l),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),v.setContextModalAgentId(l))},title:((p==null?void 0:p.provider)??"claude")!=="claude"?q?`Context usage: ${ce}k / ${Te}k tokens (${et}% used). Click to view stats.`:"Click to fetch context stats":void 0,children:[e.jsx("span",{className:"flat-terminal-wrapper__context-icon",children:e.jsx(f,{name:"dashboard",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__context-label",children:"Ctx:"}),e.jsx("span",{className:"flat-terminal-wrapper__context-bar",children:e.jsx("span",{className:"flat-terminal-wrapper__context-bar-fill",style:{width:`${we}%`,backgroundColor:Oe}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:Oe},children:[ce,"k/",Te,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",kt,"% free)"]}),!q&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(f,{name:"warn",size:12})})]})}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),Q.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:Q.map(i=>{const r=R===i.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${r?"flat-terminal-wrapper__building-btn--active":""} ${i.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${r?"Hide":"Show"} terminal: ${i.name}${i.hasUrl?"":" (starting...)"}`,onClick:()=>{if(r){oe(null);return}i.hasUrl||v.sendBuildingCommand(i.id,"start"),oe(i.id)},onContextMenu:u=>{u.preventDefault(),u.stopPropagation(),Ne(i.id,{x:u.clientX,y:u.clientY})},children:e.jsx(f,{name:"terminal",size:14})},i.id)})}),le.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:le.map(i=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${i.name}`,onClick:()=>P(i.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),Ne(i.id,{x:r.clientX,y:r.clientY})},children:e.jsx(f,{name:"scroll",size:14})},i.id))}),Ze.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:Ze.map(i=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${i.name}`,onClick:()=>P(i.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),Ne(i.id,{x:r.clientX,y:r.clientY})},children:e.jsx(f,{name:"hard-drives",size:14})},i.id))}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx(Yn,{})})]}),ne&&e.jsx(Kn,{agentId:l,agents:jt,onClose:vt,branchInfoMap:Ke,fetchRemote:ye,fetchingDirs:he,onResizeStart:i=>Je(i,"right")}),Se&&e.jsx(Zn,{agentId:l,onClose:Ct}),Ee&&e.jsx(Jn,{agentId:l,onClose:Ue})]})});function ja({onAgentClick:d,onBuildingClick:l,onBuildingDoubleClick:m,onBuildingPopup:h,onAreaContextMenu:N,onOpenSpawnModal:T,onOpenBossSpawnModal:M,onOpenAreaModal:L}){const{t:Z}=Pt(["common"]),b=_n(),V=wn(),[P,X]=a.useState(null),[K,ue]=a.useState(null),[te,pe]=a.useState(null),[je,Ye]=a.useState(null),[se,Ne]=a.useState(null),[p,J]=a.useState(null),[me,ke]=a.useState(null),[Re,fe]=a.useState(!1),ie=a.useCallback(()=>{fe(t=>!t)},[]),$e=a.useCallback(()=>{fe(!1)},[]),[We,ze]=a.useState(()=>{const t=zt(S.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Ke=a.useCallback(t=>{ze(t),Ot(S.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=n=>{if(n.key!==S.VIEW_MODE)return;const s=n.newValue;(s==="simple"||s==="chat"||s==="advanced")&&ze(s)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[ye,he]=a.useState(()=>Tt(S.FLAT_INSPECTOR_OPEN,!1)),[Q,le]=a.useState(!1),Ze=a.useCallback(()=>le(t=>!t),[]),ht=a.useCallback(()=>le(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:Q}}))},[Q]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:ye}}))},[ye]),a.useEffect(()=>{const t=()=>le(C=>!C),n=()=>{he(C=>{const k=!C;return de(S.FLAT_INSPECTOR_OPEN,k),k})},s=()=>{le(!1),he(!1),de(S.FLAT_INSPECTOR_OPEN,!1)},g=()=>le(!1),x=()=>{he(!1),de(S.FLAT_INSPECTOR_OPEN,!1)};return window.addEventListener("tide-toggle-flat-agents-drawer",t),window.addEventListener("tide-toggle-flat-inspector",n),window.addEventListener("tide-close-flat-side-views",s),window.addEventListener("tide-close-flat-agents-drawer-only",g),window.addEventListener("tide-close-flat-inspector-only",x),()=>{window.removeEventListener("tide-toggle-flat-agents-drawer",t),window.removeEventListener("tide-toggle-flat-inspector",n),window.removeEventListener("tide-close-flat-side-views",s),window.removeEventListener("tide-close-flat-agents-drawer-only",g),window.removeEventListener("tide-close-flat-inspector-only",x)}},[]);const re=a.useRef(null),Ae=a.useRef(null),[ge,xe]=a.useState(()=>{const t=Bt(S.FLAT_MIDDLE_WIDTH,0);return t>=ft?t:null}),[R,oe]=a.useState(()=>{const t=Bt(S.FLAT_INSPECTOR_WIDTH,0);return t>=It?t:null}),G=a.useCallback(t=>{if(typeof window>"u")return t;const n=R!==null?mt+R:0,s=window.innerWidth-Vt-mt-Ut-n;return Math.max(ft,Math.min(Math.max(s,ft),t))},[R]),be=a.useCallback(t=>{var x;if(typeof window>"u")return t;const n=(x=re.current)==null?void 0:x.querySelector(".flat-middle"),s=(n==null?void 0:n.getBoundingClientRect().width)??ft,g=window.innerWidth-Vt-s-mt-Ut-mt;return Math.max(It,Math.min(Math.max(g,It),t))},[]);a.useEffect(()=>{if(ge===null&&R===null)return;const t=()=>{xe(n=>{if(n===null)return n;const s=G(n);return s===n?n:s}),oe(n=>{if(n===null)return n;const s=be(n);return s===n?n:s})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[ge,R,G,be]);const gt=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=re.current)==null?void 0:s.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ae.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),xt=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=re.current)==null?void 0:s.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ae.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),Je=a.useCallback(t=>{const n=Ae.current;if(!n||t.pointerId!==n.pointerId)return;const s=t.clientX-n.startX;n.kind==="middle"?xe(G(n.startWidth+s)):oe(be(n.startWidth-s))},[G,be]),ne=a.useCallback(t=>{const n=Ae.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(Ae.current=null,document.body.classList.remove("flat-splitter-dragging"),!(Math.abs(t.clientX-n.startX)>2))return;const g=t.clientX-n.startX;if(n.kind==="middle"){const x=G(n.startWidth+g);xe(x),pt(S.FLAT_MIDDLE_WIDTH,x)}else{const x=be(n.startWidth-g);oe(x),pt(S.FLAT_INSPECTOR_WIDTH,x)}},[G,be]),Qe=a.useCallback(()=>{xe(null),pt(S.FLAT_MIDDLE_WIDTH,0)},[]),Se=a.useCallback(()=>{oe(null),pt(S.FLAT_INSPECTOR_WIDTH,0)},[]),[_e,Ee]=a.useState(()=>zt(S.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),He=a.useCallback(t=>{Ee(t),Ot(S.FLAT_INSPECTOR_VIEW,t)},[]),bt=a.useCallback(()=>{he(t=>{const n=!t;return de(S.FLAT_INSPECTOR_OPEN,n),n})},[]),Ue=a.useCallback(()=>{he(!1),de(S.FLAT_INSPECTOR_OPEN,!1)},[]),_t=vn(),wt=a.useCallback((t,n)=>{X({url:t,name:n})},[]),vt=a.useCallback((t,n)=>{ue({command:t,output:n,isLive:!1})},[]),Ct=a.useCallback((t,n)=>{v.setFileViewerPath(t,n)},[]),jt=a.useCallback(t=>{pe(t)},[]),Me=a.useCallback((t,n)=>{Ye({agentId:t,count:n})},[]),ee=a.useCallback(t=>{m?m(t):l(t)},[l,m]),_=a.useMemo(()=>V.size>0?Array.from(V)[0]:null,[V]);a.useEffect(()=>{fe(!1)},[_]);const $=a.useRef([]),q=a.useRef(-1),Ie=a.useRef(!1),Ve=a.useRef(null),[Nt,we]=a.useState(!1),[et,kt]=a.useState(!1),Oe=a.useRef(!1),ce=a.useRef(null),Te=a.useRef(!1),B=a.useMemo(()=>new Set(b.map(t=>t.id)),[b]),tt=a.useMemo(()=>{const t=new Map(b.map(s=>[s.id,s])),n=new Map;for(const s of b)if((s.isBoss||s.class==="boss")&&s.subordinateIds&&s.subordinateIds.length>0){const g=s.subordinateIds.map(x=>t.get(x)).filter(x=>x!==void 0);g.length>0&&n.set(s.id,g)}return n},[b]),F=a.useCallback(()=>{const t=$.current,n=q.current;we(n>0),kt(n>=0&&n<t.length-1)},[]),ve=a.useCallback(t=>{const n=$.current;if(n.length===0)return;let s=q.current+t;for(;s>=0&&s<n.length;){const g=n[s];if(B.has(g)){Ie.current=!0,q.current=s,F(),v.selectAgent(g);return}s+=t}},[B,F]),nt=a.useCallback(()=>ve(-1),[ve]),at=a.useCallback(()=>ve(1),[ve]);aa(a.useCallback(()=>{const t=$.current,n=q.current;return t.length>0&&n>0?(ve(-1),"handled"):"exit"},[ve]));const Be=a.useCallback((t,n)=>{if(typeof window>"u")return;const s=window.history.state,x={...typeof s=="object"&&s!==null?s:{},__flatAgentNav:{agentId:t}};n==="replace"?window.history.replaceState(x,"",window.location.href):window.history.pushState(x,"",window.location.href)},[]);a.useEffect(()=>{if(!_){Oe.current=!1,ce.current=null;return}if(!Oe.current){Be(_,"replace"),Oe.current=!0,ce.current=_;return}if(Te.current){Te.current=!1,ce.current=_;return}ce.current!==_&&(Be(_,"push"),ce.current=_)},[_,Be]),a.useEffect(()=>{const t=n=>{var C,k;const s=(k=(C=n.state)==null?void 0:C.__flatAgentNav)==null?void 0:k.agentId;if(!s||typeof s!="string"||!B.has(s)||s===_)return;Te.current=!0,Ie.current=!0;const g=$.current,x=g.lastIndexOf(s);x>=0?q.current=x:(g.push(s),q.current=g.length-1),F(),v.selectAgent(s)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[B,_,F]),a.useEffect(()=>{if(!_){$.current=[],q.current=-1,F();return}if(Ve.current=_,Ie.current){Ie.current=!1,F();return}const t=$.current,n=q.current;if(n>=0&&t[n]===_){F();return}const s=n<t.length-1?t.slice(0,n+1):t.slice();s.push(_),s.length>100&&s.shift(),$.current=s,q.current=s.length-1,F()},[_,F]);const Xe=a.useCallback(t=>{d(t),le(!1)},[d]),i=_??"",r=a.useCallback(()=>{},[]),u=a.useCallback(t=>{Xe(t)},[Xe]),c=ye,[Ce,Pe]=a.useState(c),[Fe,st]=a.useState(c);a.useEffect(()=>{if(c){Pe(!0);return}st(!1);const t=setTimeout(()=>Pe(!1),240);return()=>clearTimeout(t)},[c]),a.useEffect(()=>{if(!Ce||!c)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>st(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[Ce,c]);const it=a.useRef(null);a.useEffect(()=>{if(_)return;const t=n=>{if(n.key!==" "&&n.key!=="Backspace")return;const s=n.target;if(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.isContentEditable)return;const g=Ve.current;!g||!B.has(g)||(n.preventDefault(),v.selectAgent(g))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[_,B]);const[lt,Y]=a.useState(new Set),z=a.useCallback(t=>{Y(n=>{const s=new Set(n);return s.has(t)?s.delete(t):s.add(t),s})},[]),[ae,en]=a.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches);a.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 768px)"),n=s=>en(s.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[rt,tn]=a.useState(null),nn=a.useCallback(t=>{tn(n=>n===t?null:t)},[]),yt=Kt(),ot=Zt(),[an]=Cn(),Le=a.useMemo(()=>{const t=new Map,n=[];for(const w of b){const A=v.getAreaForAgent(w.id);if(!Ft((A==null?void 0:A.id)??null))continue;if(!A||A.archived){n.push(w);continue}const E=t.get(A.id);E?E.push(w):t.set(A.id,[w])}const s=new Map,g=[];for(const w of ot.values()){let A=!1;for(const E of yt.values())if(!E.archived&&Wt(E.id)&&v.isPositionInArea(w.position,E)){const W=s.get(E.id);W?W.push(w):s.set(E.id,[w]),A=!0;break}!A&&Ft(null)&&g.push(w)}const x=[];for(const[,w]of yt){if(w.archived||!Wt(w.id))continue;const A=t.get(w.id),E=s.get(w.id)??[];(A&&A.length>0||E.length>0)&&x.push({area:w,agents:A??[],buildings:E})}(n.length>0||g.length>0)&&x.push({area:{id:"__unassigned__",name:"Unassigned",color:"#6272a4",center:{x:0,z:0},type:"circle",radius:0,directories:[],archived:!1,assignedAgentIds:[],zIndex:0},agents:n,buildings:g});const C=x.filter(w=>w.area.id!=="__unassigned__"),k=x.filter(w=>w.area.id==="__unassigned__");let o=1,y=1;const O=new Map;if(C.length>1){let w=1/0,A=-1/0,E=1/0,W=-1/0;for(const H of C)w=Math.min(w,H.area.center.x),A=Math.max(A,H.area.center.x),E=Math.min(E,H.area.center.z),W=Math.max(W,H.area.center.z);const ct=A-w||1,dt=W-E||1;if(C.length<=4){o=C.length,y=1;const H=[...C].sort((U,At)=>U.area.center.x-At.area.center.x);for(let U=0;U<H.length;U++)O.set(H[U].area.id,{row:1,col:U+1})}else{const H=[...C].sort((j,D)=>j.area.center.x-D.area.center.x),U=[];for(let j=1;j<H.length;j++)U.push(H[j].area.center.x-H[j-1].area.center.x);const At=U.reduce((j,D)=>j+D,0)/U.length||1;let Lt=1;for(const j of U)j>At*1.3&&Lt++;o=Math.max(2,Math.min(Lt,C.length));const St=[...C].sort((j,D)=>j.area.center.z-D.area.center.z),ut=[];for(let j=1;j<St.length;j++)ut.push(St[j].area.center.z-St[j-1].area.center.z);const on=ut.reduce((j,D)=>j+D,0)/ut.length||1;let Dt=1;for(const j of ut)j>on*1.3&&Dt++;y=Math.max(2,Math.min(Dt,C.length)),o=Math.max(o,Math.ceil(C.length/y)),y=Math.max(y,Math.ceil(C.length/o));const cn=ct/o,dn=dt/y,Et=new Set;for(const j of C){let D=Math.min(o-1,Math.max(0,Math.floor((j.area.center.x-w)/cn))),De=Math.min(y-1,Math.max(0,Math.floor((j.area.center.z-E)/dn))),Ge=`${De},${D}`,Rt=0;const un=y*o;for(;Et.has(Ge)&&Rt<un;)D++,D>=o&&(D=0,De=(De+1)%y),Ge=`${De},${D}`,Rt++;Et.has(Ge)&&(De=y,D=0,Ge=`${De},${D}`,y++),Et.add(Ge),O.set(j.area.id,{row:De+1,col:D+1})}}}const I=w=>{w.sort((A,E)=>{var ct,dt,H,U;const W=(((ct=A.position)==null?void 0:ct.z)??0)-(((dt=E.position)==null?void 0:dt.z)??0);return W!==0?W:(((H=A.position)==null?void 0:H.x)??0)-(((U=E.position)==null?void 0:U.x)??0)})};for(const w of C)I(w.agents);for(const w of k)I(w.agents);return{groups:[...C,...k],gridCols:o,gridRows:y,positions:O}},[b,yt,ot,an]),sn=a.useMemo(()=>{if(!se)return[];const t=b.find(n=>n.id===se.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(f,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-agent-edit",{detail:{agentId:t.id}}))}},{id:"open-chat",label:"Open Chat",icon:e.jsx(f,{name:"chat",size:14}),onClick:()=>d(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(f,{name:"trash",size:14}),danger:!0,onClick:()=>{ke({agentId:t.id,name:t.name})}}]:[]},[se,b,d]),ln=a.useMemo(()=>{var C;if(!p)return[];const t=ot.get(p.buildingId);if(!t)return[];const n=[],s=t.type==="server"||t.type==="docker"||t.type==="terminal",g=t.status==="running",x=t.type==="boss";if(n.push({id:"open",label:t.type==="database"?"Open Database":t.type==="folder"?"Open Folder":t.type==="boss"?"View Boss Logs":t.type==="terminal"?"Open Terminal":t.type==="server"&&((C=t.pm2)!=null&&C.enabled)?"View PM2 Logs":"Open",icon:e.jsx(f,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>ee(t.id)}),s&&(g||n.push({id:"start",label:"Start",icon:e.jsx(f,{name:"play",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"start")}),g&&(n.push({id:"restart",label:"Restart",icon:e.jsx(f,{name:"refresh",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(f,{name:"stop",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"stop")}))),x&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(n.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(f,{name:"launch",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)v.sendBuildingCommand(k,"start")}}),n.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(f,{name:"pause",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)v.sendBuildingCommand(k,"stop")}}),n.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(f,{name:"restart",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)v.sendBuildingCommand(k,"restart")}})),s&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(f,{name:"health",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"healthCheck")}),n.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),n.push({id:"edit",label:"Edit Building",icon:e.jsx(f,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:building-edit",{detail:{buildingId:t.id}}))}}),n.push({id:"clone",label:"Clone Building",icon:e.jsx(f,{name:"copy",size:14}),onClick:()=>{v.createBuilding({name:`${t.name} (Copy)`,type:t.type,style:t.style,color:t.color,scale:t.scale,position:{x:t.position.x+2,z:t.position.z+2},cwd:t.cwd,folderPath:t.folderPath,commands:t.commands,pm2:t.pm2,docker:t.docker,database:t.database,terminal:t.terminal,urls:t.urls,subordinateBuildingIds:t.subordinateBuildingIds})}}),t.urls&&t.urls.length>0)for(const k of t.urls)n.push({id:`url-${k.label}`,label:k.label,icon:e.jsx(f,{name:"link",size:14}),onClick:()=>window.open(k.url,"_blank","noopener,noreferrer")});return n.push({id:"divider-danger",label:"",divider:!0,onClick:()=>{}}),n.push({id:"delete",label:"Delete Building",icon:e.jsx(f,{name:"trash",size:14}),danger:!0,onClick:()=>v.deleteBuilding(t.id)}),n},[p,ot,ee]),rn=a.useCallback(t=>{const n=new Set(Le.groups.map(s=>s.area.id));n.delete(t),Y(n),requestAnimationFrame(()=>{const s=it.current;if(!s)return;const g=s.querySelector(`[data-area-id="${t}"]`);if(!g)return;const x=s.getBoundingClientRect(),k=g.getBoundingClientRect().top-x.top+s.scrollTop-8;s.scrollTo({top:Math.max(0,k),behavior:"smooth"})})},[Le]);return e.jsxs("div",{ref:re,className:`flat-view ${c?"flat-view--with-inspector":""} ${_?"flat-view--has-chat":""} ${Q?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(ge===null&&R===null)return;const t={};return ge!==null&&(t["--flat-middle-width"]=`${ge}px`),R!==null&&(t["--flat-inspector-width"]=`${R}px`),t})(),children:[Q&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:ht,"aria-hidden":"true"}),e.jsxs("div",{className:"flat-middle",children:[e.jsx("div",{className:"flat-middle__header",children:e.jsxs("div",{className:"flat-middle__actions",children:[e.jsx("button",{className:"flat-cta-btn flat-cta-btn--agent",onClick:T,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:M,title:"Create new boss agent",children:"+ Boss"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--area",onClick:L,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(jn,{activeAgentId:i,onClose:r,onSelectAgent:u,collapsedAreas:lt,onToggleArea:z,agentListRef:it})})]}),e.jsx("div",{className:"flat-splitter flat-splitter--middle",role:"separator","aria-orientation":"vertical","aria-label":"Resize agents panel",title:"Drag to resize · Double-click to reset",onPointerDown:gt,onPointerMove:Je,onPointerUp:ne,onPointerCancel:ne,onDoubleClick:Qe}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":Q?"Close agents sidebar":"Open agents sidebar","aria-expanded":Q,onClick:Ze,children:[e.jsx(f,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),_?e.jsx(ba,{agentId:_,terminalViewMode:We,onTerminalViewModeChange:Ke,inspectorOpen:ye,onToggleInspector:bt,onImageClick:wt,onFileClick:Ct,onBashClick:vt,onViewMarkdown:jt,onRequestClearSubordinates:Me,onOpenBuilding:ee,keyboard:_t,canNavigateBack:Nt,canNavigateForward:et,onNavigateBack:nt,onNavigateForward:at,agentInfoOpen:Re,onToggleAgentInfo:ie,onHeaderContextMenu:t=>{_&&Ne({agentId:_,position:t})},onBuildingContextMenu:(t,n)=>{J({buildingId:t,position:n})}}):e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-map",children:[e.jsxs("div",{className:"flat-map__header",children:[e.jsx("span",{className:"flat-map__title",children:"🗺️ Areas"}),e.jsx("span",{className:"flat-map__hint",children:"Click an area to focus it, or an agent to chat"}),e.jsx(da,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Le.gridCols}, 1fr)`},children:Le.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=ae&&rt?((n=Le.positions.get(rt))==null?void 0:n.row)??null:null;return Le.groups.map(s=>{var k;const g=s.area.id,x=Le.positions.get(g),C=ae&&rt!==g;return ae&&t!=null&&(x==null?void 0:x.row)===t&&g!==rt?null:e.jsxs("div",{className:`flat-map-area-card${C?" flat-map-area-card--collapsed":""}`,style:{"--area-color":s.area.color,gridRow:x==null?void 0:x.row,gridColumn:x==null?void 0:x.col},onContextMenu:o=>{N&&(o.preventDefault(),o.stopPropagation(),N(g,{x:o.clientX,y:o.clientY}))},children:[((k=s.area.logo)==null?void 0:k.filename)&&e.jsx("img",{className:"flat-map-area-card__logo",src:na(s.area.logo.filename),alt:"","aria-hidden":"true",onError:o=>{o.currentTarget.style.display="none"}}),e.jsxs("button",{type:"button",className:"flat-map-area-card__header",onClick:()=>ae?nn(g):rn(g),title:ae?C?`Expand ${s.area.name}`:`Collapse ${s.area.name}`:`Focus ${s.area.name} in left panel`,"aria-expanded":ae?!C:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:s.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:s.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:s.agents.length}),ae&&e.jsx(f,{name:C?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:s.agents.map(o=>{const y=o.isBoss||o.class==="boss",O=y?tt.get(o.id):void 0,I=Nn(o),w=I.usedPercent>=80?"#ff4a4a":I.usedPercent>=60?"#ff9e4a":I.usedPercent>=40?"#ffd700":"#4aff9e",A=`Context: ${(I.totalTokens/1e3).toFixed(1)}k / ${(I.contextWindow/1e3).toFixed(1)}k (${I.usedPercent}% used, ${I.freePercent}% free)`,E=o.latestTodos&&o.latestTodos.length>0||O&&O.length>0;return e.jsx(kn,{todos:o.latestTodos,subordinates:O,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${o.status}`,onClick:()=>d(o.id),onContextMenu:W=>{W.preventDefault(),W.stopPropagation(),Ne({agentId:o.id,position:{x:W.clientX,y:W.clientY}})},title:E?void 0:`${y?"Boss · ":""}Open chat with ${o.name}
1
+ import{r as a,B as pn,E as $t,G as Gt,H as qt,j as e,J as Yt,K as mn,u as Pt,L as fn,M as hn,N as gn,O as xn,V as bn,P as _n,U as wn,W as zt,S,X as Ot,Y as Tt,Z as Bt,_ as pt,$ as de,a0 as vn,s as v,a1 as Kt,a2 as Zt,a3 as Cn,w as Ft,x as Wt,I as f,a4 as jn,n as Nn,a5 as kn,a6 as Jt,a7 as Qt,a8 as yn,a9 as An,aa as Sn,ab as En,ac as Mn,ad as In,ae as Tn,af as Pn,ag as Ln,ah as Dn,ai as Rn,aj as $n,ak as Ht,C as zn,al as On,am as Bn,an as Fn,ao as Wn,ap as Hn,aq as Un,ar as Vn,as as Xn,at as Gn,au as qn,av as Yn,aw as Kn,ax as Zn,ay as Jn,az as Qn,aA as ea,aB as ta}from"./main-C7U_3QQV.js";import{g as na}from"./area-logos-TTN-zbpE.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function aa(d){const l=a.useRef(d);l.current=d,a.useEffect(()=>{if(!pn())return;let m=null,h=!1;return $t.addListener("backButton",()=>{l.current()==="exit"&&$t.exitApp()}).then(N=>{h?N.remove():m=N}),()=>{h=!0,m&&(m.remove(),m=null)}},[])}async function sa(d){const l=Gt(),m=await fetch(`${qt()}/api/agents/${d}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${l}`}});if(!m.ok){const h=await m.json().catch(()=>({}));throw new Error((h==null?void 0:h.error)||`Failed to start terminal (${m.status})`)}return m.json()}async function ia(d){const l=Gt();await fetch(`${qt()}/api/agents/${d}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}})}const qe=new Map;function la({agentId:d}){const[l,m]=a.useState(null),[h,N]=a.useState(null);return a.useEffect(()=>{let T=!1;const M=qe.get(d);return M&&(clearTimeout(M),qe.delete(d)),m(null),N(null),sa(d).then(L=>{T||m(L.url)}).catch(L=>{T||N(L instanceof Error?L.message:"Failed to start terminal")}),()=>{T=!0;const L=qe.get(d);L&&clearTimeout(L),qe.set(d,setTimeout(()=>{qe.delete(d),ia(d)},2500))}},[d]),h?e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:h})}):l?e.jsx("div",{className:"flat-classic-terminal",children:e.jsx(Yt,{terminalUrl:l,visible:!0})}):e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:"Attaching to interactive session…"})})}const Mt=new Map,ra=6e4;function oa({agentId:d,contextSummary:l}){const{t:m}=Pt(["terminal","common"]),[h,N]=a.useState(()=>{var P;return((P=Mt.get(d))==null?void 0:P.snapshot)??null}),[T,M]=a.useState(!1),[L,Z]=a.useState(null),b=a.useRef(0);a.useEffect(()=>{const P=Mt.get(d);if(P&&Date.now()-P.fetchedAt<ra){N(P.snapshot);return}const X=++b.current;M(!0),Z(null),fn(d).then(K=>{X===b.current&&(Mt.set(d,{snapshot:K,fetchedAt:Date.now()}),N(K),M(!1))}).catch(K=>{X===b.current&&(Z(K.message||"Failed to load plan limits"),M(!1))})},[d]);const V=[];if(h!=null&&h.rateLimits){const P=[{key:"fiveHour",label:m("terminal:usage.currentSession"),window:h.rateLimits.fiveHour},{key:"sevenDay",label:m("terminal:usage.currentWeekAll"),window:h.rateLimits.sevenDay},{key:"sevenDayOpus",label:m("terminal:usage.currentWeekOpus"),window:h.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:m("terminal:usage.currentWeekSonnet"),window:h.rateLimits.sevenDaySonnet}];for(const X of P)X.window&&V.push({...X,window:X.window})}return e.jsxs("div",{className:"plan-limits-tooltip",children:[l&&e.jsx("div",{className:"plan-limits-tooltip__context",children:l}),e.jsx("div",{className:"plan-limits-tooltip__title",children:m("terminal:usage.limits")}),T&&!h&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[m("common:status.loading"),"…"]}),!T&&L&&!h&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:m("terminal:usage.limitsError",{message:L})}),V.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:V.map(({key:P,label:X,window:K})=>{const ue=Math.max(0,Math.min(100,K.utilization)),te=gn(ue);return e.jsxs("div",{className:"plan-limits-tooltip__gauge",children:[e.jsxs("div",{className:"plan-limits-tooltip__gauge-head",children:[e.jsx("span",{className:"plan-limits-tooltip__gauge-label",children:X}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:te},children:m("terminal:usage.percentUsed",{percent:Math.round(ue)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${ue}%`,background:te}})}),e.jsx("div",{className:"plan-limits-tooltip__reset",children:m("terminal:usage.resets",{time:hn(K.resetsAt)})})]},P)})}):h&&!T&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:h.rateLimitsError?m("terminal:usage.limitsError",{message:h.rateLimitsError}):h.cliHint})]})}function ca({agentId:d,disabled:l,contextSummary:m,children:h}){return e.jsx(mn,{position:"top",maxWidth:320,disabled:l,className:"plan-limits-tooltip-wrapper",triggerStyle:{display:"inline-flex",alignItems:"center"},content:e.jsx(oa,{agentId:d,contextSummary:m}),children:h})}const da=a.memo(function({className:l=""}){const{t:m}=Pt(["common"]),[h,N]=xn(),T=a.useRef(null),[M,L]=a.useState(null);a.useLayoutEffect(()=>{const b=T.current;if(!b)return;const V=b.querySelector(".view-mode-toggle__btn--active");V&&L({left:V.offsetLeft,width:V.offsetWidth})},[h]);const Z=a.useCallback(b=>{if(b!==h){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:b}})),b==="3d"){requestAnimationFrame(()=>N(b));return}N(b)}},[h,N]);return e.jsxs("div",{className:`view-mode-toggle ${l}`,ref:T,children:[M&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:M.left,width:M.width}}),bn.map(b=>e.jsxs("button",{className:`view-mode-toggle__btn ${h===b?"view-mode-toggle__btn--active":""}`,onClick:()=>Z(b),title:m(`common:viewMode.descriptions.${b}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[b==="2d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),b==="3d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}),b==="flat"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]}),b==="dashboard"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),e.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),e.jsx("span",{className:"view-mode-toggle__label",children:m(`common:viewMode.labels.${b}`)})]},b))]})}),mt=3,ft=280,Ut=320,It=240,Vt=64,ua=["simple","chat","advanced"],pa={simple:"Simple",chat:"Chat",advanced:"Advanced"},ma={simple:"○",chat:"◐",advanced:"◉"},fa={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Xt="flat-clear-context";function ha(d){const l=d.split("/").filter(Boolean);return l.length===0?d:l.slice(-2).join("/")}function ga(d){if(d.provider==="codex"){const T=d.codexModel||"gpt-5.3-codex",M=Qn[T];return{model:(M==null?void 0:M.label)||T}}if(d.provider==="opencode")return{model:d.opencodeModel||"opencode"};const l=d.model||"sonnet",m=ta[l],h=d.effort,N=h?ea[h]:void 0;return{model:(m==null?void 0:m.label)||l,effort:N==null?void 0:N.label}}function xa(d,l){if(l.type==="rectangle"&&l.width&&l.height){const m=l.width/2,h=l.height/2;return d.x>=l.center.x-m&&d.x<=l.center.x+m&&d.z>=l.center.z-h&&d.z<=l.center.z+h}if(l.type==="circle"&&l.radius){const m=d.x-l.center.x,h=d.z-l.center.z;return m*m+h*h<=l.radius*l.radius}return!1}const ba=On.memo(function({agentId:l,terminalViewMode:m,onTerminalViewModeChange:h,inspectorOpen:N,onToggleInspector:T,onImageClick:M,onFileClick:L,onBashClick:Z,onViewMarkdown:b,onRequestClearSubordinates:V,onOpenBuilding:P,keyboard:X,canNavigateBack:K,canNavigateForward:ue,onNavigateBack:te,onNavigateForward:pe,agentInfoOpen:je,onToggleAgentInfo:Ye,onHeaderContextMenu:se,onBuildingContextMenu:Ne}){var nt,at,Be,Xe;const p=Bn(l),J=Zt(),me=Fn(),ke=a.useRef(null),Re=a.useRef(null),fe=!!me.interactiveMode&&((p==null?void 0:p.provider)??"claude")==="claude"&&!!(p!=null&&p.sessionId),[ie,$e]=a.useState(!1);a.useEffect(()=>{$e(!1)},[l]),a.useEffect(()=>{!fe&&ie&&$e(!1)},[fe,ie]),a.useEffect(()=>{const i=Re.current;if(!i)return;const r=c=>{c.button===3?(c.preventDefault(),c.stopPropagation(),te()):c.button===4&&(c.preventDefault(),c.stopPropagation(),pe())},u=c=>{(c.button===3||c.button===4)&&c.preventDefault()};return i.addEventListener("mouseup",r),i.addEventListener("mousedown",u),()=>{i.removeEventListener("mouseup",r),i.removeEventListener("mousedown",u)}},[te,pe]),a.useEffect(()=>{const i=Re.current;if(!i)return;let r=0,u=0,c=0;const Ce=250,Pe=600,Fe=80,st=1.5,it=Y=>{let z=Y instanceof HTMLElement?Y:null;for(;z&&z!==i;){const ae=window.getComputedStyle(z).overflowX;if((ae==="auto"||ae==="scroll")&&z.scrollWidth>z.clientWidth)return!0;z=z.parentElement}return!1},lt=Y=>{const z=Date.now();if(z<c){Y.preventDefault();return}if(Math.abs(Y.deltaX)<=Math.abs(Y.deltaY)*st){r=0;return}if(it(Y.target)){r=0;return}z-u>Ce&&(r=0),u=z,r+=Y.deltaX,r<=-Fe?(r=0,c=z+Pe,Y.preventDefault(),te()):r>=Fe&&(r=0,c=z+Pe,Y.preventDefault(),pe())};return i.addEventListener("wheel",lt,{passive:!1}),()=>i.removeEventListener("wheel",lt)},[te,pe]);const We=Kt(),ze=a.useMemo(()=>{if(!p)return null;const i=new Set,r=[];for(const u of We.values())u.archived||u.directories.length===0||u.assignedAgentIds.includes(l)&&(i.add(u.id),r.push(u));for(const u of We.values())u.archived||u.directories.length===0||i.has(u.id)||xa({x:p.position.x,z:p.position.z},u)&&(i.add(u.id),r.push(u));return r.length===0?null:r.flatMap(u=>u.directories.filter(c=>c&&c.trim().length>0).map(c=>({areaId:u.id,areaName:u.name,dir:c})))},[p,l,We]),{branches:Ke,fetchRemote:ye,fetchingDirs:he}=Wn(ze),Q=a.useMemo(()=>{var u;const i=v.getAreaForAgent(l);if(!i)return[];const r=[];for(const c of J.values())c.type==="terminal"&&v.isPositionInArea(c.position,i)&&r.push({id:c.id,name:c.name,hasUrl:!!((u=c.terminalStatus)!=null&&u.url)});return r},[l,J]),le=a.useMemo(()=>{var u;const i=v.getAreaForAgent(l);if(!i)return[];const r=[];for(const c of J.values())c.type==="server"&&((u=c.pm2)!=null&&u.enabled)&&v.isPositionInArea(c.position,i)&&r.push({id:c.id,name:c.name});return r},[l,J]),Ze=a.useMemo(()=>{const i=v.getAreaForAgent(l);if(!i)return[];const r=[];for(const u of J.values())u.type==="database"&&u.database&&v.isPositionInArea(u.position,i)&&r.push({id:u.id,name:u.name});return r},[l,J]),[,ht]=a.useReducer(i=>i+1,0),re=((nt=ke.current)==null?void 0:nt.search.searchMode)??!1,Ae=a.useCallback(()=>{var i;(i=ke.current)==null||i.search.toggleSearch(),ht()},[]),ge=Hn(),xe=ge.isPending(Xt),[R,oe]=a.useState(null),G=R?J.get(R):null,{height:be,onResizeStart:gt}=Un(),{sidePanelWidth:xt,handleSidePanelResizeStart:Je}=Vn(),[ne,Qe]=a.useState(()=>Tt(S.GIT_PANEL_OPEN,!1)),[Se,_e]=a.useState(()=>Tt(S.BUILDINGS_PANEL_OPEN,!1)),[Ee,He]=a.useState(!1),bt=a.useCallback(()=>{He(i=>{const r=!i;return r&&Xn.setEnabled(!0),r})},[]),Ue=a.useCallback(()=>He(!1),[]),_t=a.useCallback(()=>{Qe(i=>{const r=!i;return de(S.GIT_PANEL_OPEN,r),r})},[]),wt=a.useCallback(()=>{_e(i=>{const r=!i;return de(S.BUILDINGS_PANEL_OPEN,r),r})},[]),vt=a.useCallback(()=>{Qe(!1),de(S.GIT_PANEL_OPEN,!1)},[]),Ct=a.useCallback(()=>{_e(!1),de(S.BUILDINGS_PANEL_OPEN,!1)},[]),jt=Gn();a.useEffect(()=>{if(!R)return;Q.some(r=>r.id===R)||oe(null)},[R,Q]);const[Me,ee]=a.useState(!1),_=a.useRef(null);if(a.useEffect(()=>{if(!Me)return;const i=r=>{_.current&&!_.current.contains(r.target)&&ee(!1)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[Me]),!p)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const $=p.contextStats,q=!!$,Ie=$?$.totalTokens:p.contextUsed||0,Ve=$?$.contextWindow:p.contextLimit||2e5,Nt=$?$.usedPercent:Math.round(Ie/Ve*100),we=Math.max(0,Math.min(100,Nt)),et=Math.round(we*10)/10,kt=Math.round((100-we)*10)/10,Oe=we>=80?"#ff4a4a":we>=60?"#ff9e4a":we>=40?"#ffd700":"#4aff9e",ce=(Ie/1e3).toFixed(1),Te=(Ve/1e3).toFixed(1),B=p.cwd,tt=B?ha(B):null,F=((at=p.subordinateIds)==null?void 0:at.length)||0,ve=F>0;return e.jsxs("div",{ref:Re,className:`flat-terminal-wrapper ${ne||Se||Ee?"flat-terminal-wrapper--with-side-panel":""}`,style:{"--guake-side-panel-width":`min(${xt}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${je?"flat-terminal-wrapper__header-main--active":""}`,onClick:Ye,onContextMenu:i=>{i.preventDefault(),i.stopPropagation(),se({x:i.clientX,y:i.clientY})},title:je?"Hide agent info":"Show agent info","aria-pressed":je,children:[e.jsx(Jt,{agent:p,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:p.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:Qt(p.status)},children:p.status})]}),p.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:p.taskLabel,children:["📋 ",p.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:p.provider==="codex"?"/assets/codex.png":p.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:p.provider,className:"flat-terminal-wrapper__header-provider-icon",title:p.provider==="codex"?"Codex Agent":p.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:i,effort:r}=ga(p);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:r?`Model: ${i} · Effort: ${r}`:`Model: ${i}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:i}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-sep","aria-hidden":"true",children:"·"}),e.jsx("span",{className:"flat-terminal-wrapper__header-model-effort",children:r})]})]})})()]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__header-meta",children:[e.jsxs("div",{className:"flat-terminal-wrapper__view-mode",role:"group","aria-label":"Message view mode",children:[ua.map(i=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${!ie&&m===i?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{$e(!1),h(i)},title:fa[i],"aria-pressed":!ie&&m===i,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:ma[i]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:pa[i]})]},i)),fe&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${ie?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>$e(i=>!i),title:"Classic TUI — attach to the live interactive claude session in a terminal","aria-pressed":ie,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:e.jsx(f,{name:"terminal",size:13})}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:"Classic TUI"})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__actions",role:"group","aria-label":"Terminal actions",children:[e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:te,disabled:!K,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(f,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:pe,disabled:!ue,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(f,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${re?"flat-terminal-wrapper__action-btn--active":""}`,onClick:Ae,title:re?"Close search":"Search messages","aria-pressed":re,children:e.jsx(f,{name:re?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${xe?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>ge.handleClick(Xt,()=>{var i;v.clearContext(l),(i=ke.current)==null||i.historyLoader.clearHistory()}),title:xe?"Click again to confirm clear context":"Clear context",children:e.jsx(f,{name:xe?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ne?"flat-terminal-wrapper__action-btn--active":""}`,onClick:_t,title:ne?"Hide git panel":"Show git changes","aria-pressed":ne,children:e.jsx(f,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Se?"flat-terminal-wrapper__action-btn--active":""}`,onClick:wt,title:Se?"Hide buildings panel":"Show area buildings","aria-pressed":Se,children:e.jsx(f,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:_,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Me?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>ee(i=>!i),title:"More actions","aria-expanded":Me,children:"⋮"}),Me&&e.jsxs("div",{className:"flat-terminal-wrapper__more-menu",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-terminal-wrapper__more-item ${Ee?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{bt(),ee(!1)},title:Ee?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(f,{name:"bug",size:14}),e.jsx("span",{children:Ee?"Hide Debug Panel":"Show Debug Panel"})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item",onClick:()=>{v.collapseContext(l),ee(!1)},disabled:p.status!=="idle",title:p.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(f,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),ve&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{V(l,F),ee(!1)},children:[e.jsx(f,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",F," subordinate",F===1?"":"s"]})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{v.killAgent(l),ee(!1)},children:[e.jsx(f,{name:"cross",size:14}),e.jsx("span",{children:"Remove agent"})]})]})]})]}),e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__inspector-toggle ${N?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:T,title:N?"Hide inspector panel":"Show inspector panel","aria-label":N?"Hide inspector panel":"Show inspector panel","aria-pressed":N,children:[e.jsx("span",{className:"flat-terminal-wrapper__inspector-icon","aria-hidden":"true",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"}),e.jsx("line",{x1:"10",y1:"2.5",x2:"10",y2:"13.5"})]})}),e.jsx("span",{className:"flat-terminal-wrapper__inspector-label",children:"Inspector"})]}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__close",onClick:()=>v.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(f,{name:"cross",size:14})})]})]}),ie&&fe?e.jsx(la,{agentId:l}):e.jsx(qn,{ref:ke,agentId:l,agent:p,viewMode:m,isOpen:!0,onImageClick:M,onFileClick:L,onBashClick:Z,onViewMarkdown:b,keyboard:X,hasModalOpen:!1}),G&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:gt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${G.name}`,style:{height:be},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(f,{name:"terminal",size:12}),e.jsx("span",{children:G.name}),!((Be=G.terminalStatus)!=null&&Be.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>oe(null),title:"Close embedded terminal","aria-label":"Close embedded terminal",children:e.jsx(f,{name:"cross",size:12})})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:(Xe=G.terminalStatus)!=null&&Xe.url?e.jsx(Yt,{terminalUrl:G.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."})})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[p.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(f,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),B&&tt&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${B}`,"aria-label":`Open ${B} in file explorer`,role:"button",tabIndex:0,onClick:()=>v.openFileExplorer(B),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),v.openFileExplorer(B))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(f,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:tt})]}),ze&&ze.map(({areaId:i,areaName:r,dir:u})=>{const c=Ke.get(u),Ce=he.has(u),Pe=u.split("/").filter(Boolean).pop()||u;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${r}: ${u}${c?` (${c.branch}${c.ahead?` ↑${c.ahead}`:""}${c.behind?` ↓${c.behind}`:""})`:""}`,onClick:()=>v.openFileExplorerForAreaFolder(i,u),children:[e.jsx(f,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:Pe}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(f,{name:"git-branch",size:10})," ",c.branch]}),c.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${c.ahead} ahead`,children:[e.jsx(f,{name:"arrow-up",size:9}),c.ahead]}),c.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${c.behind} behind`,children:[e.jsx(f,{name:"arrow-down",size:9}),c.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${Ce?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Fe=>{Fe.stopPropagation(),ye(u)},children:e.jsx(f,{name:Ce?"hourglass":"download",size:12})})]})]},`${i}:${u}`)}),e.jsx(ca,{agentId:l,disabled:((p==null?void 0:p.provider)??"claude")!=="claude",contextSummary:q?`Context: ${ce}k / ${Te}k tokens (${et}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>v.setContextModalAgentId(l),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),v.setContextModalAgentId(l))},title:((p==null?void 0:p.provider)??"claude")!=="claude"?q?`Context usage: ${ce}k / ${Te}k tokens (${et}% used). Click to view stats.`:"Click to fetch context stats":void 0,children:[e.jsx("span",{className:"flat-terminal-wrapper__context-icon",children:e.jsx(f,{name:"dashboard",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__context-label",children:"Ctx:"}),e.jsx("span",{className:"flat-terminal-wrapper__context-bar",children:e.jsx("span",{className:"flat-terminal-wrapper__context-bar-fill",style:{width:`${we}%`,backgroundColor:Oe}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:Oe},children:[ce,"k/",Te,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",kt,"% free)"]}),!q&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(f,{name:"warn",size:12})})]})}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),Q.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:Q.map(i=>{const r=R===i.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${r?"flat-terminal-wrapper__building-btn--active":""} ${i.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${r?"Hide":"Show"} terminal: ${i.name}${i.hasUrl?"":" (starting...)"}`,onClick:()=>{if(r){oe(null);return}i.hasUrl||v.sendBuildingCommand(i.id,"start"),oe(i.id)},onContextMenu:u=>{u.preventDefault(),u.stopPropagation(),Ne(i.id,{x:u.clientX,y:u.clientY})},children:e.jsx(f,{name:"terminal",size:14})},i.id)})}),le.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:le.map(i=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${i.name}`,onClick:()=>P(i.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),Ne(i.id,{x:r.clientX,y:r.clientY})},children:e.jsx(f,{name:"scroll",size:14})},i.id))}),Ze.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:Ze.map(i=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${i.name}`,onClick:()=>P(i.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),Ne(i.id,{x:r.clientX,y:r.clientY})},children:e.jsx(f,{name:"hard-drives",size:14})},i.id))}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx(Yn,{})})]}),ne&&e.jsx(Kn,{agentId:l,agents:jt,onClose:vt,branchInfoMap:Ke,fetchRemote:ye,fetchingDirs:he,onResizeStart:i=>Je(i,"right")}),Se&&e.jsx(Zn,{agentId:l,onClose:Ct}),Ee&&e.jsx(Jn,{agentId:l,onClose:Ue})]})});function ja({onAgentClick:d,onBuildingClick:l,onBuildingDoubleClick:m,onBuildingPopup:h,onAreaContextMenu:N,onOpenSpawnModal:T,onOpenBossSpawnModal:M,onOpenAreaModal:L}){const{t:Z}=Pt(["common"]),b=_n(),V=wn(),[P,X]=a.useState(null),[K,ue]=a.useState(null),[te,pe]=a.useState(null),[je,Ye]=a.useState(null),[se,Ne]=a.useState(null),[p,J]=a.useState(null),[me,ke]=a.useState(null),[Re,fe]=a.useState(!1),ie=a.useCallback(()=>{fe(t=>!t)},[]),$e=a.useCallback(()=>{fe(!1)},[]),[We,ze]=a.useState(()=>{const t=zt(S.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Ke=a.useCallback(t=>{ze(t),Ot(S.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=n=>{if(n.key!==S.VIEW_MODE)return;const s=n.newValue;(s==="simple"||s==="chat"||s==="advanced")&&ze(s)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[ye,he]=a.useState(()=>Tt(S.FLAT_INSPECTOR_OPEN,!1)),[Q,le]=a.useState(!1),Ze=a.useCallback(()=>le(t=>!t),[]),ht=a.useCallback(()=>le(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:Q}}))},[Q]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:ye}}))},[ye]),a.useEffect(()=>{const t=()=>le(C=>!C),n=()=>{he(C=>{const k=!C;return de(S.FLAT_INSPECTOR_OPEN,k),k})},s=()=>{le(!1),he(!1),de(S.FLAT_INSPECTOR_OPEN,!1)},g=()=>le(!1),x=()=>{he(!1),de(S.FLAT_INSPECTOR_OPEN,!1)};return window.addEventListener("tide-toggle-flat-agents-drawer",t),window.addEventListener("tide-toggle-flat-inspector",n),window.addEventListener("tide-close-flat-side-views",s),window.addEventListener("tide-close-flat-agents-drawer-only",g),window.addEventListener("tide-close-flat-inspector-only",x),()=>{window.removeEventListener("tide-toggle-flat-agents-drawer",t),window.removeEventListener("tide-toggle-flat-inspector",n),window.removeEventListener("tide-close-flat-side-views",s),window.removeEventListener("tide-close-flat-agents-drawer-only",g),window.removeEventListener("tide-close-flat-inspector-only",x)}},[]);const re=a.useRef(null),Ae=a.useRef(null),[ge,xe]=a.useState(()=>{const t=Bt(S.FLAT_MIDDLE_WIDTH,0);return t>=ft?t:null}),[R,oe]=a.useState(()=>{const t=Bt(S.FLAT_INSPECTOR_WIDTH,0);return t>=It?t:null}),G=a.useCallback(t=>{if(typeof window>"u")return t;const n=R!==null?mt+R:0,s=window.innerWidth-Vt-mt-Ut-n;return Math.max(ft,Math.min(Math.max(s,ft),t))},[R]),be=a.useCallback(t=>{var x;if(typeof window>"u")return t;const n=(x=re.current)==null?void 0:x.querySelector(".flat-middle"),s=(n==null?void 0:n.getBoundingClientRect().width)??ft,g=window.innerWidth-Vt-s-mt-Ut-mt;return Math.max(It,Math.min(Math.max(g,It),t))},[]);a.useEffect(()=>{if(ge===null&&R===null)return;const t=()=>{xe(n=>{if(n===null)return n;const s=G(n);return s===n?n:s}),oe(n=>{if(n===null)return n;const s=be(n);return s===n?n:s})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[ge,R,G,be]);const gt=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=re.current)==null?void 0:s.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ae.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),xt=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=re.current)==null?void 0:s.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ae.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),Je=a.useCallback(t=>{const n=Ae.current;if(!n||t.pointerId!==n.pointerId)return;const s=t.clientX-n.startX;n.kind==="middle"?xe(G(n.startWidth+s)):oe(be(n.startWidth-s))},[G,be]),ne=a.useCallback(t=>{const n=Ae.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(Ae.current=null,document.body.classList.remove("flat-splitter-dragging"),!(Math.abs(t.clientX-n.startX)>2))return;const g=t.clientX-n.startX;if(n.kind==="middle"){const x=G(n.startWidth+g);xe(x),pt(S.FLAT_MIDDLE_WIDTH,x)}else{const x=be(n.startWidth-g);oe(x),pt(S.FLAT_INSPECTOR_WIDTH,x)}},[G,be]),Qe=a.useCallback(()=>{xe(null),pt(S.FLAT_MIDDLE_WIDTH,0)},[]),Se=a.useCallback(()=>{oe(null),pt(S.FLAT_INSPECTOR_WIDTH,0)},[]),[_e,Ee]=a.useState(()=>zt(S.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),He=a.useCallback(t=>{Ee(t),Ot(S.FLAT_INSPECTOR_VIEW,t)},[]),bt=a.useCallback(()=>{he(t=>{const n=!t;return de(S.FLAT_INSPECTOR_OPEN,n),n})},[]),Ue=a.useCallback(()=>{he(!1),de(S.FLAT_INSPECTOR_OPEN,!1)},[]),_t=vn(),wt=a.useCallback((t,n)=>{X({url:t,name:n})},[]),vt=a.useCallback((t,n)=>{ue({command:t,output:n,isLive:!1})},[]),Ct=a.useCallback((t,n)=>{v.setFileViewerPath(t,n)},[]),jt=a.useCallback(t=>{pe(t)},[]),Me=a.useCallback((t,n)=>{Ye({agentId:t,count:n})},[]),ee=a.useCallback(t=>{m?m(t):l(t)},[l,m]),_=a.useMemo(()=>V.size>0?Array.from(V)[0]:null,[V]);a.useEffect(()=>{fe(!1)},[_]);const $=a.useRef([]),q=a.useRef(-1),Ie=a.useRef(!1),Ve=a.useRef(null),[Nt,we]=a.useState(!1),[et,kt]=a.useState(!1),Oe=a.useRef(!1),ce=a.useRef(null),Te=a.useRef(!1),B=a.useMemo(()=>new Set(b.map(t=>t.id)),[b]),tt=a.useMemo(()=>{const t=new Map(b.map(s=>[s.id,s])),n=new Map;for(const s of b)if((s.isBoss||s.class==="boss")&&s.subordinateIds&&s.subordinateIds.length>0){const g=s.subordinateIds.map(x=>t.get(x)).filter(x=>x!==void 0);g.length>0&&n.set(s.id,g)}return n},[b]),F=a.useCallback(()=>{const t=$.current,n=q.current;we(n>0),kt(n>=0&&n<t.length-1)},[]),ve=a.useCallback(t=>{const n=$.current;if(n.length===0)return;let s=q.current+t;for(;s>=0&&s<n.length;){const g=n[s];if(B.has(g)){Ie.current=!0,q.current=s,F(),v.selectAgent(g);return}s+=t}},[B,F]),nt=a.useCallback(()=>ve(-1),[ve]),at=a.useCallback(()=>ve(1),[ve]);aa(a.useCallback(()=>{const t=$.current,n=q.current;return t.length>0&&n>0?(ve(-1),"handled"):"exit"},[ve]));const Be=a.useCallback((t,n)=>{if(typeof window>"u")return;const s=window.history.state,x={...typeof s=="object"&&s!==null?s:{},__flatAgentNav:{agentId:t}};n==="replace"?window.history.replaceState(x,"",window.location.href):window.history.pushState(x,"",window.location.href)},[]);a.useEffect(()=>{if(!_){Oe.current=!1,ce.current=null;return}if(!Oe.current){Be(_,"replace"),Oe.current=!0,ce.current=_;return}if(Te.current){Te.current=!1,ce.current=_;return}ce.current!==_&&(Be(_,"push"),ce.current=_)},[_,Be]),a.useEffect(()=>{const t=n=>{var C,k;const s=(k=(C=n.state)==null?void 0:C.__flatAgentNav)==null?void 0:k.agentId;if(!s||typeof s!="string"||!B.has(s)||s===_)return;Te.current=!0,Ie.current=!0;const g=$.current,x=g.lastIndexOf(s);x>=0?q.current=x:(g.push(s),q.current=g.length-1),F(),v.selectAgent(s)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[B,_,F]),a.useEffect(()=>{if(!_){$.current=[],q.current=-1,F();return}if(Ve.current=_,Ie.current){Ie.current=!1,F();return}const t=$.current,n=q.current;if(n>=0&&t[n]===_){F();return}const s=n<t.length-1?t.slice(0,n+1):t.slice();s.push(_),s.length>100&&s.shift(),$.current=s,q.current=s.length-1,F()},[_,F]);const Xe=a.useCallback(t=>{d(t),le(!1)},[d]),i=_??"",r=a.useCallback(()=>{},[]),u=a.useCallback(t=>{Xe(t)},[Xe]),c=ye,[Ce,Pe]=a.useState(c),[Fe,st]=a.useState(c);a.useEffect(()=>{if(c){Pe(!0);return}st(!1);const t=setTimeout(()=>Pe(!1),240);return()=>clearTimeout(t)},[c]),a.useEffect(()=>{if(!Ce||!c)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>st(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[Ce,c]);const it=a.useRef(null);a.useEffect(()=>{if(_)return;const t=n=>{if(n.key!==" "&&n.key!=="Backspace")return;const s=n.target;if(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.isContentEditable)return;const g=Ve.current;!g||!B.has(g)||(n.preventDefault(),v.selectAgent(g))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[_,B]);const[lt,Y]=a.useState(new Set),z=a.useCallback(t=>{Y(n=>{const s=new Set(n);return s.has(t)?s.delete(t):s.add(t),s})},[]),[ae,en]=a.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches);a.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 768px)"),n=s=>en(s.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[rt,tn]=a.useState(null),nn=a.useCallback(t=>{tn(n=>n===t?null:t)},[]),yt=Kt(),ot=Zt(),[an]=Cn(),Le=a.useMemo(()=>{const t=new Map,n=[];for(const w of b){const A=v.getAreaForAgent(w.id);if(!Ft((A==null?void 0:A.id)??null))continue;if(!A||A.archived){n.push(w);continue}const E=t.get(A.id);E?E.push(w):t.set(A.id,[w])}const s=new Map,g=[];for(const w of ot.values()){let A=!1;for(const E of yt.values())if(!E.archived&&Wt(E.id)&&v.isPositionInArea(w.position,E)){const W=s.get(E.id);W?W.push(w):s.set(E.id,[w]),A=!0;break}!A&&Ft(null)&&g.push(w)}const x=[];for(const[,w]of yt){if(w.archived||!Wt(w.id))continue;const A=t.get(w.id),E=s.get(w.id)??[];(A&&A.length>0||E.length>0)&&x.push({area:w,agents:A??[],buildings:E})}(n.length>0||g.length>0)&&x.push({area:{id:"__unassigned__",name:"Unassigned",color:"#6272a4",center:{x:0,z:0},type:"circle",radius:0,directories:[],archived:!1,assignedAgentIds:[],zIndex:0},agents:n,buildings:g});const C=x.filter(w=>w.area.id!=="__unassigned__"),k=x.filter(w=>w.area.id==="__unassigned__");let o=1,y=1;const O=new Map;if(C.length>1){let w=1/0,A=-1/0,E=1/0,W=-1/0;for(const H of C)w=Math.min(w,H.area.center.x),A=Math.max(A,H.area.center.x),E=Math.min(E,H.area.center.z),W=Math.max(W,H.area.center.z);const ct=A-w||1,dt=W-E||1;if(C.length<=4){o=C.length,y=1;const H=[...C].sort((U,At)=>U.area.center.x-At.area.center.x);for(let U=0;U<H.length;U++)O.set(H[U].area.id,{row:1,col:U+1})}else{const H=[...C].sort((j,D)=>j.area.center.x-D.area.center.x),U=[];for(let j=1;j<H.length;j++)U.push(H[j].area.center.x-H[j-1].area.center.x);const At=U.reduce((j,D)=>j+D,0)/U.length||1;let Lt=1;for(const j of U)j>At*1.3&&Lt++;o=Math.max(2,Math.min(Lt,C.length));const St=[...C].sort((j,D)=>j.area.center.z-D.area.center.z),ut=[];for(let j=1;j<St.length;j++)ut.push(St[j].area.center.z-St[j-1].area.center.z);const on=ut.reduce((j,D)=>j+D,0)/ut.length||1;let Dt=1;for(const j of ut)j>on*1.3&&Dt++;y=Math.max(2,Math.min(Dt,C.length)),o=Math.max(o,Math.ceil(C.length/y)),y=Math.max(y,Math.ceil(C.length/o));const cn=ct/o,dn=dt/y,Et=new Set;for(const j of C){let D=Math.min(o-1,Math.max(0,Math.floor((j.area.center.x-w)/cn))),De=Math.min(y-1,Math.max(0,Math.floor((j.area.center.z-E)/dn))),Ge=`${De},${D}`,Rt=0;const un=y*o;for(;Et.has(Ge)&&Rt<un;)D++,D>=o&&(D=0,De=(De+1)%y),Ge=`${De},${D}`,Rt++;Et.has(Ge)&&(De=y,D=0,Ge=`${De},${D}`,y++),Et.add(Ge),O.set(j.area.id,{row:De+1,col:D+1})}}}const I=w=>{w.sort((A,E)=>{var ct,dt,H,U;const W=(((ct=A.position)==null?void 0:ct.z)??0)-(((dt=E.position)==null?void 0:dt.z)??0);return W!==0?W:(((H=A.position)==null?void 0:H.x)??0)-(((U=E.position)==null?void 0:U.x)??0)})};for(const w of C)I(w.agents);for(const w of k)I(w.agents);return{groups:[...C,...k],gridCols:o,gridRows:y,positions:O}},[b,yt,ot,an]),sn=a.useMemo(()=>{if(!se)return[];const t=b.find(n=>n.id===se.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(f,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-agent-edit",{detail:{agentId:t.id}}))}},{id:"open-chat",label:"Open Chat",icon:e.jsx(f,{name:"chat",size:14}),onClick:()=>d(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(f,{name:"trash",size:14}),danger:!0,onClick:()=>{ke({agentId:t.id,name:t.name})}}]:[]},[se,b,d]),ln=a.useMemo(()=>{var C;if(!p)return[];const t=ot.get(p.buildingId);if(!t)return[];const n=[],s=t.type==="server"||t.type==="docker"||t.type==="terminal",g=t.status==="running",x=t.type==="boss";if(n.push({id:"open",label:t.type==="database"?"Open Database":t.type==="folder"?"Open Folder":t.type==="boss"?"View Boss Logs":t.type==="terminal"?"Open Terminal":t.type==="server"&&((C=t.pm2)!=null&&C.enabled)?"View PM2 Logs":"Open",icon:e.jsx(f,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>ee(t.id)}),s&&(g||n.push({id:"start",label:"Start",icon:e.jsx(f,{name:"play",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"start")}),g&&(n.push({id:"restart",label:"Restart",icon:e.jsx(f,{name:"refresh",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(f,{name:"stop",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"stop")}))),x&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(n.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(f,{name:"launch",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)v.sendBuildingCommand(k,"start")}}),n.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(f,{name:"pause",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)v.sendBuildingCommand(k,"stop")}}),n.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(f,{name:"restart",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)v.sendBuildingCommand(k,"restart")}})),s&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(f,{name:"health",size:14}),onClick:()=>v.sendBuildingCommand(t.id,"healthCheck")}),n.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),n.push({id:"edit",label:"Edit Building",icon:e.jsx(f,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:building-edit",{detail:{buildingId:t.id}}))}}),n.push({id:"clone",label:"Clone Building",icon:e.jsx(f,{name:"copy",size:14}),onClick:()=>{v.createBuilding({name:`${t.name} (Copy)`,type:t.type,style:t.style,color:t.color,scale:t.scale,position:{x:t.position.x+2,z:t.position.z+2},cwd:t.cwd,folderPath:t.folderPath,commands:t.commands,pm2:t.pm2,docker:t.docker,database:t.database,terminal:t.terminal,urls:t.urls,subordinateBuildingIds:t.subordinateBuildingIds})}}),t.urls&&t.urls.length>0)for(const k of t.urls)n.push({id:`url-${k.label}`,label:k.label,icon:e.jsx(f,{name:"link",size:14}),onClick:()=>window.open(k.url,"_blank","noopener,noreferrer")});return n.push({id:"divider-danger",label:"",divider:!0,onClick:()=>{}}),n.push({id:"delete",label:"Delete Building",icon:e.jsx(f,{name:"trash",size:14}),danger:!0,onClick:()=>v.deleteBuilding(t.id)}),n},[p,ot,ee]),rn=a.useCallback(t=>{const n=new Set(Le.groups.map(s=>s.area.id));n.delete(t),Y(n),requestAnimationFrame(()=>{const s=it.current;if(!s)return;const g=s.querySelector(`[data-area-id="${t}"]`);if(!g)return;const x=s.getBoundingClientRect(),k=g.getBoundingClientRect().top-x.top+s.scrollTop-8;s.scrollTo({top:Math.max(0,k),behavior:"smooth"})})},[Le]);return e.jsxs("div",{ref:re,className:`flat-view ${c?"flat-view--with-inspector":""} ${_?"flat-view--has-chat":""} ${Q?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(ge===null&&R===null)return;const t={};return ge!==null&&(t["--flat-middle-width"]=`${ge}px`),R!==null&&(t["--flat-inspector-width"]=`${R}px`),t})(),children:[Q&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:ht,"aria-hidden":"true"}),e.jsxs("div",{className:"flat-middle",children:[e.jsx("div",{className:"flat-middle__header",children:e.jsxs("div",{className:"flat-middle__actions",children:[e.jsx("button",{className:"flat-cta-btn flat-cta-btn--agent",onClick:T,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:M,title:"Create new boss agent",children:"+ Boss"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--area",onClick:L,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(jn,{activeAgentId:i,onClose:r,onSelectAgent:u,collapsedAreas:lt,onToggleArea:z,agentListRef:it})})]}),e.jsx("div",{className:"flat-splitter flat-splitter--middle",role:"separator","aria-orientation":"vertical","aria-label":"Resize agents panel",title:"Drag to resize · Double-click to reset",onPointerDown:gt,onPointerMove:Je,onPointerUp:ne,onPointerCancel:ne,onDoubleClick:Qe}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":Q?"Close agents sidebar":"Open agents sidebar","aria-expanded":Q,onClick:Ze,children:[e.jsx(f,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),_?e.jsx(ba,{agentId:_,terminalViewMode:We,onTerminalViewModeChange:Ke,inspectorOpen:ye,onToggleInspector:bt,onImageClick:wt,onFileClick:Ct,onBashClick:vt,onViewMarkdown:jt,onRequestClearSubordinates:Me,onOpenBuilding:ee,keyboard:_t,canNavigateBack:Nt,canNavigateForward:et,onNavigateBack:nt,onNavigateForward:at,agentInfoOpen:Re,onToggleAgentInfo:ie,onHeaderContextMenu:t=>{_&&Ne({agentId:_,position:t})},onBuildingContextMenu:(t,n)=>{J({buildingId:t,position:n})}}):e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-map",children:[e.jsxs("div",{className:"flat-map__header",children:[e.jsx("span",{className:"flat-map__title",children:"🗺️ Areas"}),e.jsx("span",{className:"flat-map__hint",children:"Click an area to focus it, or an agent to chat"}),e.jsx(da,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Le.gridCols}, 1fr)`},children:Le.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=ae&&rt?((n=Le.positions.get(rt))==null?void 0:n.row)??null:null;return Le.groups.map(s=>{var k;const g=s.area.id,x=Le.positions.get(g),C=ae&&rt!==g;return ae&&t!=null&&(x==null?void 0:x.row)===t&&g!==rt?null:e.jsxs("div",{className:`flat-map-area-card${C?" flat-map-area-card--collapsed":""}`,style:{"--area-color":s.area.color,gridRow:x==null?void 0:x.row,gridColumn:x==null?void 0:x.col},onContextMenu:o=>{N&&(o.preventDefault(),o.stopPropagation(),N(g,{x:o.clientX,y:o.clientY}))},children:[((k=s.area.logo)==null?void 0:k.filename)&&e.jsx("img",{className:"flat-map-area-card__logo",src:na(s.area.logo.filename),alt:"","aria-hidden":"true",onError:o=>{o.currentTarget.style.display="none"}}),e.jsxs("button",{type:"button",className:"flat-map-area-card__header",onClick:()=>ae?nn(g):rn(g),title:ae?C?`Expand ${s.area.name}`:`Collapse ${s.area.name}`:`Focus ${s.area.name} in left panel`,"aria-expanded":ae?!C:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:s.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:s.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:s.agents.length}),ae&&e.jsx(f,{name:C?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:s.agents.map(o=>{const y=o.isBoss||o.class==="boss",O=y?tt.get(o.id):void 0,I=Nn(o),w=I.usedPercent>=80?"#ff4a4a":I.usedPercent>=60?"#ff9e4a":I.usedPercent>=40?"#ffd700":"#4aff9e",A=`Context: ${(I.totalTokens/1e3).toFixed(1)}k / ${(I.contextWindow/1e3).toFixed(1)}k (${I.usedPercent}% used, ${I.freePercent}% free)`,E=o.latestTodos&&o.latestTodos.length>0||O&&O.length>0;return e.jsx(kn,{todos:o.latestTodos,subordinates:O,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${o.status}`,onClick:()=>d(o.id),onContextMenu:W=>{W.preventDefault(),W.stopPropagation(),Ne({agentId:o.id,position:{x:W.clientX,y:W.clientY}})},title:E?void 0:`${y?"Boss · ":""}Open chat with ${o.name}
2
2
  ${A}`,children:[e.jsx(Jt,{agent:o,size:16}),y&&e.jsx("span",{className:"flat-map-agent-chip__crown","aria-hidden":"true",children:e.jsx(f,{name:"crown",size:11,color:"#ffd700",weight:"fill"})}),e.jsx("span",{className:"flat-map-agent-chip__name",children:o.name}),e.jsx("img",{src:o.provider==="codex"?"/assets/codex.png":o.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:o.provider,className:"flat-map-agent-chip__provider-icon",title:o.provider==="codex"?"Codex Agent":o.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),e.jsx("span",{className:"flat-map-agent-chip__dot",style:{backgroundColor:Qt(o.status)}}),o.latestTodos&&o.latestTodos.length>0&&e.jsx(yn,{todos:o.latestTodos,maxDots:6}),y&&O&&O.length>0&&e.jsx(An,{subordinates:O,maxDots:6}),e.jsx("span",{className:"flat-map-agent-chip__context-bar","aria-hidden":"true",children:e.jsx("span",{className:"flat-map-agent-chip__context-bar-fill",style:{width:`${I.usedPercent}%`,backgroundColor:w}})})]})},o.id)})}),s.area.directories.length>0&&e.jsx("div",{className:"flat-map-area-card__folders",role:"group","aria-label":`${s.area.name} folders`,children:s.area.directories.map(o=>{const y=o.split("/").filter(Boolean).pop()||o;return e.jsxs("button",{type:"button",className:"flat-map-folder-chip",onClick:O=>{O.stopPropagation(),v.openFileExplorerForAreaFolder(g,o)},title:`Open in file explorer: ${o}`,children:[e.jsx(f,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-map-folder-chip__name",children:y})]},o)})}),s.buildings.length>0&&e.jsx("div",{className:"flat-map-area-card__buildings",children:s.buildings.map(o=>{var O;const y=(O=Sn[o.type])==null?void 0:O.color;return e.jsxs("button",{type:"button",className:`flat-map-building-chip flat-map-building-chip--${o.status}`,style:y?{"--building-type-color":y}:void 0,onClick:I=>{if(h){const w=I.currentTarget.getBoundingClientRect();h(o.id,{x:w.right,y:w.top+w.height/2})}else ee(o.id)},onContextMenu:I=>{I.preventDefault(),I.stopPropagation(),J({buildingId:o.id,position:{x:I.clientX,y:I.clientY}})},title:`${o.name} · ${o.type} · ${o.status}`,children:[e.jsx(f,{name:En(o.type),size:12,color:y}),e.jsx("span",{className:"flat-map-building-chip__name",children:o.name}),e.jsx("span",{className:"flat-map-building-chip__dot",style:{backgroundColor:Mn(o.status)}})]},o.id)})})]},g)})})()})]})})]}),c&&e.jsx("div",{className:"flat-splitter flat-splitter--inspector",role:"separator","aria-orientation":"vertical","aria-label":"Resize inspector panel",title:"Drag to resize · Double-click to reset",onPointerDown:xt,onPointerMove:Je,onPointerUp:ne,onPointerCancel:ne,onDoubleClick:Se}),Ce&&e.jsxs("aside",{className:`flat-inspector ${Fe?"flat-inspector--open":"flat-inspector--closing"}`,"aria-label":"Inspector panel",children:[e.jsxs("div",{className:"flat-inspector__header",children:[e.jsxs("div",{className:"flat-inspector__tabs",role:"tablist","aria-label":"Inspector view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":_e==="agent",className:`flat-inspector__tab ${_e==="agent"?"flat-inspector__tab--active":""}`,onClick:()=>He("agent"),children:"Agent"}),e.jsx("button",{type:"button",role:"tab","aria-selected":_e==="tracking",className:`flat-inspector__tab ${_e==="tracking"?"flat-inspector__tab--active":""}`,onClick:()=>He("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:Ue,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:_e==="tracking"?e.jsx(In,{activeAgentId:_??"",onSelectAgent:t=>{d(t),window.innerWidth<=768&&Ue()}}):(()=>{if(!_)return e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Select an agent to inspect"})});const t=b.find(n=>n.id===_);return t?e.jsx(Tn,{agent:t,onFocusAgent:n=>{d(n),window.innerWidth<=768&&Ue()},onKillAgent:n=>v.killAgent(n)}):e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Agent not found"})})})()})]}),P&&e.jsx(Pn,{url:P.url,name:P.name,onClose:()=>X(null)}),K&&e.jsx(Ln,{state:K,onClose:()=>ue(null)}),e.jsx(Dn,{agent:_?b.find(t=>t.id===_)??null:null,content:te,onClose:()=>pe(null)}),je&&e.jsx(Rn,{action:"clear-subordinates",selectedAgentId:je.agentId,subordinateCount:je.count,onClose:()=>Ye(null),onClearHistory:()=>{}}),e.jsx($n,{agent:_?b.find(t=>t.id===_)??null:null,isOpen:Re&&!!_,onClose:$e}),e.jsx(Ht,{isOpen:se!==null,position:(se==null?void 0:se.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:sn,onClose:()=>Ne(null)}),e.jsx(Ht,{isOpen:p!==null,position:(p==null?void 0:p.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:ln,onClose:()=>J(null)}),e.jsx(zn,{isOpen:me!==null,title:Z("common:confirm.removeAgentTitle"),message:Z("common:confirm.removeAgentMessage",{name:(me==null?void 0:me.name)??""}),confirmLabel:Z("common:buttons.remove"),cancelLabel:Z("common:buttons.cancel"),variant:"danger",onConfirm:()=>{me&&v.removeAgentFromServer(me.agentId)},onClose:()=>ke(null)})]})}export{ja as FlatView};