tide-commander 1.129.1 → 1.129.2

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 (38) hide show
  1. package/dist/assets/{BossLogsModal-5ymchtxj.js → BossLogsModal-BMJsPBdB.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-BckmLAJF.js → BossSpawnModal-DuDDNuE-.js} +1 -1
  3. package/dist/assets/{ControlsModal-DoYeuAi8.js → ControlsModal-Cn3pkMIT.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-Dpp5SKr4.js → DockerLogsModal-D5XQ6zSr.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-DL_C_p6W.js → EmbeddedEditor-Ct4fmYRC.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-D9hkyLrF.js → GmailOAuthSetup-Cfxh0FZm.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-C0YYRe4h.js → GoogleOAuthSetup-Z-Yv0mbQ.js} +1 -1
  8. package/dist/assets/{IframeModal-BkwZcWcy.js → IframeModal-eyoeBSzE.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-C4gviCUC.js → IntegrationsPanel-DzdEuC2w.js} +2 -2
  10. package/dist/assets/{LogViewerModal-DlJMPa8d.js → LogViewerModal-fhtTos_b.js} +1 -1
  11. package/dist/assets/{MonitoringModal-27q1Iofd.js → MonitoringModal-D_QNY_Zh.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-G8zQzzim.js → PM2LogsModal-DulkKfnA.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-DOtG6QmN.js → RestoreArchivedAreaModal-BkpEL2dc.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-C358FEi7.js → Scene2DCanvas-C5E1mERA.js} +1 -1
  15. package/dist/assets/{SceneManager-CZGgonqI.js → SceneManager-BA7KiD3q.js} +1 -1
  16. package/dist/assets/{SkillsPanel-Bf_3MqHX.js → SkillsPanel-uotqhq5s.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-BPCGoq4r.js → SlackMultiInstanceSetup-B1QA0scY.js} +1 -1
  18. package/dist/assets/{SpawnModal-C_iavTTP.js → SpawnModal-B1d-vt6c.js} +1 -1
  19. package/dist/assets/{StatisticsModal-9_DI0pXQ.js → StatisticsModal-CpMdoPSG.js} +1 -1
  20. package/dist/assets/{SubordinateAssignmentModal-B0JgGCql.js → SubordinateAssignmentModal-ALjpv2DP.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-Ceb-zgvf.js → TriggerManagerPanel-rrDTH1Oq.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-BFmvddmG.js → WorkflowEditorPanel-BcuM9e70.js} +1 -1
  23. package/dist/assets/{area-logos-Bsh88_lc.js → area-logos-BkmhbXfG.js} +1 -1
  24. package/dist/assets/{index-B-7vpOr-.js → index-BNoB11BS.js} +2 -2
  25. package/dist/assets/{index-BHe9nLqO.js → index-BiXjxgpq.js} +1 -1
  26. package/dist/assets/{index-DGsxbbzQ.js → index-BoN1bGyV.js} +1 -1
  27. package/dist/assets/{index-Bu2Ug8Tf.js → index-C9NJLW6A.js} +3 -3
  28. package/dist/assets/{index-Dt3XLrxz.js → index-CfEgfolW.js} +1 -1
  29. package/dist/assets/{index-v31fNaZP.js → index-DI7bDj0E.js} +1 -1
  30. package/dist/assets/{index-CTUEetOy.js → index-DMCGsQg5.js} +1 -1
  31. package/dist/assets/{index-B7ZqxBd2.js → index-ZQNyoovC.js} +1 -1
  32. package/dist/assets/{index-BhHUfbTC.js → index-dfuoBomr.js} +1 -1
  33. package/dist/assets/{main-ChEsMqV1.js → main-CEKV7I4r.js} +105 -105
  34. package/dist/assets/{web-lM7I_-tr.js → web-CvCmCymz.js} +1 -1
  35. package/dist/assets/{web-D9MI5O3T.js → web-DTb2MfHS.js} +1 -1
  36. package/dist/assets/{web-C7kyjQWZ.js → web-jSBoGXkW.js} +1 -1
  37. package/dist/index.html +1 -1
  38. package/package.json +1 -1
@@ -1 +1 @@
1
- import{u as J,a as Z,r,s as h,j as e,D as de,I as H,C as oe,b as me,c as be,d as ue,g as he,e as _e,Q as pe,R as xe}from"./main-ChEsMqV1.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const fe=({building:a,connections:x,activeConnectionId:l,activeDatabase:c,collapsed:y,onToggleCollapse:f,onConnectionChange:Q,onDatabaseChange:S,onInsertTable:L,onSelectTableQuery:P})=>{const{t:m}=J(["terminal"]),q=Z(a.id),[I,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,w]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?q.databases.get(l)??[]:[],G=l&&c?`${l}:${c}`:"",j=G?q.tables.get(G)??[]:[],p=l?q.connectionStatus.get(l):void 0,D=r.useMemo(()=>{if(!k.trim())return N;const t=k.toLowerCase();return N.filter(o=>o.toLowerCase().includes(t))},[N,k]),b=r.useMemo(()=>{if(!d.trim())return j;const t=d.toLowerCase();return j.filter(o=>o.name.toLowerCase().includes(t))},[j,d]);r.useEffect(()=>{const t=o=>{C.current&&!C.current.contains(o.target)&&w(!1)};return $&&document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[$]),r.useEffect(()=>{l&&!p&&h.testDatabaseConnection(a.id,l)},[a.id,l,p]),r.useEffect(()=>{l&&(p!=null&&p.connected)&&N.length===0&&h.listDatabases(a.id,l)},[a.id,l,p==null?void 0:p.connected,N.length]),r.useEffect(()=>{l&&c&&j.length===0&&h.listTables(a.id,l,c)},[a.id,l,c,j.length]),r.useEffect(()=>{F(null),g("")},[l,c]);const _=r.useCallback(t=>{R(o=>{const T=new Set(o);if(T.has(t))T.delete(t);else if(T.add(t),l&&c){const v=`${l}:${c}:${t}`;q.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,q.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return q.tableSchemas.get(o)};return y?e.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.expandSidebar"),children:"»"})}):e.jsxs("div",{className:"database-sidebar",children:[e.jsxs("div",{className:"database-sidebar__header",children:[e.jsx("span",{children:m("terminal:database.explorer")}),e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.collapseSidebar"),children:"«"})]}),e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),e.jsx("select",{className:"database-sidebar__select",value:l||"",onChange:t=>Q(t.target.value),children:x.length===0?e.jsx("option",{value:"",children:m("terminal:database.noConnections")}):x.map(t=>{var o;return e.jsxs("option",{value:t.id,children:[((o=de[t.engine])==null?void 0:o.icon)??"🗄️"," ",t.name]},t.id)})}),p&&e.jsx("div",{className:`database-sidebar__status ${p.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:p.connected?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),p.serverVersion&&e.jsxs("span",{className:"database-sidebar__version",children:["(",p.serverVersion,")"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),p.error||m("terminal:database.disconnected")]})})]}),N.length>0&&e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),e.jsxs("div",{className:"database-sidebar__searchable-select",ref:C,children:[e.jsx("input",{ref:K,className:"database-sidebar__search-input",type:"text",value:$?k:c||"",placeholder:m("terminal:database.selectDatabase"),onChange:t=>{n(t.target.value),$||w(!0)},onFocus:()=>{w(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(w(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),w(!1),n(""),(T=K.current)==null||T.blur())}}),$&&e.jsx("div",{className:"database-sidebar__dropdown",children:D.length===0?e.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):D.map(t=>e.jsx("div",{className:`database-sidebar__dropdown-item ${t===c?"database-sidebar__dropdown-item--active":""}`,onMouseDown:o=>{o.preventDefault(),S(t),w(!1),n("")},children:t},t))})]})]}),j.length>0&&e.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[e.jsx("div",{className:"database-sidebar__section-title",children:d.trim()?m("terminal:database.tablesCount",{count:b.length})+` / ${j.length}`:m("terminal:database.tablesCount",{count:j.length})}),e.jsxs("div",{className:"database-sidebar__table-filter",children:[e.jsx("input",{ref:O,className:"database-sidebar__table-filter-input",type:"text",value:d,placeholder:m("terminal:database.filterTables"),onChange:t=>g(t.target.value),onKeyDown:t=>{var o;t.key==="Escape"&&(d?g(""):(o=O.current)==null||o.blur(),t.stopPropagation())}}),d&&e.jsx("button",{className:"database-sidebar__table-filter-clear",onClick:()=>{var t;g(""),(t=O.current)==null||t.focus()},title:"Clear filter",children:"×"})]}),e.jsxs("div",{className:"database-sidebar__tables",children:[d.trim()&&b.length===0&&e.jsx("div",{className:"database-sidebar__tables-empty",children:m("terminal:database.noTablesMatch")}),b.map(t=>{const o=I.has(t.name),T=o?z(t.name):null;return e.jsxs("div",{className:"database-sidebar__table",children:[e.jsxs("div",{className:"database-sidebar__table-header",children:[e.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>_(t.name),title:o?"Collapse table schema":"Expand table schema",children:e.jsx(H,{name:o?"caret-down":"caret-right",size:10})}),e.jsx("span",{className:"database-sidebar__table-icon",children:e.jsx(H,{name:t.type==="view"?"eye":"clipboard",size:12})}),e.jsx("span",{className:`database-sidebar__table-name ${U===t.name?"database-sidebar__table-name--selected":""}`,onClick:()=>F(t.name),onDoubleClick:()=>{F(t.name),P(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),L(t.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),o&&T&&e.jsx("div",{className:"database-sidebar__table-columns",children:T.columns.map(v=>e.jsxs("div",{className:"database-sidebar__column",onClick:()=>L(v.name),title:`${v.type}${v.nullable?" NULL":" NOT NULL"}${v.primaryKey?" PK":""}`,children:[e.jsx("span",{className:"database-sidebar__column-icon",children:v.primaryKey?e.jsx(H,{name:"key",size:11}):null}),e.jsx("span",{className:"database-sidebar__column-name",children:v.name}),e.jsx("span",{className:"database-sidebar__column-type",children:v.type})]},v.name))})]},t.name)})]})]})]})},je=({buildingId:a,history:x,onLoadQuery:l})=>{const{t:c}=J(["terminal","common"]),[y,f]=r.useState(""),[Q,S]=r.useState(!1),[L,P]=r.useState(!1),m=r.useMemo(()=>{let n=x;if(Q&&(n=n.filter(d=>d.favorite)),y.trim()){const d=y.toLowerCase();n=n.filter(g=>g.query.toLowerCase().includes(d)||g.database.toLowerCase().includes(d))}return n},[x,Q,y]),q=n=>{const d=new Date(n),$=new Date().getTime()-d.getTime();return $<1440*60*1e3?d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):$<10080*60*1e3?d.toLocaleDateString([],{weekday:"short"})+" "+d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})},I=r.useCallback((n,d)=>{d.stopPropagation(),h.toggleQueryFavorite(a,n)},[a]),R=r.useCallback((n,d)=>{d.stopPropagation(),h.deleteQueryFromHistory(a,n)},[a]),k=r.useCallback(()=>{P(!0)},[]);return x.length===0?e.jsxs("div",{className:"query-history query-history--empty",children:[e.jsx("p",{children:c("terminal:database.noHistory")}),e.jsx("p",{children:c("terminal:database.queriesAppearHere")})]}):e.jsxs("div",{className:"query-history",children:[e.jsxs("div",{className:"query-history__toolbar",children:[e.jsx("input",{type:"text",className:"query-history__search",placeholder:c("terminal:database.searchQueries"),value:y,onChange:n=>f(n.target.value)}),e.jsxs("label",{className:"query-history__filter",children:[e.jsx("input",{type:"checkbox",checked:Q,onChange:n=>S(n.target.checked)}),c("terminal:database.favoritesOnly")]}),e.jsx("button",{className:"query-history__clear",onClick:k,title:c("terminal:database.clearAll"),children:c("terminal:database.clearAll")})]}),e.jsxs("div",{className:"query-history__list",children:[m.map(n=>e.jsxs("div",{className:`query-history__item ${n.status==="error"?"query-history__item--error":""}`,onClick:()=>l(n.query),children:[e.jsxs("div",{className:"query-history__item-header",children:[e.jsx("span",{className:`query-history__status ${n.status==="success"?"query-history__status--success":"query-history__status--error"}`,children:e.jsx(H,{name:n.status==="success"?"check":"cross",size:12})}),e.jsx("span",{className:"query-history__database",children:n.database}),e.jsx("span",{className:"query-history__date",children:q(n.executedAt)}),e.jsxs("span",{className:"query-history__duration",children:[n.duration,"ms"]}),n.rowCount!==void 0&&e.jsx("span",{className:"query-history__row-count",children:c("terminal:database.rowCount",{count:n.rowCount})})]}),e.jsx("div",{className:"query-history__query",children:e.jsx("code",{children:n.query.length>200?n.query.substring(0,200)+"...":n.query})}),n.error&&e.jsx("div",{className:"query-history__error",children:n.error}),e.jsxs("div",{className:"query-history__actions",children:[e.jsx("button",{className:`query-history__favorite ${n.favorite?"query-history__favorite--active":""}`,onClick:d=>I(n.id,d),title:n.favorite?c("terminal:database.removeFromFavorites"):c("terminal:database.addToFavorites"),children:e.jsx(H,{name:"star",size:12,weight:n.favorite?"fill":"regular",color:n.favorite?"#facc15":void 0})}),e.jsx("button",{className:"query-history__delete",onClick:d=>R(n.id,d),title:c("terminal:database.deleteFromHistory"),children:e.jsx(H,{name:"trash",size:12})})]})]},n.id)),m.length===0&&e.jsx("div",{className:"query-history__no-results",children:c("terminal:database.noQueriesMatch")})]}),e.jsx(oe,{isOpen:L,title:c("terminal:database.clearAll"),message:c("terminal:database.confirmClearHistory"),confirmLabel:c("terminal:database.clearAll"),cancelLabel:c("common:buttons.cancel"),variant:"danger",onConfirm:()=>h.clearQueryHistory(a),onClose:()=>P(!1)})]})},ye=({tabs:a,activeTabId:x,onTabClick:l,onTabClose:c})=>{const{t:y}=J(["terminal"]);return e.jsx("div",{className:"database-tabs",children:a.map(f=>e.jsxs("div",{className:`database-tabs__tab ${x===f.id?"database-tabs__tab--active":""}`,children:[e.jsxs("button",{className:"database-tabs__tab-label",onClick:()=>l(f),title:`${f.connectionName} / ${f.database}`,children:[f.database,e.jsx("span",{className:"database-tabs__tab-connection",children:f.connectionName})]}),e.jsx("button",{className:"database-tabs__tab-close",onClick:()=>c(f.id),title:y("terminal:database.closeTab"),"aria-label":`Close ${f.database} tab`,children:"×"})]},f.id))})},ee=a=>`db-panel-${a}`;function Ne(a){try{const x=localStorage.getItem(ee(a));return x?JSON.parse(x):{}}catch{return{}}}function ve(a,x){try{localStorage.setItem(ee(a),JSON.stringify(x))}catch{}}const ge=({building:a,onClose:x})=>{var B,W,Y,X;const{t:l}=J(["terminal","common"]),c=Z(a.id),y=me(a.id),f=be(a.id),Q=ue(a.id),S=r.useRef(Ne(a.id)),L=r.useRef(null),P=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],q=(s,i)=>`${s}:${i}`,I=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[w,U]=r.useState(!1),[F,K]=r.useState(()=>(S.current.openTabs??[]).map(i=>{var u;return{id:`${i.connectionId}:${i.database}`,connectionId:i.connectionId,connectionName:((u=m.find(A=>A.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,G]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(I(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return G(A=>{const E={...A};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((W=a.database)==null?void 0:W.activeConnectionId)??((Y=m[0])==null?void 0:Y.id),_=c.activeDatabase??S.current.database??((X=a.database)==null?void 0:X.activeDatabase),z=m.find(s=>s.id===b),t=b&&_?`${b}:${_}`:"",o=t?c.tables.get(t)??[]:[],T=r.useMemo(()=>{const s=new Map;return!b||!_||o.forEach(i=>{const u=c.tableSchemas.get(`${b}:${_}:${i.name}`);u&&s.set(i.name,{columns:u.columns})}),s},[b,_,o,c.tableSchemas]),v=r.useCallback((s,i)=>{var E;const u=q(s,i),A=((E=m.find(M=>M.id===s))==null?void 0:E.name)??s;K(M=>{if(M.some(ie=>ie.id===u))return M;const ce={id:u,connectionId:s,connectionName:A,database:i};return[...M,ce]}),O(u),p(N[u]??""),h.setActiveConnection(a.id,s),h.setActiveDatabase(a.id,i)},[a.id,m,N]),ae=r.useCallback(s=>{K(i=>i.filter(u=>u.id!==s)),C===s&&K(i=>{if(i.length>0){const u=i[0];O(u.id),p(N[u.id]??""),h.setActiveConnection(a.id,u.connectionId),h.setActiveDatabase(a.id,u.database)}else O(null),p("");return i})},[C,a.id,N]),se=r.useCallback(s=>{O(s.id),p(N[s.id]??""),h.setActiveConnection(a.id,s.connectionId),h.setActiveDatabase(a.id,s.database)},[a.id,N]);r.useEffect(()=>{if(!w&&m.length>0){const s=S.current;s.connectionId&&m.some(i=>i.id===s.connectionId)&&(h.setActiveConnection(a.id,s.connectionId),h.listDatabases(a.id,s.connectionId),s.database&&(h.setActiveDatabase(a.id,s.database),h.listTables(a.id,s.connectionId,s.database))),U(!0)}},[a.id,m,w]),r.useEffect(()=>{h.requestQueryHistory(a.id)},[a.id]),r.useEffect(()=>{const s=i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),x())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[x]),r.useEffect(()=>{w&&b&&ve(a.id,{connectionId:b,database:_,lastQuery:j,queries:N,generalQuery:"",openTabs:F.map(s=>({connectionId:s.connectionId,database:s.database})),activeTabId:C??void 0})},[a.id,b,_,j,w,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=L.current)==null?void 0:i.querySelector(".query-editor__textarea"),A=(u==null?void 0:u.selectionStart)??P.current,E=he(j,A);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);if(u.length<=1)h.executeQuery(a.id,b,_,j.trim());else{const A=b,E=_;(async()=>{for(const M of u)await h.executeQueryAndWait(a.id,A,E,M.sql)})()}}},[a.id,b,_,j,Q]),ne=r.useCallback(s=>{D(s),k("results")},[]),re=r.useCallback(s=>{h.setActiveConnection(a.id,s),h.listDatabases(a.id,s)},[a.id]),le=r.useCallback(s=>{b&&(v(b,s),h.listTables(a.id,b,s))},[a.id,b,v]),V=y[n];return m.length===0?e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:e.jsx(H,{name:"database",size:16})}),e.jsx("span",{className:"database-panel__name",children:a.name})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsx("div",{className:"database-panel__body",children:e.jsxs("div",{className:"database-panel__no-connections",children:[e.jsx("div",{className:"database-panel__no-connections-icon",children:e.jsx(H,{name:"plug",size:32})}),e.jsx("h3",{children:l("terminal:database.noConnections")}),e.jsx("p",{children:l("terminal:database.noConnectionsDesc")}),e.jsx("p",{children:l("terminal:database.toGetStarted")}),e.jsxs("ol",{children:[e.jsx("li",{children:l("terminal:database.step1Close")}),e.jsx("li",{children:l("terminal:database.step2Settings")}),e.jsx("li",{children:l("terminal:database.step3AddConnection")}),e.jsx("li",{children:l("terminal:database.step4Reopen")})]})]})})]}):e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:(z==null?void 0:z.engine)==="mysql"?"🐬":"🐘"}),e.jsx("span",{className:"database-panel__name",children:a.name}),z&&e.jsxs("span",{className:"database-panel__connection-info",children:[z.name," / ",_||l("terminal:database.noDatabaseSelected")]})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsxs("div",{className:"database-panel__body",children:[e.jsx(fe,{building:a,connections:m,activeConnectionId:b,activeDatabase:_,collapsed:g,onToggleCollapse:()=>$(!g),onConnectionChange:re,onDatabaseChange:le,onInsertTable:s=>D(i=>i+` ${s}`),onSelectTableQuery:s=>{const i=`SELECT * FROM ${s}`;D(i),b&&_&&h.executeQuery(a.id,b,_,i)}}),e.jsxs("div",{className:"database-panel__main",children:[F.length>0&&e.jsx(ye,{tabs:F,activeTabId:C,onTabClick:se,onTabClose:ae}),e.jsx(pe,{query:j,onChange:D,onExecute:te,isExecuting:Q,disabled:!b||!_,tables:o,tableSchemas:T,onRequestTableSchema:s=>{b&&_&&h.getTableSchema(a.id,b,_,s)}}),e.jsxs("div",{className:"database-panel__tabs",children:[e.jsxs("button",{className:`database-panel__tab ${R==="results"?"database-panel__tab--active":""}`,onClick:()=>k("results"),children:[l("terminal:database.results"),y.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:y.length})]}),e.jsxs("button",{className:`database-panel__tab ${R==="history"?"database-panel__tab--active":""}`,onClick:()=>k("history"),children:[l("terminal:database.history"),f.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:f.length})]}),R==="results"&&y.length>1&&e.jsxs("div",{className:"database-panel__result-nav",children:[e.jsxs("button",{disabled:n>=y.length-1,onClick:()=>d(s=>s+1),children:["← ",l("terminal:database.older")]}),e.jsxs("span",{children:[n+1," / ",y.length]}),e.jsxs("button",{disabled:n<=0,onClick:()=>d(s=>s-1),children:[l("terminal:database.newer")," →"]})]})]}),e.jsx("div",{className:"database-panel__tab-content",children:R==="results"?V?e.jsx(xe,{result:V,buildingId:a.id,building:a}):e.jsxs("div",{className:"database-panel__empty",children:[e.jsx("p",{children:l("terminal:database.noResultsYet")}),e.jsx("p",{children:l("terminal:database.selectDbAndRun")})]}):e.jsx(je,{buildingId:a.id,history:f,onLoadQuery:ne})})]})]})]})};export{ge as DatabasePanel,fe as DatabaseSidebar,ye as DatabaseTabs,pe as QueryEditor,je as QueryHistoryPanel,xe as ResultsTable};
1
+ import{u as J,a as Z,r,s as h,j as e,D as de,I as H,C as oe,b as me,c as be,d as ue,g as he,e as _e,Q as pe,R as xe}from"./main-CEKV7I4r.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const fe=({building:a,connections:x,activeConnectionId:l,activeDatabase:c,collapsed:y,onToggleCollapse:f,onConnectionChange:Q,onDatabaseChange:S,onInsertTable:L,onSelectTableQuery:P})=>{const{t:m}=J(["terminal"]),q=Z(a.id),[I,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,w]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?q.databases.get(l)??[]:[],G=l&&c?`${l}:${c}`:"",j=G?q.tables.get(G)??[]:[],p=l?q.connectionStatus.get(l):void 0,D=r.useMemo(()=>{if(!k.trim())return N;const t=k.toLowerCase();return N.filter(o=>o.toLowerCase().includes(t))},[N,k]),b=r.useMemo(()=>{if(!d.trim())return j;const t=d.toLowerCase();return j.filter(o=>o.name.toLowerCase().includes(t))},[j,d]);r.useEffect(()=>{const t=o=>{C.current&&!C.current.contains(o.target)&&w(!1)};return $&&document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[$]),r.useEffect(()=>{l&&!p&&h.testDatabaseConnection(a.id,l)},[a.id,l,p]),r.useEffect(()=>{l&&(p!=null&&p.connected)&&N.length===0&&h.listDatabases(a.id,l)},[a.id,l,p==null?void 0:p.connected,N.length]),r.useEffect(()=>{l&&c&&j.length===0&&h.listTables(a.id,l,c)},[a.id,l,c,j.length]),r.useEffect(()=>{F(null),g("")},[l,c]);const _=r.useCallback(t=>{R(o=>{const T=new Set(o);if(T.has(t))T.delete(t);else if(T.add(t),l&&c){const v=`${l}:${c}:${t}`;q.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,q.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return q.tableSchemas.get(o)};return y?e.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.expandSidebar"),children:"»"})}):e.jsxs("div",{className:"database-sidebar",children:[e.jsxs("div",{className:"database-sidebar__header",children:[e.jsx("span",{children:m("terminal:database.explorer")}),e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.collapseSidebar"),children:"«"})]}),e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),e.jsx("select",{className:"database-sidebar__select",value:l||"",onChange:t=>Q(t.target.value),children:x.length===0?e.jsx("option",{value:"",children:m("terminal:database.noConnections")}):x.map(t=>{var o;return e.jsxs("option",{value:t.id,children:[((o=de[t.engine])==null?void 0:o.icon)??"🗄️"," ",t.name]},t.id)})}),p&&e.jsx("div",{className:`database-sidebar__status ${p.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:p.connected?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),p.serverVersion&&e.jsxs("span",{className:"database-sidebar__version",children:["(",p.serverVersion,")"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),p.error||m("terminal:database.disconnected")]})})]}),N.length>0&&e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),e.jsxs("div",{className:"database-sidebar__searchable-select",ref:C,children:[e.jsx("input",{ref:K,className:"database-sidebar__search-input",type:"text",value:$?k:c||"",placeholder:m("terminal:database.selectDatabase"),onChange:t=>{n(t.target.value),$||w(!0)},onFocus:()=>{w(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(w(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),w(!1),n(""),(T=K.current)==null||T.blur())}}),$&&e.jsx("div",{className:"database-sidebar__dropdown",children:D.length===0?e.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):D.map(t=>e.jsx("div",{className:`database-sidebar__dropdown-item ${t===c?"database-sidebar__dropdown-item--active":""}`,onMouseDown:o=>{o.preventDefault(),S(t),w(!1),n("")},children:t},t))})]})]}),j.length>0&&e.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[e.jsx("div",{className:"database-sidebar__section-title",children:d.trim()?m("terminal:database.tablesCount",{count:b.length})+` / ${j.length}`:m("terminal:database.tablesCount",{count:j.length})}),e.jsxs("div",{className:"database-sidebar__table-filter",children:[e.jsx("input",{ref:O,className:"database-sidebar__table-filter-input",type:"text",value:d,placeholder:m("terminal:database.filterTables"),onChange:t=>g(t.target.value),onKeyDown:t=>{var o;t.key==="Escape"&&(d?g(""):(o=O.current)==null||o.blur(),t.stopPropagation())}}),d&&e.jsx("button",{className:"database-sidebar__table-filter-clear",onClick:()=>{var t;g(""),(t=O.current)==null||t.focus()},title:"Clear filter",children:"×"})]}),e.jsxs("div",{className:"database-sidebar__tables",children:[d.trim()&&b.length===0&&e.jsx("div",{className:"database-sidebar__tables-empty",children:m("terminal:database.noTablesMatch")}),b.map(t=>{const o=I.has(t.name),T=o?z(t.name):null;return e.jsxs("div",{className:"database-sidebar__table",children:[e.jsxs("div",{className:"database-sidebar__table-header",children:[e.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>_(t.name),title:o?"Collapse table schema":"Expand table schema",children:e.jsx(H,{name:o?"caret-down":"caret-right",size:10})}),e.jsx("span",{className:"database-sidebar__table-icon",children:e.jsx(H,{name:t.type==="view"?"eye":"clipboard",size:12})}),e.jsx("span",{className:`database-sidebar__table-name ${U===t.name?"database-sidebar__table-name--selected":""}`,onClick:()=>F(t.name),onDoubleClick:()=>{F(t.name),P(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),L(t.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),o&&T&&e.jsx("div",{className:"database-sidebar__table-columns",children:T.columns.map(v=>e.jsxs("div",{className:"database-sidebar__column",onClick:()=>L(v.name),title:`${v.type}${v.nullable?" NULL":" NOT NULL"}${v.primaryKey?" PK":""}`,children:[e.jsx("span",{className:"database-sidebar__column-icon",children:v.primaryKey?e.jsx(H,{name:"key",size:11}):null}),e.jsx("span",{className:"database-sidebar__column-name",children:v.name}),e.jsx("span",{className:"database-sidebar__column-type",children:v.type})]},v.name))})]},t.name)})]})]})]})},je=({buildingId:a,history:x,onLoadQuery:l})=>{const{t:c}=J(["terminal","common"]),[y,f]=r.useState(""),[Q,S]=r.useState(!1),[L,P]=r.useState(!1),m=r.useMemo(()=>{let n=x;if(Q&&(n=n.filter(d=>d.favorite)),y.trim()){const d=y.toLowerCase();n=n.filter(g=>g.query.toLowerCase().includes(d)||g.database.toLowerCase().includes(d))}return n},[x,Q,y]),q=n=>{const d=new Date(n),$=new Date().getTime()-d.getTime();return $<1440*60*1e3?d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):$<10080*60*1e3?d.toLocaleDateString([],{weekday:"short"})+" "+d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})},I=r.useCallback((n,d)=>{d.stopPropagation(),h.toggleQueryFavorite(a,n)},[a]),R=r.useCallback((n,d)=>{d.stopPropagation(),h.deleteQueryFromHistory(a,n)},[a]),k=r.useCallback(()=>{P(!0)},[]);return x.length===0?e.jsxs("div",{className:"query-history query-history--empty",children:[e.jsx("p",{children:c("terminal:database.noHistory")}),e.jsx("p",{children:c("terminal:database.queriesAppearHere")})]}):e.jsxs("div",{className:"query-history",children:[e.jsxs("div",{className:"query-history__toolbar",children:[e.jsx("input",{type:"text",className:"query-history__search",placeholder:c("terminal:database.searchQueries"),value:y,onChange:n=>f(n.target.value)}),e.jsxs("label",{className:"query-history__filter",children:[e.jsx("input",{type:"checkbox",checked:Q,onChange:n=>S(n.target.checked)}),c("terminal:database.favoritesOnly")]}),e.jsx("button",{className:"query-history__clear",onClick:k,title:c("terminal:database.clearAll"),children:c("terminal:database.clearAll")})]}),e.jsxs("div",{className:"query-history__list",children:[m.map(n=>e.jsxs("div",{className:`query-history__item ${n.status==="error"?"query-history__item--error":""}`,onClick:()=>l(n.query),children:[e.jsxs("div",{className:"query-history__item-header",children:[e.jsx("span",{className:`query-history__status ${n.status==="success"?"query-history__status--success":"query-history__status--error"}`,children:e.jsx(H,{name:n.status==="success"?"check":"cross",size:12})}),e.jsx("span",{className:"query-history__database",children:n.database}),e.jsx("span",{className:"query-history__date",children:q(n.executedAt)}),e.jsxs("span",{className:"query-history__duration",children:[n.duration,"ms"]}),n.rowCount!==void 0&&e.jsx("span",{className:"query-history__row-count",children:c("terminal:database.rowCount",{count:n.rowCount})})]}),e.jsx("div",{className:"query-history__query",children:e.jsx("code",{children:n.query.length>200?n.query.substring(0,200)+"...":n.query})}),n.error&&e.jsx("div",{className:"query-history__error",children:n.error}),e.jsxs("div",{className:"query-history__actions",children:[e.jsx("button",{className:`query-history__favorite ${n.favorite?"query-history__favorite--active":""}`,onClick:d=>I(n.id,d),title:n.favorite?c("terminal:database.removeFromFavorites"):c("terminal:database.addToFavorites"),children:e.jsx(H,{name:"star",size:12,weight:n.favorite?"fill":"regular",color:n.favorite?"#facc15":void 0})}),e.jsx("button",{className:"query-history__delete",onClick:d=>R(n.id,d),title:c("terminal:database.deleteFromHistory"),children:e.jsx(H,{name:"trash",size:12})})]})]},n.id)),m.length===0&&e.jsx("div",{className:"query-history__no-results",children:c("terminal:database.noQueriesMatch")})]}),e.jsx(oe,{isOpen:L,title:c("terminal:database.clearAll"),message:c("terminal:database.confirmClearHistory"),confirmLabel:c("terminal:database.clearAll"),cancelLabel:c("common:buttons.cancel"),variant:"danger",onConfirm:()=>h.clearQueryHistory(a),onClose:()=>P(!1)})]})},ye=({tabs:a,activeTabId:x,onTabClick:l,onTabClose:c})=>{const{t:y}=J(["terminal"]);return e.jsx("div",{className:"database-tabs",children:a.map(f=>e.jsxs("div",{className:`database-tabs__tab ${x===f.id?"database-tabs__tab--active":""}`,children:[e.jsxs("button",{className:"database-tabs__tab-label",onClick:()=>l(f),title:`${f.connectionName} / ${f.database}`,children:[f.database,e.jsx("span",{className:"database-tabs__tab-connection",children:f.connectionName})]}),e.jsx("button",{className:"database-tabs__tab-close",onClick:()=>c(f.id),title:y("terminal:database.closeTab"),"aria-label":`Close ${f.database} tab`,children:"×"})]},f.id))})},ee=a=>`db-panel-${a}`;function Ne(a){try{const x=localStorage.getItem(ee(a));return x?JSON.parse(x):{}}catch{return{}}}function ve(a,x){try{localStorage.setItem(ee(a),JSON.stringify(x))}catch{}}const ge=({building:a,onClose:x})=>{var B,W,Y,X;const{t:l}=J(["terminal","common"]),c=Z(a.id),y=me(a.id),f=be(a.id),Q=ue(a.id),S=r.useRef(Ne(a.id)),L=r.useRef(null),P=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],q=(s,i)=>`${s}:${i}`,I=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[w,U]=r.useState(!1),[F,K]=r.useState(()=>(S.current.openTabs??[]).map(i=>{var u;return{id:`${i.connectionId}:${i.database}`,connectionId:i.connectionId,connectionName:((u=m.find(A=>A.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,G]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(I(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return G(A=>{const E={...A};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((W=a.database)==null?void 0:W.activeConnectionId)??((Y=m[0])==null?void 0:Y.id),_=c.activeDatabase??S.current.database??((X=a.database)==null?void 0:X.activeDatabase),z=m.find(s=>s.id===b),t=b&&_?`${b}:${_}`:"",o=t?c.tables.get(t)??[]:[],T=r.useMemo(()=>{const s=new Map;return!b||!_||o.forEach(i=>{const u=c.tableSchemas.get(`${b}:${_}:${i.name}`);u&&s.set(i.name,{columns:u.columns})}),s},[b,_,o,c.tableSchemas]),v=r.useCallback((s,i)=>{var E;const u=q(s,i),A=((E=m.find(M=>M.id===s))==null?void 0:E.name)??s;K(M=>{if(M.some(ie=>ie.id===u))return M;const ce={id:u,connectionId:s,connectionName:A,database:i};return[...M,ce]}),O(u),p(N[u]??""),h.setActiveConnection(a.id,s),h.setActiveDatabase(a.id,i)},[a.id,m,N]),ae=r.useCallback(s=>{K(i=>i.filter(u=>u.id!==s)),C===s&&K(i=>{if(i.length>0){const u=i[0];O(u.id),p(N[u.id]??""),h.setActiveConnection(a.id,u.connectionId),h.setActiveDatabase(a.id,u.database)}else O(null),p("");return i})},[C,a.id,N]),se=r.useCallback(s=>{O(s.id),p(N[s.id]??""),h.setActiveConnection(a.id,s.connectionId),h.setActiveDatabase(a.id,s.database)},[a.id,N]);r.useEffect(()=>{if(!w&&m.length>0){const s=S.current;s.connectionId&&m.some(i=>i.id===s.connectionId)&&(h.setActiveConnection(a.id,s.connectionId),h.listDatabases(a.id,s.connectionId),s.database&&(h.setActiveDatabase(a.id,s.database),h.listTables(a.id,s.connectionId,s.database))),U(!0)}},[a.id,m,w]),r.useEffect(()=>{h.requestQueryHistory(a.id)},[a.id]),r.useEffect(()=>{const s=i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),x())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[x]),r.useEffect(()=>{w&&b&&ve(a.id,{connectionId:b,database:_,lastQuery:j,queries:N,generalQuery:"",openTabs:F.map(s=>({connectionId:s.connectionId,database:s.database})),activeTabId:C??void 0})},[a.id,b,_,j,w,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=L.current)==null?void 0:i.querySelector(".query-editor__textarea"),A=(u==null?void 0:u.selectionStart)??P.current,E=he(j,A);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);if(u.length<=1)h.executeQuery(a.id,b,_,j.trim());else{const A=b,E=_;(async()=>{for(const M of u)await h.executeQueryAndWait(a.id,A,E,M.sql)})()}}},[a.id,b,_,j,Q]),ne=r.useCallback(s=>{D(s),k("results")},[]),re=r.useCallback(s=>{h.setActiveConnection(a.id,s),h.listDatabases(a.id,s)},[a.id]),le=r.useCallback(s=>{b&&(v(b,s),h.listTables(a.id,b,s))},[a.id,b,v]),V=y[n];return m.length===0?e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:e.jsx(H,{name:"database",size:16})}),e.jsx("span",{className:"database-panel__name",children:a.name})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsx("div",{className:"database-panel__body",children:e.jsxs("div",{className:"database-panel__no-connections",children:[e.jsx("div",{className:"database-panel__no-connections-icon",children:e.jsx(H,{name:"plug",size:32})}),e.jsx("h3",{children:l("terminal:database.noConnections")}),e.jsx("p",{children:l("terminal:database.noConnectionsDesc")}),e.jsx("p",{children:l("terminal:database.toGetStarted")}),e.jsxs("ol",{children:[e.jsx("li",{children:l("terminal:database.step1Close")}),e.jsx("li",{children:l("terminal:database.step2Settings")}),e.jsx("li",{children:l("terminal:database.step3AddConnection")}),e.jsx("li",{children:l("terminal:database.step4Reopen")})]})]})})]}):e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:(z==null?void 0:z.engine)==="mysql"?"🐬":"🐘"}),e.jsx("span",{className:"database-panel__name",children:a.name}),z&&e.jsxs("span",{className:"database-panel__connection-info",children:[z.name," / ",_||l("terminal:database.noDatabaseSelected")]})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsxs("div",{className:"database-panel__body",children:[e.jsx(fe,{building:a,connections:m,activeConnectionId:b,activeDatabase:_,collapsed:g,onToggleCollapse:()=>$(!g),onConnectionChange:re,onDatabaseChange:le,onInsertTable:s=>D(i=>i+` ${s}`),onSelectTableQuery:s=>{const i=`SELECT * FROM ${s}`;D(i),b&&_&&h.executeQuery(a.id,b,_,i)}}),e.jsxs("div",{className:"database-panel__main",children:[F.length>0&&e.jsx(ye,{tabs:F,activeTabId:C,onTabClick:se,onTabClose:ae}),e.jsx(pe,{query:j,onChange:D,onExecute:te,isExecuting:Q,disabled:!b||!_,tables:o,tableSchemas:T,onRequestTableSchema:s=>{b&&_&&h.getTableSchema(a.id,b,_,s)}}),e.jsxs("div",{className:"database-panel__tabs",children:[e.jsxs("button",{className:`database-panel__tab ${R==="results"?"database-panel__tab--active":""}`,onClick:()=>k("results"),children:[l("terminal:database.results"),y.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:y.length})]}),e.jsxs("button",{className:`database-panel__tab ${R==="history"?"database-panel__tab--active":""}`,onClick:()=>k("history"),children:[l("terminal:database.history"),f.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:f.length})]}),R==="results"&&y.length>1&&e.jsxs("div",{className:"database-panel__result-nav",children:[e.jsxs("button",{disabled:n>=y.length-1,onClick:()=>d(s=>s+1),children:["← ",l("terminal:database.older")]}),e.jsxs("span",{children:[n+1," / ",y.length]}),e.jsxs("button",{disabled:n<=0,onClick:()=>d(s=>s-1),children:[l("terminal:database.newer")," →"]})]})]}),e.jsx("div",{className:"database-panel__tab-content",children:R==="results"?V?e.jsx(xe,{result:V,buildingId:a.id,building:a}):e.jsxs("div",{className:"database-panel__empty",children:[e.jsx("p",{children:l("terminal:database.noResultsYet")}),e.jsx("p",{children:l("terminal:database.selectDbAndRun")})]}):e.jsx(je,{buildingId:a.id,history:f,onLoadQuery:ne})})]})]})]})};export{ge as DatabasePanel,fe as DatabaseSidebar,ye as DatabaseTabs,pe as QueryEditor,je as QueryHistoryPanel,xe as ResultsTable};
@@ -1,2 +1,2 @@
1
- import{r as a,B as pn,E as zt,G as qt,H as Yt,j as e,J as Kt,K as mn,u as Lt,L as fn,M as hn,N as gn,O as xn,V as bn,P as _n,U as wn,W as Ot,S,X as Bt,Y as Pt,Z as Ft,_ as mt,$ as oe,a0 as vn,s as _,a1 as Zt,a2 as Jt,a3 as Cn,w as Wt,x as Ht,I as p,a4 as jn,n as Nn,a5 as kn,a6 as Qt,a7 as en,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 Ut,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,aC as na,aD as aa}from"./main-ChEsMqV1.js";import{g as sa}from"./area-logos-Bsh88_lc.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function ia(u){const r=a.useRef(u);r.current=u,a.useEffect(()=>{if(!pn())return;let f=null,h=!1;return zt.addListener("backButton",()=>{r.current()==="exit"&&zt.exitApp()}).then(N=>{h?N.remove():f=N}),()=>{h=!0,f&&(f.remove(),f=null)}},[])}async function la(u){const r=qt(),f=await fetch(`${Yt()}/api/agents/${u}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!f.ok){const h=await f.json().catch(()=>({}));throw new Error((h==null?void 0:h.error)||`Failed to start terminal (${f.status})`)}return f.json()}async function ra(u){const r=qt();await fetch(`${Yt()}/api/agents/${u}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}const Ze=new Map;function oa({agentId:u}){const[r,f]=a.useState(null),[h,N]=a.useState(null);return a.useEffect(()=>{let L=!1;const M=Ze.get(u);return M&&(clearTimeout(M),Ze.delete(u)),f(null),N(null),la(u).then(R=>{L||f(R.url)}).catch(R=>{L||N(R instanceof Error?R.message:"Failed to start terminal")}),()=>{L=!0;const R=Ze.get(u);R&&clearTimeout(R),Ze.set(u,setTimeout(()=>{Ze.delete(u),ra(u)},2500))}},[u]),h?e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:h})}):r?e.jsx("div",{className:"flat-classic-terminal",children:e.jsx(Kt,{terminalUrl:r,visible:!0})}):e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:"Attaching to interactive session…"})})}const It=new Map,ca=6e4;function da({agentId:u,contextSummary:r}){const{t:f}=Lt(["terminal","common"]),[h,N]=a.useState(()=>{var I;return((I=It.get(u))==null?void 0:I.snapshot)??null}),[L,M]=a.useState(!1),[R,Z]=a.useState(null),w=a.useRef(0);a.useEffect(()=>{const I=It.get(u);if(I&&Date.now()-I.fetchedAt<ca){N(I.snapshot);return}const V=++w.current;M(!0),Z(null),fn(u).then(Y=>{V===w.current&&(It.set(u,{snapshot:Y,fetchedAt:Date.now()}),N(Y),M(!1))}).catch(Y=>{V===w.current&&(Z(Y.message||"Failed to load plan limits"),M(!1))})},[u]);const U=[];if(h!=null&&h.rateLimits){const I=[{key:"fiveHour",label:f("terminal:usage.currentSession"),window:h.rateLimits.fiveHour},{key:"sevenDay",label:f("terminal:usage.currentWeekAll"),window:h.rateLimits.sevenDay},{key:"sevenDayOpus",label:f("terminal:usage.currentWeekOpus"),window:h.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:f("terminal:usage.currentWeekSonnet"),window:h.rateLimits.sevenDaySonnet}];for(const V of I)V.window&&U.push({...V,window:V.window})}return e.jsxs("div",{className:"plan-limits-tooltip",children:[r&&e.jsx("div",{className:"plan-limits-tooltip__context",children:r}),e.jsx("div",{className:"plan-limits-tooltip__title",children:f("terminal:usage.limits")}),L&&!h&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[f("common:status.loading"),"…"]}),!L&&R&&!h&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:f("terminal:usage.limitsError",{message:R})}),U.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:U.map(({key:I,label:V,window:Y})=>{const ce=Math.max(0,Math.min(100,Y.utilization)),te=gn(ce);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:V}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:te},children:f("terminal:usage.percentUsed",{percent:Math.round(ce)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${ce}%`,background:te}})}),e.jsx("div",{className:"plan-limits-tooltip__reset",children:f("terminal:usage.resets",{time:hn(Y.resetsAt)})})]},I)})}):h&&!L&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:h.rateLimitsError?f("terminal:usage.limitsError",{message:h.rateLimitsError}):h.cliHint})]})}function ua({agentId:u,disabled:r,contextSummary:f,children:h}){return e.jsx(mn,{position:"top",maxWidth:320,disabled:r,className:"plan-limits-tooltip-wrapper",triggerStyle:{display:"inline-flex",alignItems:"center"},content:e.jsx(da,{agentId:u,contextSummary:f}),children:h})}const pa=a.memo(function({className:r=""}){const{t:f}=Lt(["common"]),[h,N]=xn(),L=a.useRef(null),[M,R]=a.useState(null);a.useLayoutEffect(()=>{const w=L.current;if(!w)return;const U=w.querySelector(".view-mode-toggle__btn--active");U&&R({left:U.offsetLeft,width:U.offsetWidth})},[h]);const Z=a.useCallback(w=>{if(w!==h){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:w}})),w==="3d"){requestAnimationFrame(()=>N(w));return}N(w)}},[h,N]);return e.jsxs("div",{className:`view-mode-toggle ${r}`,ref:L,children:[M&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:M.left,width:M.width}}),bn.map(w=>e.jsxs("button",{className:`view-mode-toggle__btn ${h===w?"view-mode-toggle__btn--active":""}`,onClick:()=>Z(w),title:f(`common:viewMode.descriptions.${w}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[w==="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"})]}),w==="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"})]}),w==="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"})]}),w==="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:f(`common:viewMode.labels.${w}`)})]},w))]})}),ft=3,ht=280,Vt=320,Tt=240,Xt=64,ma=["simple","chat","advanced"],fa={simple:"Simple",chat:"Chat",advanced:"Advanced"},ha={simple:"○",chat:"◐",advanced:"◉"},ga={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Gt="flat-clear-context";function xa(u){const r=u.split("/").filter(Boolean);return r.length===0?u:r.slice(-2).join("/")}function ba(u){if(u.provider==="codex"){const L=u.codexModel||"gpt-5.3-codex",M=ta[L];return{model:(M==null?void 0:M.label)||L}}if(u.provider==="opencode")return{model:u.opencodeModel||"opencode"};const r=u.model||"sonnet",f=aa[r],h=u.effort,N=h?na[h]:void 0;return{model:(f==null?void 0:f.label)||r,effort:N==null?void 0:N.label}}function _a(u,r){if(r.type==="rectangle"&&r.width&&r.height){const f=r.width/2,h=r.height/2;return u.x>=r.center.x-f&&u.x<=r.center.x+f&&u.z>=r.center.z-h&&u.z<=r.center.z+h}if(r.type==="circle"&&r.radius){const f=u.x-r.center.x,h=u.z-r.center.z;return f*f+h*h<=r.radius*r.radius}return!1}const wa=On.memo(function({agentId:r,terminalViewMode:f,onTerminalViewModeChange:h,inspectorOpen:N,onToggleInspector:L,onImageClick:M,onFileClick:R,onBashClick:Z,onViewMarkdown:w,onRequestClearSubordinates:U,onOpenBuilding:I,keyboard:V,canNavigateBack:Y,canNavigateForward:ce,onNavigateBack:te,onNavigateForward:de,agentInfoOpen:we,onToggleAgentInfo:Je,onHeaderContextMenu:se,onBuildingContextMenu:ue}){var Ve,Ye,it,lt;const m=Bn(r),X=Jt(),pe=Fn(),ve=a.useRef(null),Le=a.useRef(null),me=!!pe.interactiveMode&&((m==null?void 0:m.provider)??"claude")==="claude"&&!!(m!=null&&m.sessionId),[ie,De]=a.useState(!1);a.useEffect(()=>{De(!1)},[r]),a.useEffect(()=>{!me&&ie&&De(!1)},[me,ie]),a.useEffect(()=>{const s=Le.current;if(!s)return;const l=d=>{d.button===3?(d.preventDefault(),d.stopPropagation(),te()):d.button===4&&(d.preventDefault(),d.stopPropagation(),de())},c=d=>{(d.button===3||d.button===4)&&d.preventDefault()};return s.addEventListener("mouseup",l),s.addEventListener("mousedown",c),()=>{s.removeEventListener("mouseup",l),s.removeEventListener("mousedown",c)}},[te,de]),a.useEffect(()=>{const s=Le.current;if(!s)return;let l=0,c=0,d=0;const _e=250,Ee=600,Me=80,yt=1.5,rt=T=>{let z=T instanceof HTMLElement?T:null;for(;z&&z!==s;){const Ie=window.getComputedStyle(z).overflowX;if((Ie==="auto"||Ie==="scroll")&&z.scrollWidth>z.clientWidth)return!0;z=z.parentElement}return!1},ot=T=>{const z=Date.now();if(z<d){T.preventDefault();return}if(Math.abs(T.deltaX)<=Math.abs(T.deltaY)*yt){l=0;return}if(rt(T.target)){l=0;return}z-c>_e&&(l=0),c=z,l+=T.deltaX,l<=-Me?(l=0,d=z+Ee,T.preventDefault(),te()):l>=Me&&(l=0,d=z+Ee,T.preventDefault(),de())};return s.addEventListener("wheel",ot,{passive:!1}),()=>s.removeEventListener("wheel",ot)},[te,de]);const Xe=Zt(),Re=a.useMemo(()=>{if(!m)return null;const s=new Set,l=[];for(const c of Xe.values())c.archived||c.directories.length===0||c.assignedAgentIds.includes(r)&&(s.add(c.id),l.push(c));for(const c of Xe.values())c.archived||c.directories.length===0||s.has(c.id)||_a({x:m.position.x,z:m.position.z},c)&&(s.add(c.id),l.push(c));return l.length===0?null:l.flatMap(c=>c.directories.filter(d=>d&&d.trim().length>0).map(d=>({areaId:c.id,areaName:c.name,dir:d})))},[m,r,Xe]),{branches:Qe,fetchRemote:Ce,fetchingDirs:fe}=Wn(Re),J=a.useMemo(()=>{var c;const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of X.values())d.type==="terminal"&&_.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name,hasUrl:!!((c=d.terminalStatus)!=null&&c.url)});return l},[r,X]),le=a.useMemo(()=>{var c;const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of X.values())d.type==="server"&&((c=d.pm2)!=null&&c.enabled)&&_.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name});return l},[r,X]),et=a.useMemo(()=>{const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of X.values())c.type==="database"&&c.database&&_.isPositionInArea(c.position,s)&&l.push({id:c.id,name:c.name});return l},[r,X]),tt=Hn(),je=a.useMemo(()=>{const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of X.values())if(c.type==="tests"&&_.isPositionInArea(c.position,s)){const d=!!c.folderPath&&tt.some(_e=>Un(_e,c.folderPath));l.push({id:c.id,name:c.name,working:d})}return l},[r,X,tt]),[,Ne]=a.useReducer(s=>s+1,0),ne=((Ve=ve.current)==null?void 0:Ve.search.searchMode)??!1,$e=a.useCallback(()=>{var s;(s=ve.current)==null||s.search.toggleSearch(),Ne()},[]),Q=Vn(),he=Q.isPending(Gt),[G,ee]=a.useState(null),ge=G?X.get(G):null,{height:gt,onResizeStart:nt}=Xn(),{sidePanelWidth:ze,handleSidePanelResizeStart:xt}=Gn(),[ke,xe]=a.useState(()=>Pt(S.GIT_PANEL_OPEN,!1)),[ye,Ge]=a.useState(()=>Pt(S.BUILDINGS_PANEL_OPEN,!1)),[Ae,Oe]=a.useState(!1),bt=a.useCallback(()=>{Oe(s=>{const l=!s;return l&&qn.setEnabled(!0),l})},[]),_t=a.useCallback(()=>Oe(!1),[]),wt=a.useCallback(()=>{xe(s=>{const l=!s;return oe(S.GIT_PANEL_OPEN,l),l})},[]),vt=a.useCallback(()=>{Ge(s=>{const l=!s;return oe(S.BUILDINGS_PANEL_OPEN,l),l})},[]),Ct=a.useCallback(()=>{xe(!1),oe(S.GIT_PANEL_OPEN,!1)},[]),jt=a.useCallback(()=>{Ge(!1),oe(S.BUILDINGS_PANEL_OPEN,!1)},[]),Be=Yn();a.useEffect(()=>{if(!G)return;J.some(l=>l.id===G)||ee(null)},[G,J]);const[b,B]=a.useState(!1),q=a.useRef(null);if(a.useEffect(()=>{if(!b)return;const s=l=>{q.current&&!q.current.contains(l.target)&&B(!1)};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[b]),!m)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 K=m.contextStats,Fe=!!K,at=K?K.totalTokens:m.contextUsed||0,st=K?K.contextWindow:m.contextLimit||2e5,Nt=K?K.usedPercent:Math.round(at/st*100),be=Math.max(0,Math.min(100,Nt)),We=Math.round(be*10)/10,Se=Math.round((100-be)*10)/10,He=be>=80?"#ff4a4a":be>=60?"#ff9e4a":be>=40?"#ffd700":"#4aff9e",ae=(at/1e3).toFixed(1),qe=(st/1e3).toFixed(1),D=m.cwd,re=D?xa(D):null,Ue=((Ye=m.subordinateIds)==null?void 0:Ye.length)||0,kt=Ue>0;return e.jsxs("div",{ref:Le,className:`flat-terminal-wrapper ${ke||ye||Ae?"flat-terminal-wrapper--with-side-panel":""}`,style:{"--guake-side-panel-width":`min(${ze}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${we?"flat-terminal-wrapper__header-main--active":""}`,onClick:Je,onContextMenu:s=>{s.preventDefault(),s.stopPropagation(),se({x:s.clientX,y:s.clientY})},title:we?"Hide agent info":"Show agent info","aria-pressed":we,children:[e.jsx(Qt,{agent:m,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:m.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:en(m.status)},children:m.status})]}),m.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:m.taskLabel,children:["📋 ",m.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:m.provider==="codex"?"/assets/codex.png":m.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:m.provider,className:"flat-terminal-wrapper__header-provider-icon",title:m.provider==="codex"?"Codex Agent":m.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:s,effort:l}=ba(m);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:l?`Model: ${s} · Effort: ${l}`:`Model: ${s}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:s}),l&&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:l})]})]})})()]})]}),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:[ma.map(s=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${!ie&&f===s?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{De(!1),h(s)},title:ga[s],"aria-pressed":!ie&&f===s,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:ha[s]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:fa[s]})]},s)),me&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${ie?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>De(s=>!s),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(p,{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:!Y,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(p,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:de,disabled:!ce,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(p,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ne?"flat-terminal-wrapper__action-btn--active":""}`,onClick:$e,title:ne?"Close search":"Search messages","aria-pressed":ne,children:e.jsx(p,{name:ne?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${he?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>Q.handleClick(Gt,()=>{var s;_.clearContext(r),(s=ve.current)==null||s.historyLoader.clearHistory()}),title:he?"Click again to confirm clear context":"Clear context",children:e.jsx(p,{name:he?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ke?"flat-terminal-wrapper__action-btn--active":""}`,onClick:wt,title:ke?"Hide git panel":"Show git changes","aria-pressed":ke,children:e.jsx(p,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ye?"flat-terminal-wrapper__action-btn--active":""}`,onClick:vt,title:ye?"Hide buildings panel":"Show area buildings","aria-pressed":ye,children:e.jsx(p,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:q,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${b?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>B(s=>!s),title:"More actions","aria-expanded":b,children:"⋮"}),b&&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 ${Ae?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{bt(),B(!1)},title:Ae?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(p,{name:"bug",size:14}),e.jsx("span",{children:Ae?"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:()=>{_.collapseContext(r),B(!1)},disabled:m.status!=="idle",title:m.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(p,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),kt&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{U(r,Ue),B(!1)},children:[e.jsx(p,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",Ue," subordinate",Ue===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:()=>{_.killAgent(r),B(!1)},children:[e.jsx(p,{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:L,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:()=>_.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(p,{name:"cross",size:14})})]})]}),ie&&me?e.jsx(oa,{agentId:r}):e.jsx(Kn,{ref:ve,agentId:r,agent:m,viewMode:f,isOpen:!0,onImageClick:M,onFileClick:R,onBashClick:Z,onViewMarkdown:w,keyboard:V,hasModalOpen:!1}),ge&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:nt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${ge.name}`,style:{height:gt},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(p,{name:"terminal",size:12}),e.jsx("span",{children:ge.name}),!((it=ge.terminalStatus)!=null&&it.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>ee(null),title:"Close embedded terminal","aria-label":"Close embedded terminal",children:e.jsx(p,{name:"cross",size:12})})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:(lt=ge.terminalStatus)!=null&&lt.url?e.jsx(Kt,{terminalUrl:ge.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:[m.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(p,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),D&&re&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${D}`,"aria-label":`Open ${D} in file explorer`,role:"button",tabIndex:0,onClick:()=>_.openFileExplorer(D),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),_.openFileExplorer(D))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(p,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:re})]}),Re&&Re.map(({areaId:s,areaName:l,dir:c})=>{const d=Qe.get(c),_e=fe.has(c),Ee=c.split("/").filter(Boolean).pop()||c;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${l}: ${c}${d?` (${d.branch}${d.ahead?` ↑${d.ahead}`:""}${d.behind?` ↓${d.behind}`:""})`:""}`,onClick:()=>_.openFileExplorerForAreaFolder(s,c),children:[e.jsx(p,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:Ee}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(p,{name:"git-branch",size:10})," ",d.branch]}),d.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${d.ahead} ahead`,children:[e.jsx(p,{name:"arrow-up",size:9}),d.ahead]}),d.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${d.behind} behind`,children:[e.jsx(p,{name:"arrow-down",size:9}),d.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${_e?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Me=>{Me.stopPropagation(),Ce(c)},children:e.jsx(p,{name:_e?"hourglass":"download",size:12})})]})]},`${s}:${c}`)}),e.jsx(ua,{agentId:r,disabled:((m==null?void 0:m.provider)??"claude")!=="claude",contextSummary:Fe?`Context: ${ae}k / ${qe}k tokens (${We}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>_.setContextModalAgentId(r),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),_.setContextModalAgentId(r))},title:((m==null?void 0:m.provider)??"claude")!=="claude"?Fe?`Context usage: ${ae}k / ${qe}k tokens (${We}% 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(p,{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:`${be}%`,backgroundColor:He}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:He},children:[ae,"k/",qe,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",Se,"% free)"]}),!Fe&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(p,{name:"warn",size:12})})]})}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),J.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:J.map(s=>{const l=G===s.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${l?"flat-terminal-wrapper__building-btn--active":""} ${s.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${l?"Hide":"Show"} terminal: ${s.name}${s.hasUrl?"":" (starting...)"}`,onClick:()=>{if(l){ee(null);return}s.hasUrl||_.sendBuildingCommand(s.id,"start"),ee(s.id)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),ue(s.id,{x:c.clientX,y:c.clientY})},children:e.jsx(p,{name:"terminal",size:14})},s.id)})}),le.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:le.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"scroll",size:14})},s.id))}),et.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:et.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"hard-drives",size:14})},s.id))}),je.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area tests",children:je.map(s=>e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${s.working?"flat-terminal-wrapper__building-btn--tests-working":""}`,title:s.working?`Running tests: ${s.name}`:`Open tests: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"flask",size:14})},s.id))}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx(Zn,{})})]}),ke&&e.jsx(Jn,{agentId:r,agents:Be,onClose:Ct,branchInfoMap:Qe,fetchRemote:Ce,fetchingDirs:fe,onResizeStart:s=>xt(s,"right")}),ye&&e.jsx(Qn,{agentId:r,onClose:jt}),Ae&&e.jsx(ea,{agentId:r,onClose:_t})]})});function ka({onAgentClick:u,onBuildingClick:r,onBuildingDoubleClick:f,onBuildingPopup:h,onAreaContextMenu:N,onOpenSpawnModal:L,onOpenBossSpawnModal:M,onOpenAreaModal:R}){const{t:Z}=Lt(["common"]),w=_n(),U=wn(),[I,V]=a.useState(null),[Y,ce]=a.useState(null),[te,de]=a.useState(null),[we,Je]=a.useState(null),[se,ue]=a.useState(null),[m,X]=a.useState(null),[pe,ve]=a.useState(null),[Le,me]=a.useState(!1),ie=a.useCallback(()=>{me(t=>!t)},[]),De=a.useCallback(()=>{me(!1)},[]),[Xe,Re]=a.useState(()=>{const t=Ot(S.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Qe=a.useCallback(t=>{Re(t),Bt(S.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=n=>{if(n.key!==S.VIEW_MODE)return;const i=n.newValue;(i==="simple"||i==="chat"||i==="advanced")&&Re(i)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[Ce,fe]=a.useState(()=>Pt(S.FLAT_INSPECTOR_OPEN,!1)),[J,le]=a.useState(!1),et=a.useCallback(()=>le(t=>!t),[]),tt=a.useCallback(()=>le(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:J}}))},[J]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:Ce}}))},[Ce]),a.useEffect(()=>{const t=()=>le(C=>!C),n=()=>{fe(C=>{const k=!C;return oe(S.FLAT_INSPECTOR_OPEN,k),k})},i=()=>{le(!1),fe(!1),oe(S.FLAT_INSPECTOR_OPEN,!1)},g=()=>le(!1),x=()=>{fe(!1),oe(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",i),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",i),window.removeEventListener("tide-close-flat-agents-drawer-only",g),window.removeEventListener("tide-close-flat-inspector-only",x)}},[]);const je=a.useRef(null),Ne=a.useRef(null),[ne,$e]=a.useState(()=>{const t=Ft(S.FLAT_MIDDLE_WIDTH,0);return t>=ht?t:null}),[Q,he]=a.useState(()=>{const t=Ft(S.FLAT_INSPECTOR_WIDTH,0);return t>=Tt?t:null}),G=a.useCallback(t=>{if(typeof window>"u")return t;const n=Q!==null?ft+Q:0,i=window.innerWidth-Xt-ft-Vt-n;return Math.max(ht,Math.min(Math.max(i,ht),t))},[Q]),ee=a.useCallback(t=>{var x;if(typeof window>"u")return t;const n=(x=je.current)==null?void 0:x.querySelector(".flat-middle"),i=(n==null?void 0:n.getBoundingClientRect().width)??ht,g=window.innerWidth-Xt-i-ft-Vt-ft;return Math.max(Tt,Math.min(Math.max(g,Tt),t))},[]);a.useEffect(()=>{if(ne===null&&Q===null)return;const t=()=>{$e(n=>{if(n===null)return n;const i=G(n);return i===n?n:i}),he(n=>{if(n===null)return n;const i=ee(n);return i===n?n:i})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[ne,Q,G,ee]);const ge=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=je.current)==null?void 0:i.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ne.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),gt=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=je.current)==null?void 0:i.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ne.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),nt=a.useCallback(t=>{const n=Ne.current;if(!n||t.pointerId!==n.pointerId)return;const i=t.clientX-n.startX;n.kind==="middle"?$e(G(n.startWidth+i)):he(ee(n.startWidth-i))},[G,ee]),ze=a.useCallback(t=>{const n=Ne.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(Ne.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);$e(x),mt(S.FLAT_MIDDLE_WIDTH,x)}else{const x=ee(n.startWidth-g);he(x),mt(S.FLAT_INSPECTOR_WIDTH,x)}},[G,ee]),xt=a.useCallback(()=>{$e(null),mt(S.FLAT_MIDDLE_WIDTH,0)},[]),ke=a.useCallback(()=>{he(null),mt(S.FLAT_INSPECTOR_WIDTH,0)},[]),[xe,ye]=a.useState(()=>Ot(S.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Ge=a.useCallback(t=>{ye(t),Bt(S.FLAT_INSPECTOR_VIEW,t)},[]),Ae=a.useCallback(()=>{fe(t=>{const n=!t;return oe(S.FLAT_INSPECTOR_OPEN,n),n})},[]),Oe=a.useCallback(()=>{fe(!1),oe(S.FLAT_INSPECTOR_OPEN,!1)},[]),bt=vn(),_t=a.useCallback((t,n)=>{V({url:t,name:n})},[]),wt=a.useCallback((t,n)=>{ce({command:t,output:n,isLive:!1})},[]),vt=a.useCallback((t,n)=>{_.setFileViewerPath(t,n)},[]),Ct=a.useCallback(t=>{de(t)},[]),jt=a.useCallback((t,n)=>{Je({agentId:t,count:n})},[]),Be=a.useCallback(t=>{f?f(t):r(t)},[r,f]),b=a.useMemo(()=>U.size>0?Array.from(U)[0]:null,[U]);a.useEffect(()=>{me(!1)},[b]);const B=a.useRef([]),q=a.useRef(-1),K=a.useRef(!1),Fe=a.useRef(null),[at,st]=a.useState(!1),[Nt,be]=a.useState(!1),We=a.useRef(!1),Se=a.useRef(null),He=a.useRef(!1),ae=a.useMemo(()=>new Set(w.map(t=>t.id)),[w]),qe=a.useMemo(()=>{const t=new Map(w.map(i=>[i.id,i])),n=new Map;for(const i of w)if((i.isBoss||i.class==="boss")&&i.subordinateIds&&i.subordinateIds.length>0){const g=i.subordinateIds.map(x=>t.get(x)).filter(x=>x!==void 0);g.length>0&&n.set(i.id,g)}return n},[w]),D=a.useCallback(()=>{const t=B.current,n=q.current;st(n>0),be(n>=0&&n<t.length-1)},[]),re=a.useCallback(t=>{const n=B.current;if(n.length===0)return;let i=q.current+t;for(;i>=0&&i<n.length;){const g=n[i];if(ae.has(g)){K.current=!0,q.current=i,D(),_.selectAgent(g);return}i+=t}},[ae,D]),Ue=a.useCallback(()=>re(-1),[re]),kt=a.useCallback(()=>re(1),[re]);ia(a.useCallback(()=>{const t=B.current,n=q.current;return t.length>0&&n>0?(re(-1),"handled"):"exit"},[re]));const Ve=a.useCallback((t,n)=>{if(typeof window>"u")return;const i=window.history.state,x={...typeof i=="object"&&i!==null?i:{},__flatAgentNav:{agentId:t}};n==="replace"?window.history.replaceState(x,"",window.location.href):window.history.pushState(x,"",window.location.href)},[]);a.useEffect(()=>{if(!b){We.current=!1,Se.current=null;return}if(!We.current){Ve(b,"replace"),We.current=!0,Se.current=b;return}if(He.current){He.current=!1,Se.current=b;return}Se.current!==b&&(Ve(b,"push"),Se.current=b)},[b,Ve]),a.useEffect(()=>{const t=n=>{var C,k;const i=(k=(C=n.state)==null?void 0:C.__flatAgentNav)==null?void 0:k.agentId;if(!i||typeof i!="string"||!ae.has(i)||i===b)return;He.current=!0,K.current=!0;const g=B.current,x=g.lastIndexOf(i);x>=0?q.current=x:(g.push(i),q.current=g.length-1),D(),_.selectAgent(i)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ae,b,D]),a.useEffect(()=>{if(!b){B.current=[],q.current=-1,D();return}if(Fe.current=b,K.current){K.current=!1,D();return}const t=B.current,n=q.current;if(n>=0&&t[n]===b){D();return}const i=n<t.length-1?t.slice(0,n+1):t.slice();i.push(b),i.length>100&&i.shift(),B.current=i,q.current=i.length-1,D()},[b,D]);const Ye=a.useCallback(t=>{u(t),le(!1)},[u]),it=b??"",lt=a.useCallback(()=>{},[]),s=a.useCallback(t=>{Ye(t)},[Ye]),l=Ce,[c,d]=a.useState(l),[_e,Ee]=a.useState(l);a.useEffect(()=>{if(l){d(!0);return}Ee(!1);const t=setTimeout(()=>d(!1),240);return()=>clearTimeout(t)},[l]),a.useEffect(()=>{if(!c||!l)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>Ee(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[c,l]);const Me=a.useRef(null);a.useEffect(()=>{if(b)return;const t=n=>{if(n.key!==" "&&n.key!=="Backspace")return;const i=n.target;if(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable)return;const g=Fe.current;!g||!ae.has(g)||(n.preventDefault(),_.selectAgent(g))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[b,ae]);const[yt,rt]=a.useState(new Set),ot=a.useCallback(t=>{rt(n=>{const i=new Set(n);return i.has(t)?i.delete(t):i.add(t),i})},[]),[T,z]=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=i=>z(i.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[Ie,tn]=a.useState(null),nn=a.useCallback(t=>{tn(n=>n===t?null:t)},[]),At=Zt(),ct=Jt(),[an]=Cn(),Te=a.useMemo(()=>{const t=new Map,n=[];for(const v of w){const A=_.getAreaForAgent(v.id);if(!Wt((A==null?void 0:A.id)??null))continue;if(!A||A.archived){n.push(v);continue}const E=t.get(A.id);E?E.push(v):t.set(A.id,[v])}const i=new Map,g=[];for(const v of ct.values()){let A=!1;for(const E of At.values())if(!E.archived&&Ht(E.id)&&_.isPositionInArea(v.position,E)){const F=i.get(E.id);F?F.push(v):i.set(E.id,[v]),A=!0;break}!A&&Wt(null)&&g.push(v)}const x=[];for(const[,v]of At){if(v.archived||!Ht(v.id))continue;const A=t.get(v.id),E=i.get(v.id)??[];(A&&A.length>0||E.length>0)&&x.push({area:v,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(v=>v.area.id!=="__unassigned__"),k=x.filter(v=>v.area.id==="__unassigned__");let o=1,y=1;const O=new Map;if(C.length>1){let v=1/0,A=-1/0,E=1/0,F=-1/0;for(const W of C)v=Math.min(v,W.area.center.x),A=Math.max(A,W.area.center.x),E=Math.min(E,W.area.center.z),F=Math.max(F,W.area.center.z);const dt=A-v||1,ut=F-E||1;if(C.length<=4){o=C.length,y=1;const W=[...C].sort((H,St)=>H.area.center.x-St.area.center.x);for(let H=0;H<W.length;H++)O.set(W[H].area.id,{row:1,col:H+1})}else{const W=[...C].sort((j,$)=>j.area.center.x-$.area.center.x),H=[];for(let j=1;j<W.length;j++)H.push(W[j].area.center.x-W[j-1].area.center.x);const St=H.reduce((j,$)=>j+$,0)/H.length||1;let Dt=1;for(const j of H)j>St*1.3&&Dt++;o=Math.max(2,Math.min(Dt,C.length));const Et=[...C].sort((j,$)=>j.area.center.z-$.area.center.z),pt=[];for(let j=1;j<Et.length;j++)pt.push(Et[j].area.center.z-Et[j-1].area.center.z);const on=pt.reduce((j,$)=>j+$,0)/pt.length||1;let Rt=1;for(const j of pt)j>on*1.3&&Rt++;y=Math.max(2,Math.min(Rt,C.length)),o=Math.max(o,Math.ceil(C.length/y)),y=Math.max(y,Math.ceil(C.length/o));const cn=dt/o,dn=ut/y,Mt=new Set;for(const j of C){let $=Math.min(o-1,Math.max(0,Math.floor((j.area.center.x-v)/cn))),Pe=Math.min(y-1,Math.max(0,Math.floor((j.area.center.z-E)/dn))),Ke=`${Pe},${$}`,$t=0;const un=y*o;for(;Mt.has(Ke)&&$t<un;)$++,$>=o&&($=0,Pe=(Pe+1)%y),Ke=`${Pe},${$}`,$t++;Mt.has(Ke)&&(Pe=y,$=0,Ke=`${Pe},${$}`,y++),Mt.add(Ke),O.set(j.area.id,{row:Pe+1,col:$+1})}}}const P=v=>{v.sort((A,E)=>{var dt,ut,W,H;const F=(((dt=A.position)==null?void 0:dt.z)??0)-(((ut=E.position)==null?void 0:ut.z)??0);return F!==0?F:(((W=A.position)==null?void 0:W.x)??0)-(((H=E.position)==null?void 0:H.x)??0)})};for(const v of C)P(v.agents);for(const v of k)P(v.agents);return{groups:[...C,...k],gridCols:o,gridRows:y,positions:O}},[w,At,ct,an]),sn=a.useMemo(()=>{if(!se)return[];const t=w.find(n=>n.id===se.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(p,{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(p,{name:"chat",size:14}),onClick:()=>u(t.id)},{id:"clone-agent",label:"Clone Agent",icon:e.jsx(p,{name:"clipboard",size:14}),onClick:()=>_.cloneAgent(t.id)},{id:"fork-agent",label:"Fork Agent (with history)",icon:e.jsx(p,{name:"git-branch",size:14}),onClick:()=>_.forkAgent(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(p,{name:"trash",size:14}),danger:!0,onClick:()=>{ve({agentId:t.id,name:t.name})}}]:[]},[se,w,u]),ln=a.useMemo(()=>{var C;if(!m)return[];const t=ct.get(m.buildingId);if(!t)return[];const n=[],i=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==="tests"?"Open Tests":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(p,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="tests"?"flask":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>Be(t.id)}),i&&(g||n.push({id:"start",label:"Start",icon:e.jsx(p,{name:"play",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"start")}),g&&(n.push({id:"restart",label:"Restart",icon:e.jsx(p,{name:"refresh",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(p,{name:"stop",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"stop")}))),x&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(n.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(p,{name:"launch",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"start")}}),n.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(p,{name:"pause",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"stop")}}),n.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(p,{name:"restart",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"restart")}})),i&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(p,{name:"health",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"healthCheck")}),n.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),n.push({id:"edit",label:"Edit Building",icon:e.jsx(p,{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(p,{name:"copy",size:14}),onClick:()=>{_.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(p,{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(p,{name:"trash",size:14}),danger:!0,onClick:()=>_.deleteBuilding(t.id)}),n},[m,ct,Be]),rn=a.useCallback(t=>{const n=new Set(Te.groups.map(i=>i.area.id));n.delete(t),rt(n),requestAnimationFrame(()=>{const i=Me.current;if(!i)return;const g=i.querySelector(`[data-area-id="${t}"]`);if(!g)return;const x=i.getBoundingClientRect(),k=g.getBoundingClientRect().top-x.top+i.scrollTop-8;i.scrollTo({top:Math.max(0,k),behavior:"smooth"})})},[Te]);return e.jsxs("div",{ref:je,className:`flat-view ${l?"flat-view--with-inspector":""} ${b?"flat-view--has-chat":""} ${J?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(ne===null&&Q===null)return;const t={};return ne!==null&&(t["--flat-middle-width"]=`${ne}px`),Q!==null&&(t["--flat-inspector-width"]=`${Q}px`),t})(),children:[J&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:tt,"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:L,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:R,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(jn,{activeAgentId:it,onClose:lt,onSelectAgent:s,collapsedAreas:yt,onToggleArea:ot,agentListRef:Me})})]}),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:ge,onPointerMove:nt,onPointerUp:ze,onPointerCancel:ze,onDoubleClick:xt}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":J?"Close agents sidebar":"Open agents sidebar","aria-expanded":J,onClick:et,children:[e.jsx(p,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),b?e.jsx(wa,{agentId:b,terminalViewMode:Xe,onTerminalViewModeChange:Qe,inspectorOpen:Ce,onToggleInspector:Ae,onImageClick:_t,onFileClick:vt,onBashClick:wt,onViewMarkdown:Ct,onRequestClearSubordinates:jt,onOpenBuilding:Be,keyboard:bt,canNavigateBack:at,canNavigateForward:Nt,onNavigateBack:Ue,onNavigateForward:kt,agentInfoOpen:Le,onToggleAgentInfo:ie,onHeaderContextMenu:t=>{b&&ue({agentId:b,position:t})},onBuildingContextMenu:(t,n)=>{X({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(pa,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Te.gridCols}, 1fr)`},children:Te.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=T&&Ie?((n=Te.positions.get(Ie))==null?void 0:n.row)??null:null;return Te.groups.map(i=>{var k;const g=i.area.id,x=Te.positions.get(g),C=T&&Ie!==g;return T&&t!=null&&(x==null?void 0:x.row)===t&&g!==Ie?null:e.jsxs("div",{className:`flat-map-area-card${C?" flat-map-area-card--collapsed":""}`,style:{"--area-color":i.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=i.area.logo)==null?void 0:k.filename)&&e.jsx("img",{className:"flat-map-area-card__logo",src:sa(i.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:()=>T?nn(g):rn(g),title:T?C?`Expand ${i.area.name}`:`Collapse ${i.area.name}`:`Focus ${i.area.name} in left panel`,"aria-expanded":T?!C:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:i.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:i.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:i.agents.length}),T&&e.jsx(p,{name:C?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:i.agents.map(o=>{const y=o.isBoss||o.class==="boss",O=y?qe.get(o.id):void 0,P=Nn(o),v=P.usedPercent>=80?"#ff4a4a":P.usedPercent>=60?"#ff9e4a":P.usedPercent>=40?"#ffd700":"#4aff9e",A=`Context: ${(P.totalTokens/1e3).toFixed(1)}k / ${(P.contextWindow/1e3).toFixed(1)}k (${P.usedPercent}% used, ${P.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:()=>u(o.id),onContextMenu:F=>{F.preventDefault(),F.stopPropagation(),ue({agentId:o.id,position:{x:F.clientX,y:F.clientY}})},title:E?void 0:`${y?"Boss · ":""}Open chat with ${o.name}
1
+ import{r as a,B as pn,E as zt,G as qt,H as Yt,j as e,J as Kt,K as mn,u as Lt,L as fn,M as hn,N as gn,O as xn,V as bn,P as _n,U as wn,W as Ot,S,X as Bt,Y as Pt,Z as Ft,_ as mt,$ as oe,a0 as vn,s as _,a1 as Zt,a2 as Jt,a3 as Cn,w as Wt,x as Ht,I as p,a4 as jn,n as Nn,a5 as kn,a6 as Qt,a7 as en,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 Ut,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,aC as na,aD as aa}from"./main-CEKV7I4r.js";import{g as sa}from"./area-logos-BkmhbXfG.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function ia(u){const r=a.useRef(u);r.current=u,a.useEffect(()=>{if(!pn())return;let f=null,h=!1;return zt.addListener("backButton",()=>{r.current()==="exit"&&zt.exitApp()}).then(N=>{h?N.remove():f=N}),()=>{h=!0,f&&(f.remove(),f=null)}},[])}async function la(u){const r=qt(),f=await fetch(`${Yt()}/api/agents/${u}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!f.ok){const h=await f.json().catch(()=>({}));throw new Error((h==null?void 0:h.error)||`Failed to start terminal (${f.status})`)}return f.json()}async function ra(u){const r=qt();await fetch(`${Yt()}/api/agents/${u}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}const Ze=new Map;function oa({agentId:u}){const[r,f]=a.useState(null),[h,N]=a.useState(null);return a.useEffect(()=>{let L=!1;const M=Ze.get(u);return M&&(clearTimeout(M),Ze.delete(u)),f(null),N(null),la(u).then(R=>{L||f(R.url)}).catch(R=>{L||N(R instanceof Error?R.message:"Failed to start terminal")}),()=>{L=!0;const R=Ze.get(u);R&&clearTimeout(R),Ze.set(u,setTimeout(()=>{Ze.delete(u),ra(u)},2500))}},[u]),h?e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:h})}):r?e.jsx("div",{className:"flat-classic-terminal",children:e.jsx(Kt,{terminalUrl:r,visible:!0})}):e.jsx("div",{className:"flat-classic-terminal flat-classic-terminal--message",children:e.jsx("span",{children:"Attaching to interactive session…"})})}const It=new Map,ca=6e4;function da({agentId:u,contextSummary:r}){const{t:f}=Lt(["terminal","common"]),[h,N]=a.useState(()=>{var I;return((I=It.get(u))==null?void 0:I.snapshot)??null}),[L,M]=a.useState(!1),[R,Z]=a.useState(null),w=a.useRef(0);a.useEffect(()=>{const I=It.get(u);if(I&&Date.now()-I.fetchedAt<ca){N(I.snapshot);return}const V=++w.current;M(!0),Z(null),fn(u).then(Y=>{V===w.current&&(It.set(u,{snapshot:Y,fetchedAt:Date.now()}),N(Y),M(!1))}).catch(Y=>{V===w.current&&(Z(Y.message||"Failed to load plan limits"),M(!1))})},[u]);const U=[];if(h!=null&&h.rateLimits){const I=[{key:"fiveHour",label:f("terminal:usage.currentSession"),window:h.rateLimits.fiveHour},{key:"sevenDay",label:f("terminal:usage.currentWeekAll"),window:h.rateLimits.sevenDay},{key:"sevenDayOpus",label:f("terminal:usage.currentWeekOpus"),window:h.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:f("terminal:usage.currentWeekSonnet"),window:h.rateLimits.sevenDaySonnet}];for(const V of I)V.window&&U.push({...V,window:V.window})}return e.jsxs("div",{className:"plan-limits-tooltip",children:[r&&e.jsx("div",{className:"plan-limits-tooltip__context",children:r}),e.jsx("div",{className:"plan-limits-tooltip__title",children:f("terminal:usage.limits")}),L&&!h&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[f("common:status.loading"),"…"]}),!L&&R&&!h&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:f("terminal:usage.limitsError",{message:R})}),U.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:U.map(({key:I,label:V,window:Y})=>{const ce=Math.max(0,Math.min(100,Y.utilization)),te=gn(ce);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:V}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:te},children:f("terminal:usage.percentUsed",{percent:Math.round(ce)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${ce}%`,background:te}})}),e.jsx("div",{className:"plan-limits-tooltip__reset",children:f("terminal:usage.resets",{time:hn(Y.resetsAt)})})]},I)})}):h&&!L&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:h.rateLimitsError?f("terminal:usage.limitsError",{message:h.rateLimitsError}):h.cliHint})]})}function ua({agentId:u,disabled:r,contextSummary:f,children:h}){return e.jsx(mn,{position:"top",maxWidth:320,disabled:r,className:"plan-limits-tooltip-wrapper",triggerStyle:{display:"inline-flex",alignItems:"center"},content:e.jsx(da,{agentId:u,contextSummary:f}),children:h})}const pa=a.memo(function({className:r=""}){const{t:f}=Lt(["common"]),[h,N]=xn(),L=a.useRef(null),[M,R]=a.useState(null);a.useLayoutEffect(()=>{const w=L.current;if(!w)return;const U=w.querySelector(".view-mode-toggle__btn--active");U&&R({left:U.offsetLeft,width:U.offsetWidth})},[h]);const Z=a.useCallback(w=>{if(w!==h){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:w}})),w==="3d"){requestAnimationFrame(()=>N(w));return}N(w)}},[h,N]);return e.jsxs("div",{className:`view-mode-toggle ${r}`,ref:L,children:[M&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:M.left,width:M.width}}),bn.map(w=>e.jsxs("button",{className:`view-mode-toggle__btn ${h===w?"view-mode-toggle__btn--active":""}`,onClick:()=>Z(w),title:f(`common:viewMode.descriptions.${w}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[w==="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"})]}),w==="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"})]}),w==="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"})]}),w==="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:f(`common:viewMode.labels.${w}`)})]},w))]})}),ft=3,ht=280,Vt=320,Tt=240,Xt=64,ma=["simple","chat","advanced"],fa={simple:"Simple",chat:"Chat",advanced:"Advanced"},ha={simple:"○",chat:"◐",advanced:"◉"},ga={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Gt="flat-clear-context";function xa(u){const r=u.split("/").filter(Boolean);return r.length===0?u:r.slice(-2).join("/")}function ba(u){if(u.provider==="codex"){const L=u.codexModel||"gpt-5.3-codex",M=ta[L];return{model:(M==null?void 0:M.label)||L}}if(u.provider==="opencode")return{model:u.opencodeModel||"opencode"};const r=u.model||"sonnet",f=aa[r],h=u.effort,N=h?na[h]:void 0;return{model:(f==null?void 0:f.label)||r,effort:N==null?void 0:N.label}}function _a(u,r){if(r.type==="rectangle"&&r.width&&r.height){const f=r.width/2,h=r.height/2;return u.x>=r.center.x-f&&u.x<=r.center.x+f&&u.z>=r.center.z-h&&u.z<=r.center.z+h}if(r.type==="circle"&&r.radius){const f=u.x-r.center.x,h=u.z-r.center.z;return f*f+h*h<=r.radius*r.radius}return!1}const wa=On.memo(function({agentId:r,terminalViewMode:f,onTerminalViewModeChange:h,inspectorOpen:N,onToggleInspector:L,onImageClick:M,onFileClick:R,onBashClick:Z,onViewMarkdown:w,onRequestClearSubordinates:U,onOpenBuilding:I,keyboard:V,canNavigateBack:Y,canNavigateForward:ce,onNavigateBack:te,onNavigateForward:de,agentInfoOpen:we,onToggleAgentInfo:Je,onHeaderContextMenu:se,onBuildingContextMenu:ue}){var Ve,Ye,it,lt;const m=Bn(r),X=Jt(),pe=Fn(),ve=a.useRef(null),Le=a.useRef(null),me=!!pe.interactiveMode&&((m==null?void 0:m.provider)??"claude")==="claude"&&!!(m!=null&&m.sessionId),[ie,De]=a.useState(!1);a.useEffect(()=>{De(!1)},[r]),a.useEffect(()=>{!me&&ie&&De(!1)},[me,ie]),a.useEffect(()=>{const s=Le.current;if(!s)return;const l=d=>{d.button===3?(d.preventDefault(),d.stopPropagation(),te()):d.button===4&&(d.preventDefault(),d.stopPropagation(),de())},c=d=>{(d.button===3||d.button===4)&&d.preventDefault()};return s.addEventListener("mouseup",l),s.addEventListener("mousedown",c),()=>{s.removeEventListener("mouseup",l),s.removeEventListener("mousedown",c)}},[te,de]),a.useEffect(()=>{const s=Le.current;if(!s)return;let l=0,c=0,d=0;const _e=250,Ee=600,Me=80,yt=1.5,rt=T=>{let z=T instanceof HTMLElement?T:null;for(;z&&z!==s;){const Ie=window.getComputedStyle(z).overflowX;if((Ie==="auto"||Ie==="scroll")&&z.scrollWidth>z.clientWidth)return!0;z=z.parentElement}return!1},ot=T=>{const z=Date.now();if(z<d){T.preventDefault();return}if(Math.abs(T.deltaX)<=Math.abs(T.deltaY)*yt){l=0;return}if(rt(T.target)){l=0;return}z-c>_e&&(l=0),c=z,l+=T.deltaX,l<=-Me?(l=0,d=z+Ee,T.preventDefault(),te()):l>=Me&&(l=0,d=z+Ee,T.preventDefault(),de())};return s.addEventListener("wheel",ot,{passive:!1}),()=>s.removeEventListener("wheel",ot)},[te,de]);const Xe=Zt(),Re=a.useMemo(()=>{if(!m)return null;const s=new Set,l=[];for(const c of Xe.values())c.archived||c.directories.length===0||c.assignedAgentIds.includes(r)&&(s.add(c.id),l.push(c));for(const c of Xe.values())c.archived||c.directories.length===0||s.has(c.id)||_a({x:m.position.x,z:m.position.z},c)&&(s.add(c.id),l.push(c));return l.length===0?null:l.flatMap(c=>c.directories.filter(d=>d&&d.trim().length>0).map(d=>({areaId:c.id,areaName:c.name,dir:d})))},[m,r,Xe]),{branches:Qe,fetchRemote:Ce,fetchingDirs:fe}=Wn(Re),J=a.useMemo(()=>{var c;const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of X.values())d.type==="terminal"&&_.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name,hasUrl:!!((c=d.terminalStatus)!=null&&c.url)});return l},[r,X]),le=a.useMemo(()=>{var c;const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of X.values())d.type==="server"&&((c=d.pm2)!=null&&c.enabled)&&_.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name});return l},[r,X]),et=a.useMemo(()=>{const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of X.values())c.type==="database"&&c.database&&_.isPositionInArea(c.position,s)&&l.push({id:c.id,name:c.name});return l},[r,X]),tt=Hn(),je=a.useMemo(()=>{const s=_.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of X.values())if(c.type==="tests"&&_.isPositionInArea(c.position,s)){const d=!!c.folderPath&&tt.some(_e=>Un(_e,c.folderPath));l.push({id:c.id,name:c.name,working:d})}return l},[r,X,tt]),[,Ne]=a.useReducer(s=>s+1,0),ne=((Ve=ve.current)==null?void 0:Ve.search.searchMode)??!1,$e=a.useCallback(()=>{var s;(s=ve.current)==null||s.search.toggleSearch(),Ne()},[]),Q=Vn(),he=Q.isPending(Gt),[G,ee]=a.useState(null),ge=G?X.get(G):null,{height:gt,onResizeStart:nt}=Xn(),{sidePanelWidth:ze,handleSidePanelResizeStart:xt}=Gn(),[ke,xe]=a.useState(()=>Pt(S.GIT_PANEL_OPEN,!1)),[ye,Ge]=a.useState(()=>Pt(S.BUILDINGS_PANEL_OPEN,!1)),[Ae,Oe]=a.useState(!1),bt=a.useCallback(()=>{Oe(s=>{const l=!s;return l&&qn.setEnabled(!0),l})},[]),_t=a.useCallback(()=>Oe(!1),[]),wt=a.useCallback(()=>{xe(s=>{const l=!s;return oe(S.GIT_PANEL_OPEN,l),l})},[]),vt=a.useCallback(()=>{Ge(s=>{const l=!s;return oe(S.BUILDINGS_PANEL_OPEN,l),l})},[]),Ct=a.useCallback(()=>{xe(!1),oe(S.GIT_PANEL_OPEN,!1)},[]),jt=a.useCallback(()=>{Ge(!1),oe(S.BUILDINGS_PANEL_OPEN,!1)},[]),Be=Yn();a.useEffect(()=>{if(!G)return;J.some(l=>l.id===G)||ee(null)},[G,J]);const[b,B]=a.useState(!1),q=a.useRef(null);if(a.useEffect(()=>{if(!b)return;const s=l=>{q.current&&!q.current.contains(l.target)&&B(!1)};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[b]),!m)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 K=m.contextStats,Fe=!!K,at=K?K.totalTokens:m.contextUsed||0,st=K?K.contextWindow:m.contextLimit||2e5,Nt=K?K.usedPercent:Math.round(at/st*100),be=Math.max(0,Math.min(100,Nt)),We=Math.round(be*10)/10,Se=Math.round((100-be)*10)/10,He=be>=80?"#ff4a4a":be>=60?"#ff9e4a":be>=40?"#ffd700":"#4aff9e",ae=(at/1e3).toFixed(1),qe=(st/1e3).toFixed(1),D=m.cwd,re=D?xa(D):null,Ue=((Ye=m.subordinateIds)==null?void 0:Ye.length)||0,kt=Ue>0;return e.jsxs("div",{ref:Le,className:`flat-terminal-wrapper ${ke||ye||Ae?"flat-terminal-wrapper--with-side-panel":""}`,style:{"--guake-side-panel-width":`min(${ze}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${we?"flat-terminal-wrapper__header-main--active":""}`,onClick:Je,onContextMenu:s=>{s.preventDefault(),s.stopPropagation(),se({x:s.clientX,y:s.clientY})},title:we?"Hide agent info":"Show agent info","aria-pressed":we,children:[e.jsx(Qt,{agent:m,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:m.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:en(m.status)},children:m.status})]}),m.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:m.taskLabel,children:["📋 ",m.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:m.provider==="codex"?"/assets/codex.png":m.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:m.provider,className:"flat-terminal-wrapper__header-provider-icon",title:m.provider==="codex"?"Codex Agent":m.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:s,effort:l}=ba(m);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:l?`Model: ${s} · Effort: ${l}`:`Model: ${s}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:s}),l&&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:l})]})]})})()]})]}),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:[ma.map(s=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${!ie&&f===s?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{De(!1),h(s)},title:ga[s],"aria-pressed":!ie&&f===s,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:ha[s]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:fa[s]})]},s)),me&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${ie?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>De(s=>!s),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(p,{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:!Y,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(p,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:de,disabled:!ce,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(p,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ne?"flat-terminal-wrapper__action-btn--active":""}`,onClick:$e,title:ne?"Close search":"Search messages","aria-pressed":ne,children:e.jsx(p,{name:ne?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${he?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>Q.handleClick(Gt,()=>{var s;_.clearContext(r),(s=ve.current)==null||s.historyLoader.clearHistory()}),title:he?"Click again to confirm clear context":"Clear context",children:e.jsx(p,{name:he?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ke?"flat-terminal-wrapper__action-btn--active":""}`,onClick:wt,title:ke?"Hide git panel":"Show git changes","aria-pressed":ke,children:e.jsx(p,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ye?"flat-terminal-wrapper__action-btn--active":""}`,onClick:vt,title:ye?"Hide buildings panel":"Show area buildings","aria-pressed":ye,children:e.jsx(p,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:q,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${b?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>B(s=>!s),title:"More actions","aria-expanded":b,children:"⋮"}),b&&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 ${Ae?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{bt(),B(!1)},title:Ae?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(p,{name:"bug",size:14}),e.jsx("span",{children:Ae?"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:()=>{_.collapseContext(r),B(!1)},disabled:m.status!=="idle",title:m.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(p,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),kt&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{U(r,Ue),B(!1)},children:[e.jsx(p,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",Ue," subordinate",Ue===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:()=>{_.killAgent(r),B(!1)},children:[e.jsx(p,{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:L,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:()=>_.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(p,{name:"cross",size:14})})]})]}),ie&&me?e.jsx(oa,{agentId:r}):e.jsx(Kn,{ref:ve,agentId:r,agent:m,viewMode:f,isOpen:!0,onImageClick:M,onFileClick:R,onBashClick:Z,onViewMarkdown:w,keyboard:V,hasModalOpen:!1}),ge&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:nt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${ge.name}`,style:{height:gt},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(p,{name:"terminal",size:12}),e.jsx("span",{children:ge.name}),!((it=ge.terminalStatus)!=null&&it.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>ee(null),title:"Close embedded terminal","aria-label":"Close embedded terminal",children:e.jsx(p,{name:"cross",size:12})})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:(lt=ge.terminalStatus)!=null&&lt.url?e.jsx(Kt,{terminalUrl:ge.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:[m.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(p,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),D&&re&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${D}`,"aria-label":`Open ${D} in file explorer`,role:"button",tabIndex:0,onClick:()=>_.openFileExplorer(D),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),_.openFileExplorer(D))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(p,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:re})]}),Re&&Re.map(({areaId:s,areaName:l,dir:c})=>{const d=Qe.get(c),_e=fe.has(c),Ee=c.split("/").filter(Boolean).pop()||c;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${l}: ${c}${d?` (${d.branch}${d.ahead?` ↑${d.ahead}`:""}${d.behind?` ↓${d.behind}`:""})`:""}`,onClick:()=>_.openFileExplorerForAreaFolder(s,c),children:[e.jsx(p,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:Ee}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(p,{name:"git-branch",size:10})," ",d.branch]}),d.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${d.ahead} ahead`,children:[e.jsx(p,{name:"arrow-up",size:9}),d.ahead]}),d.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${d.behind} behind`,children:[e.jsx(p,{name:"arrow-down",size:9}),d.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${_e?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Me=>{Me.stopPropagation(),Ce(c)},children:e.jsx(p,{name:_e?"hourglass":"download",size:12})})]})]},`${s}:${c}`)}),e.jsx(ua,{agentId:r,disabled:((m==null?void 0:m.provider)??"claude")!=="claude",contextSummary:Fe?`Context: ${ae}k / ${qe}k tokens (${We}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>_.setContextModalAgentId(r),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),_.setContextModalAgentId(r))},title:((m==null?void 0:m.provider)??"claude")!=="claude"?Fe?`Context usage: ${ae}k / ${qe}k tokens (${We}% 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(p,{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:`${be}%`,backgroundColor:He}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:He},children:[ae,"k/",qe,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",Se,"% free)"]}),!Fe&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(p,{name:"warn",size:12})})]})}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),J.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:J.map(s=>{const l=G===s.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${l?"flat-terminal-wrapper__building-btn--active":""} ${s.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${l?"Hide":"Show"} terminal: ${s.name}${s.hasUrl?"":" (starting...)"}`,onClick:()=>{if(l){ee(null);return}s.hasUrl||_.sendBuildingCommand(s.id,"start"),ee(s.id)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),ue(s.id,{x:c.clientX,y:c.clientY})},children:e.jsx(p,{name:"terminal",size:14})},s.id)})}),le.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:le.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"scroll",size:14})},s.id))}),et.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:et.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"hard-drives",size:14})},s.id))}),je.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area tests",children:je.map(s=>e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${s.working?"flat-terminal-wrapper__building-btn--tests-working":""}`,title:s.working?`Running tests: ${s.name}`:`Open tests: ${s.name}`,onClick:()=>I(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),ue(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"flask",size:14})},s.id))}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx(Zn,{})})]}),ke&&e.jsx(Jn,{agentId:r,agents:Be,onClose:Ct,branchInfoMap:Qe,fetchRemote:Ce,fetchingDirs:fe,onResizeStart:s=>xt(s,"right")}),ye&&e.jsx(Qn,{agentId:r,onClose:jt}),Ae&&e.jsx(ea,{agentId:r,onClose:_t})]})});function ka({onAgentClick:u,onBuildingClick:r,onBuildingDoubleClick:f,onBuildingPopup:h,onAreaContextMenu:N,onOpenSpawnModal:L,onOpenBossSpawnModal:M,onOpenAreaModal:R}){const{t:Z}=Lt(["common"]),w=_n(),U=wn(),[I,V]=a.useState(null),[Y,ce]=a.useState(null),[te,de]=a.useState(null),[we,Je]=a.useState(null),[se,ue]=a.useState(null),[m,X]=a.useState(null),[pe,ve]=a.useState(null),[Le,me]=a.useState(!1),ie=a.useCallback(()=>{me(t=>!t)},[]),De=a.useCallback(()=>{me(!1)},[]),[Xe,Re]=a.useState(()=>{const t=Ot(S.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Qe=a.useCallback(t=>{Re(t),Bt(S.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=n=>{if(n.key!==S.VIEW_MODE)return;const i=n.newValue;(i==="simple"||i==="chat"||i==="advanced")&&Re(i)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[Ce,fe]=a.useState(()=>Pt(S.FLAT_INSPECTOR_OPEN,!1)),[J,le]=a.useState(!1),et=a.useCallback(()=>le(t=>!t),[]),tt=a.useCallback(()=>le(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:J}}))},[J]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:Ce}}))},[Ce]),a.useEffect(()=>{const t=()=>le(C=>!C),n=()=>{fe(C=>{const k=!C;return oe(S.FLAT_INSPECTOR_OPEN,k),k})},i=()=>{le(!1),fe(!1),oe(S.FLAT_INSPECTOR_OPEN,!1)},g=()=>le(!1),x=()=>{fe(!1),oe(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",i),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",i),window.removeEventListener("tide-close-flat-agents-drawer-only",g),window.removeEventListener("tide-close-flat-inspector-only",x)}},[]);const je=a.useRef(null),Ne=a.useRef(null),[ne,$e]=a.useState(()=>{const t=Ft(S.FLAT_MIDDLE_WIDTH,0);return t>=ht?t:null}),[Q,he]=a.useState(()=>{const t=Ft(S.FLAT_INSPECTOR_WIDTH,0);return t>=Tt?t:null}),G=a.useCallback(t=>{if(typeof window>"u")return t;const n=Q!==null?ft+Q:0,i=window.innerWidth-Xt-ft-Vt-n;return Math.max(ht,Math.min(Math.max(i,ht),t))},[Q]),ee=a.useCallback(t=>{var x;if(typeof window>"u")return t;const n=(x=je.current)==null?void 0:x.querySelector(".flat-middle"),i=(n==null?void 0:n.getBoundingClientRect().width)??ht,g=window.innerWidth-Xt-i-ft-Vt-ft;return Math.max(Tt,Math.min(Math.max(g,Tt),t))},[]);a.useEffect(()=>{if(ne===null&&Q===null)return;const t=()=>{$e(n=>{if(n===null)return n;const i=G(n);return i===n?n:i}),he(n=>{if(n===null)return n;const i=ee(n);return i===n?n:i})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[ne,Q,G,ee]);const ge=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=je.current)==null?void 0:i.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ne.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),gt=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=je.current)==null?void 0:i.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),Ne.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),nt=a.useCallback(t=>{const n=Ne.current;if(!n||t.pointerId!==n.pointerId)return;const i=t.clientX-n.startX;n.kind==="middle"?$e(G(n.startWidth+i)):he(ee(n.startWidth-i))},[G,ee]),ze=a.useCallback(t=>{const n=Ne.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(Ne.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);$e(x),mt(S.FLAT_MIDDLE_WIDTH,x)}else{const x=ee(n.startWidth-g);he(x),mt(S.FLAT_INSPECTOR_WIDTH,x)}},[G,ee]),xt=a.useCallback(()=>{$e(null),mt(S.FLAT_MIDDLE_WIDTH,0)},[]),ke=a.useCallback(()=>{he(null),mt(S.FLAT_INSPECTOR_WIDTH,0)},[]),[xe,ye]=a.useState(()=>Ot(S.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Ge=a.useCallback(t=>{ye(t),Bt(S.FLAT_INSPECTOR_VIEW,t)},[]),Ae=a.useCallback(()=>{fe(t=>{const n=!t;return oe(S.FLAT_INSPECTOR_OPEN,n),n})},[]),Oe=a.useCallback(()=>{fe(!1),oe(S.FLAT_INSPECTOR_OPEN,!1)},[]),bt=vn(),_t=a.useCallback((t,n)=>{V({url:t,name:n})},[]),wt=a.useCallback((t,n)=>{ce({command:t,output:n,isLive:!1})},[]),vt=a.useCallback((t,n)=>{_.setFileViewerPath(t,n)},[]),Ct=a.useCallback(t=>{de(t)},[]),jt=a.useCallback((t,n)=>{Je({agentId:t,count:n})},[]),Be=a.useCallback(t=>{f?f(t):r(t)},[r,f]),b=a.useMemo(()=>U.size>0?Array.from(U)[0]:null,[U]);a.useEffect(()=>{me(!1)},[b]);const B=a.useRef([]),q=a.useRef(-1),K=a.useRef(!1),Fe=a.useRef(null),[at,st]=a.useState(!1),[Nt,be]=a.useState(!1),We=a.useRef(!1),Se=a.useRef(null),He=a.useRef(!1),ae=a.useMemo(()=>new Set(w.map(t=>t.id)),[w]),qe=a.useMemo(()=>{const t=new Map(w.map(i=>[i.id,i])),n=new Map;for(const i of w)if((i.isBoss||i.class==="boss")&&i.subordinateIds&&i.subordinateIds.length>0){const g=i.subordinateIds.map(x=>t.get(x)).filter(x=>x!==void 0);g.length>0&&n.set(i.id,g)}return n},[w]),D=a.useCallback(()=>{const t=B.current,n=q.current;st(n>0),be(n>=0&&n<t.length-1)},[]),re=a.useCallback(t=>{const n=B.current;if(n.length===0)return;let i=q.current+t;for(;i>=0&&i<n.length;){const g=n[i];if(ae.has(g)){K.current=!0,q.current=i,D(),_.selectAgent(g);return}i+=t}},[ae,D]),Ue=a.useCallback(()=>re(-1),[re]),kt=a.useCallback(()=>re(1),[re]);ia(a.useCallback(()=>{const t=B.current,n=q.current;return t.length>0&&n>0?(re(-1),"handled"):"exit"},[re]));const Ve=a.useCallback((t,n)=>{if(typeof window>"u")return;const i=window.history.state,x={...typeof i=="object"&&i!==null?i:{},__flatAgentNav:{agentId:t}};n==="replace"?window.history.replaceState(x,"",window.location.href):window.history.pushState(x,"",window.location.href)},[]);a.useEffect(()=>{if(!b){We.current=!1,Se.current=null;return}if(!We.current){Ve(b,"replace"),We.current=!0,Se.current=b;return}if(He.current){He.current=!1,Se.current=b;return}Se.current!==b&&(Ve(b,"push"),Se.current=b)},[b,Ve]),a.useEffect(()=>{const t=n=>{var C,k;const i=(k=(C=n.state)==null?void 0:C.__flatAgentNav)==null?void 0:k.agentId;if(!i||typeof i!="string"||!ae.has(i)||i===b)return;He.current=!0,K.current=!0;const g=B.current,x=g.lastIndexOf(i);x>=0?q.current=x:(g.push(i),q.current=g.length-1),D(),_.selectAgent(i)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ae,b,D]),a.useEffect(()=>{if(!b){B.current=[],q.current=-1,D();return}if(Fe.current=b,K.current){K.current=!1,D();return}const t=B.current,n=q.current;if(n>=0&&t[n]===b){D();return}const i=n<t.length-1?t.slice(0,n+1):t.slice();i.push(b),i.length>100&&i.shift(),B.current=i,q.current=i.length-1,D()},[b,D]);const Ye=a.useCallback(t=>{u(t),le(!1)},[u]),it=b??"",lt=a.useCallback(()=>{},[]),s=a.useCallback(t=>{Ye(t)},[Ye]),l=Ce,[c,d]=a.useState(l),[_e,Ee]=a.useState(l);a.useEffect(()=>{if(l){d(!0);return}Ee(!1);const t=setTimeout(()=>d(!1),240);return()=>clearTimeout(t)},[l]),a.useEffect(()=>{if(!c||!l)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>Ee(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[c,l]);const Me=a.useRef(null);a.useEffect(()=>{if(b)return;const t=n=>{if(n.key!==" "&&n.key!=="Backspace")return;const i=n.target;if(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable)return;const g=Fe.current;!g||!ae.has(g)||(n.preventDefault(),_.selectAgent(g))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[b,ae]);const[yt,rt]=a.useState(new Set),ot=a.useCallback(t=>{rt(n=>{const i=new Set(n);return i.has(t)?i.delete(t):i.add(t),i})},[]),[T,z]=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=i=>z(i.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[Ie,tn]=a.useState(null),nn=a.useCallback(t=>{tn(n=>n===t?null:t)},[]),At=Zt(),ct=Jt(),[an]=Cn(),Te=a.useMemo(()=>{const t=new Map,n=[];for(const v of w){const A=_.getAreaForAgent(v.id);if(!Wt((A==null?void 0:A.id)??null))continue;if(!A||A.archived){n.push(v);continue}const E=t.get(A.id);E?E.push(v):t.set(A.id,[v])}const i=new Map,g=[];for(const v of ct.values()){let A=!1;for(const E of At.values())if(!E.archived&&Ht(E.id)&&_.isPositionInArea(v.position,E)){const F=i.get(E.id);F?F.push(v):i.set(E.id,[v]),A=!0;break}!A&&Wt(null)&&g.push(v)}const x=[];for(const[,v]of At){if(v.archived||!Ht(v.id))continue;const A=t.get(v.id),E=i.get(v.id)??[];(A&&A.length>0||E.length>0)&&x.push({area:v,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(v=>v.area.id!=="__unassigned__"),k=x.filter(v=>v.area.id==="__unassigned__");let o=1,y=1;const O=new Map;if(C.length>1){let v=1/0,A=-1/0,E=1/0,F=-1/0;for(const W of C)v=Math.min(v,W.area.center.x),A=Math.max(A,W.area.center.x),E=Math.min(E,W.area.center.z),F=Math.max(F,W.area.center.z);const dt=A-v||1,ut=F-E||1;if(C.length<=4){o=C.length,y=1;const W=[...C].sort((H,St)=>H.area.center.x-St.area.center.x);for(let H=0;H<W.length;H++)O.set(W[H].area.id,{row:1,col:H+1})}else{const W=[...C].sort((j,$)=>j.area.center.x-$.area.center.x),H=[];for(let j=1;j<W.length;j++)H.push(W[j].area.center.x-W[j-1].area.center.x);const St=H.reduce((j,$)=>j+$,0)/H.length||1;let Dt=1;for(const j of H)j>St*1.3&&Dt++;o=Math.max(2,Math.min(Dt,C.length));const Et=[...C].sort((j,$)=>j.area.center.z-$.area.center.z),pt=[];for(let j=1;j<Et.length;j++)pt.push(Et[j].area.center.z-Et[j-1].area.center.z);const on=pt.reduce((j,$)=>j+$,0)/pt.length||1;let Rt=1;for(const j of pt)j>on*1.3&&Rt++;y=Math.max(2,Math.min(Rt,C.length)),o=Math.max(o,Math.ceil(C.length/y)),y=Math.max(y,Math.ceil(C.length/o));const cn=dt/o,dn=ut/y,Mt=new Set;for(const j of C){let $=Math.min(o-1,Math.max(0,Math.floor((j.area.center.x-v)/cn))),Pe=Math.min(y-1,Math.max(0,Math.floor((j.area.center.z-E)/dn))),Ke=`${Pe},${$}`,$t=0;const un=y*o;for(;Mt.has(Ke)&&$t<un;)$++,$>=o&&($=0,Pe=(Pe+1)%y),Ke=`${Pe},${$}`,$t++;Mt.has(Ke)&&(Pe=y,$=0,Ke=`${Pe},${$}`,y++),Mt.add(Ke),O.set(j.area.id,{row:Pe+1,col:$+1})}}}const P=v=>{v.sort((A,E)=>{var dt,ut,W,H;const F=(((dt=A.position)==null?void 0:dt.z)??0)-(((ut=E.position)==null?void 0:ut.z)??0);return F!==0?F:(((W=A.position)==null?void 0:W.x)??0)-(((H=E.position)==null?void 0:H.x)??0)})};for(const v of C)P(v.agents);for(const v of k)P(v.agents);return{groups:[...C,...k],gridCols:o,gridRows:y,positions:O}},[w,At,ct,an]),sn=a.useMemo(()=>{if(!se)return[];const t=w.find(n=>n.id===se.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(p,{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(p,{name:"chat",size:14}),onClick:()=>u(t.id)},{id:"clone-agent",label:"Clone Agent",icon:e.jsx(p,{name:"clipboard",size:14}),onClick:()=>_.cloneAgent(t.id)},{id:"fork-agent",label:"Fork Agent (with history)",icon:e.jsx(p,{name:"git-branch",size:14}),onClick:()=>_.forkAgent(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(p,{name:"trash",size:14}),danger:!0,onClick:()=>{ve({agentId:t.id,name:t.name})}}]:[]},[se,w,u]),ln=a.useMemo(()=>{var C;if(!m)return[];const t=ct.get(m.buildingId);if(!t)return[];const n=[],i=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==="tests"?"Open Tests":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(p,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="tests"?"flask":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>Be(t.id)}),i&&(g||n.push({id:"start",label:"Start",icon:e.jsx(p,{name:"play",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"start")}),g&&(n.push({id:"restart",label:"Restart",icon:e.jsx(p,{name:"refresh",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(p,{name:"stop",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"stop")}))),x&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(n.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(p,{name:"launch",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"start")}}),n.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(p,{name:"pause",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"stop")}}),n.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(p,{name:"restart",size:14}),onClick:()=>{for(const k of t.subordinateBuildingIds)_.sendBuildingCommand(k,"restart")}})),i&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(p,{name:"health",size:14}),onClick:()=>_.sendBuildingCommand(t.id,"healthCheck")}),n.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),n.push({id:"edit",label:"Edit Building",icon:e.jsx(p,{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(p,{name:"copy",size:14}),onClick:()=>{_.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(p,{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(p,{name:"trash",size:14}),danger:!0,onClick:()=>_.deleteBuilding(t.id)}),n},[m,ct,Be]),rn=a.useCallback(t=>{const n=new Set(Te.groups.map(i=>i.area.id));n.delete(t),rt(n),requestAnimationFrame(()=>{const i=Me.current;if(!i)return;const g=i.querySelector(`[data-area-id="${t}"]`);if(!g)return;const x=i.getBoundingClientRect(),k=g.getBoundingClientRect().top-x.top+i.scrollTop-8;i.scrollTo({top:Math.max(0,k),behavior:"smooth"})})},[Te]);return e.jsxs("div",{ref:je,className:`flat-view ${l?"flat-view--with-inspector":""} ${b?"flat-view--has-chat":""} ${J?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(ne===null&&Q===null)return;const t={};return ne!==null&&(t["--flat-middle-width"]=`${ne}px`),Q!==null&&(t["--flat-inspector-width"]=`${Q}px`),t})(),children:[J&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:tt,"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:L,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:R,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(jn,{activeAgentId:it,onClose:lt,onSelectAgent:s,collapsedAreas:yt,onToggleArea:ot,agentListRef:Me})})]}),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:ge,onPointerMove:nt,onPointerUp:ze,onPointerCancel:ze,onDoubleClick:xt}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":J?"Close agents sidebar":"Open agents sidebar","aria-expanded":J,onClick:et,children:[e.jsx(p,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),b?e.jsx(wa,{agentId:b,terminalViewMode:Xe,onTerminalViewModeChange:Qe,inspectorOpen:Ce,onToggleInspector:Ae,onImageClick:_t,onFileClick:vt,onBashClick:wt,onViewMarkdown:Ct,onRequestClearSubordinates:jt,onOpenBuilding:Be,keyboard:bt,canNavigateBack:at,canNavigateForward:Nt,onNavigateBack:Ue,onNavigateForward:kt,agentInfoOpen:Le,onToggleAgentInfo:ie,onHeaderContextMenu:t=>{b&&ue({agentId:b,position:t})},onBuildingContextMenu:(t,n)=>{X({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(pa,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Te.gridCols}, 1fr)`},children:Te.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=T&&Ie?((n=Te.positions.get(Ie))==null?void 0:n.row)??null:null;return Te.groups.map(i=>{var k;const g=i.area.id,x=Te.positions.get(g),C=T&&Ie!==g;return T&&t!=null&&(x==null?void 0:x.row)===t&&g!==Ie?null:e.jsxs("div",{className:`flat-map-area-card${C?" flat-map-area-card--collapsed":""}`,style:{"--area-color":i.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=i.area.logo)==null?void 0:k.filename)&&e.jsx("img",{className:"flat-map-area-card__logo",src:sa(i.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:()=>T?nn(g):rn(g),title:T?C?`Expand ${i.area.name}`:`Collapse ${i.area.name}`:`Focus ${i.area.name} in left panel`,"aria-expanded":T?!C:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:i.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:i.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:i.agents.length}),T&&e.jsx(p,{name:C?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:i.agents.map(o=>{const y=o.isBoss||o.class==="boss",O=y?qe.get(o.id):void 0,P=Nn(o),v=P.usedPercent>=80?"#ff4a4a":P.usedPercent>=60?"#ff9e4a":P.usedPercent>=40?"#ffd700":"#4aff9e",A=`Context: ${(P.totalTokens/1e3).toFixed(1)}k / ${(P.contextWindow/1e3).toFixed(1)}k (${P.usedPercent}% used, ${P.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:()=>u(o.id),onContextMenu:F=>{F.preventDefault(),F.stopPropagation(),ue({agentId:o.id,position:{x:F.clientX,y:F.clientY}})},title:E?void 0:`${y?"Boss · ":""}Open chat with ${o.name}
2
2
  ${A}`,children:[e.jsx(Qt,{agent:o,size:16}),y&&e.jsx("span",{className:"flat-map-agent-chip__crown","aria-hidden":"true",children:e.jsx(p,{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:en(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:`${P.usedPercent}%`,backgroundColor:v}})})]})},o.id)})}),i.area.directories.length>0&&e.jsx("div",{className:"flat-map-area-card__folders",role:"group","aria-label":`${i.area.name} folders`,children:i.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(),_.openFileExplorerForAreaFolder(g,o)},title:`Open in file explorer: ${o}`,children:[e.jsx(p,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-map-folder-chip__name",children:y})]},o)})}),i.buildings.length>0&&e.jsx("div",{className:"flat-map-area-card__buildings",children:i.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:P=>{if(h){const v=P.currentTarget.getBoundingClientRect();h(o.id,{x:v.right,y:v.top+v.height/2})}else Be(o.id)},onContextMenu:P=>{P.preventDefault(),P.stopPropagation(),X({buildingId:o.id,position:{x:P.clientX,y:P.clientY}})},title:`${o.name} · ${o.type} · ${o.status}`,children:[e.jsx(p,{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)})})()})]})})]}),l&&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:gt,onPointerMove:nt,onPointerUp:ze,onPointerCancel:ze,onDoubleClick:ke}),c&&e.jsxs("aside",{className:`flat-inspector ${_e?"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":xe==="agent",className:`flat-inspector__tab ${xe==="agent"?"flat-inspector__tab--active":""}`,onClick:()=>Ge("agent"),children:"Agent"}),e.jsx("button",{type:"button",role:"tab","aria-selected":xe==="tracking",className:`flat-inspector__tab ${xe==="tracking"?"flat-inspector__tab--active":""}`,onClick:()=>Ge("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:Oe,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:xe==="tracking"?e.jsx(In,{activeAgentId:b??"",onSelectAgent:t=>{u(t),window.innerWidth<=768&&Oe()}}):(()=>{if(!b)return e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Select an agent to inspect"})});const t=w.find(n=>n.id===b);return t?e.jsx(Tn,{agent:t,onFocusAgent:n=>{u(n),window.innerWidth<=768&&Oe()},onKillAgent:n=>_.killAgent(n)}):e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Agent not found"})})})()})]}),I&&e.jsx(Pn,{url:I.url,name:I.name,onClose:()=>V(null)}),Y&&e.jsx(Ln,{state:Y,onClose:()=>ce(null)}),e.jsx(Dn,{agent:b?w.find(t=>t.id===b)??null:null,content:te,onClose:()=>de(null)}),we&&e.jsx(Rn,{action:"clear-subordinates",selectedAgentId:we.agentId,subordinateCount:we.count,onClose:()=>Je(null),onClearHistory:()=>{}}),e.jsx($n,{agent:b?w.find(t=>t.id===b)??null:null,isOpen:Le&&!!b,onClose:De}),e.jsx(Ut,{isOpen:se!==null,position:(se==null?void 0:se.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:sn,onClose:()=>ue(null)}),e.jsx(Ut,{isOpen:m!==null,position:(m==null?void 0:m.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:ln,onClose:()=>X(null)}),e.jsx(zn,{isOpen:pe!==null,title:Z("common:confirm.removeAgentTitle"),message:Z("common:confirm.removeAgentMessage",{name:(pe==null?void 0:pe.name)??""}),confirmLabel:Z("common:buttons.remove"),cancelLabel:Z("common:buttons.cancel"),variant:"danger",onConfirm:()=>{pe&&_.removeAgentFromServer(pe.agentId)},onClose:()=>ve(null)})]})}export{ka as FlatView};
@@ -1,4 +1,4 @@
1
- import{r as l,b3 as Re,b4 as Ye,j as e,I as L,u as Y,b5 as as,ab as ns,f as Ve,s as T,b6 as hs,b7 as ms,aY as gs,b8 as fs,C as he,G as oe,H as Z,h as je,i as ke,m as xs,b9 as bs,ba as js,bb as vs,bc as ws,P as Ns,bd as Se,a6 as ys,be as is,bf as ks,bg as Be,bh as Ss,bi as Cs,bj as As,bk as Ts,bl as _s,bm as Is,bn as Es,aS as Ps,W as Ls,S as ye,bo as $s,bp as Ds,aU as Fs,bq as Ue,X as Ee,b0 as Os,br as ze,bs as Rs}from"./main-ChEsMqV1.js";import{g as Us,d as zs,u as Ms}from"./area-logos-Bsh88_lc.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.129.1";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,b3 as Re,b4 as Ye,j as e,I as L,u as Y,b5 as as,ab as ns,f as Ve,s as T,b6 as hs,b7 as ms,aY as gs,b8 as fs,C as he,G as oe,H as Z,h as je,i as ke,m as xs,b9 as bs,ba as js,bb as vs,bc as ws,P as Ns,bd as Se,a6 as ys,be as is,bf as ks,bg as Be,bh as Ss,bi as Cs,bj as As,bk as Ts,bl as _s,bm as Is,bn as Es,aS as Ps,W as Ls,S as ye,bo as $s,bp as Ds,aU as Fs,bq as Ue,X as Ee,b0 as Os,br as ze,bs as Rs}from"./main-CEKV7I4r.js";import{g as Us,d as zs,u as Ms}from"./area-logos-BkmhbXfG.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.129.2";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?`