tide-commander 1.139.2 → 1.140.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/assets/{BossLogsModal-BuknVw0t.js → BossLogsModal-CEShD72G.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-Bk_GVUor.js → BossSpawnModal-D_DbznYG.js} +1 -1
  3. package/dist/assets/{ControlsModal-YxXtwKJV.js → ControlsModal-CSV9_1uM.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-CblkdNqt.js → DockerLogsModal-CiygMroW.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-D_jdlmTI.js → EmbeddedEditor-Dkdulh-K.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-CGXFB4Xr.js → GmailOAuthSetup-Diq3kLhl.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-Btgu3TOp.js → GoogleOAuthSetup-CeeDd_xu.js} +1 -1
  8. package/dist/assets/{IframeModal-yvc5X_Yh.js → IframeModal-C5dbNqKD.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-zQ7-X7PF.js → IntegrationsPanel-DRn7C1MY.js} +2 -2
  10. package/dist/assets/{LogViewerModal-DGzIeeJQ.js → LogViewerModal-DOQxrBbw.js} +1 -1
  11. package/dist/assets/{MonitoringModal-DySuIczM.js → MonitoringModal-Cwwk7At7.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-Dq5ZLh0W.js → PM2LogsModal-BBLqAy_X.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-D_6yMJIx.js → RestoreArchivedAreaModal-D02230fP.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-tZKB12LU.js → Scene2DCanvas-T1mD-NLE.js} +1 -1
  15. package/dist/assets/{SceneManager-BeJLz_RT.js → SceneManager-B8CWKy5o.js} +1 -1
  16. package/dist/assets/{SkillsPanel-gPP_MHFb.js → SkillsPanel-BcckjcEb.js} +2 -2
  17. package/dist/assets/{SlackMultiInstanceSetup-C7Qvm39W.js → SlackMultiInstanceSetup-Cj8Iu2Wk.js} +1 -1
  18. package/dist/assets/{SpawnModal-D3-Z5mzv.js → SpawnModal-BvhLamvi.js} +1 -1
  19. package/dist/assets/{StatisticsModal-DCAF9Dsa.js → StatisticsModal-CZ5_LEYB.js} +1 -1
  20. package/dist/assets/{SubordinateAssignmentModal-DTbryouu.js → SubordinateAssignmentModal-B5fsamyK.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-i9h5lRli.js → TriggerManagerPanel-6lpEA2KC.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-DY8YA4bD.js → WorkflowEditorPanel-BrF8p9-9.js} +1 -1
  23. package/dist/assets/{area-logos-CFnhy-W8.js → area-logos-N2igqdil.js} +1 -1
  24. package/dist/assets/index-BEjvvTvd.js +2 -0
  25. package/dist/assets/{index-Cjtcr4_w.js → index-BQHw3dpO.js} +4 -4
  26. package/dist/assets/{index-BCTUaC9_.js → index-C05ImQcq.js} +1 -1
  27. package/dist/assets/{index-B1ZW-nQg.js → index-C4WbvHfv.js} +1 -1
  28. package/dist/assets/{index-ochVZ1qG.js → index-DQOQTnz4.js} +3 -3
  29. package/dist/assets/{index-DAlpCHwk.js → index-DqPObBhQ.js} +1 -1
  30. package/dist/assets/index-HVo8TeN6.js +2 -0
  31. package/dist/assets/index-HX-vahcd.js +1 -0
  32. package/dist/assets/{index-CC0xW5So.js → index-egOui-YJ.js} +3 -3
  33. package/dist/assets/{main-CpuU-ex-.js → main-CAmYbJhQ.js} +118 -118
  34. package/dist/assets/main-DYAzUs5m.css +1 -0
  35. package/dist/assets/{web-f3jpYwOI.js → web-BV4UqfvW.js} +1 -1
  36. package/dist/assets/{web-KIxT1AKQ.js → web-Bp9InB_8.js} +1 -1
  37. package/dist/assets/{web-CQHAjGLu.js → web-Cbif1aIk.js} +1 -1
  38. package/dist/index.html +2 -2
  39. package/dist/locales/en/config.json +9 -1
  40. package/dist/src/packages/server/data/builtin-skills/browser-control.js +7 -5
  41. package/dist/src/packages/server/routes/browser.js +4 -1
  42. package/package.json +1 -1
  43. package/dist/assets/index-B5TMKZMf.js +0 -2
  44. package/dist/assets/index-BL0c4Fee.js +0 -1
  45. package/dist/assets/index-C9wQ_Bkk.js +0 -2
  46. package/dist/assets/main-d2YCqass.css +0 -1
@@ -0,0 +1,2 @@
1
+ import{r as a,B as mn,E as Bt,G as Zt,H as Jt,j as e,J as Qt,K as fn,u as Rt,L as hn,M as gn,N as xn,O as bn,V as wn,P as _n,U as vn,W as Cn,X as Ft,S,Y as Wt,Z as Dt,_ as Ht,$ as xt,a0 as ge,a1 as jn,s as b,a2 as en,a3 as tn,a4 as Nn,w as Ut,x as Vt,I as p,a5 as kn,n as yn,a6 as An,a7 as nn,a8 as an,a9 as Sn,aa as En,ab as Mn,ac as In,ad as Tn,ae as Pn,af as Ln,ag as Dn,ah as Rn,ai as $n,aj as zn,ak as On,al as Xt,C as Bn,am as Fn,an as Gt,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,aE as sa,aF as ia}from"./main-CAmYbJhQ.js";import{g as la}from"./area-logos-N2igqdil.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function ra(u){const r=a.useRef(u);r.current=u,a.useEffect(()=>{if(!mn())return;let m=null,h=!1;return Bt.addListener("backButton",()=>{r.current()==="exit"&&Bt.exitApp()}).then(N=>{h?N.remove():m=N}),()=>{h=!0,m&&(m.remove(),m=null)}},[])}async function oa(u){const r=Zt(),m=await fetch(`${Jt()}/api/agents/${u}/terminal`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!m.ok){const h=await m.json().catch(()=>({}));throw new Error((h==null?void 0:h.error)||`Failed to start terminal (${m.status})`)}return m.json()}async function ca(u){const r=Zt();await fetch(`${Jt()}/api/agents/${u}/terminal`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}const at=new Map;function da({agentId:u}){const[r,m]=a.useState(null),[h,N]=a.useState(null);return a.useEffect(()=>{let P=!1;const I=at.get(u);return I&&(clearTimeout(I),at.delete(u)),m(null),N(null),oa(u).then(L=>{P||m(L.url)}).catch(L=>{P||N(L instanceof Error?L.message:"Failed to start terminal")}),()=>{P=!0;const L=at.get(u);L&&clearTimeout(L),at.set(u,setTimeout(()=>{at.delete(u),ca(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(Qt,{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 Pt=new Map,ua=6e4;function pa({agentId:u,contextSummary:r}){const{t:m}=Rt(["terminal","common"]),[h,N]=a.useState(()=>{var M;return((M=Pt.get(u))==null?void 0:M.snapshot)??null}),[P,I]=a.useState(!1),[L,G]=a.useState(null),w=a.useRef(0);a.useEffect(()=>{const M=Pt.get(u);if(M&&Date.now()-M.fetchedAt<ua){N(M.snapshot);return}const O=++w.current;I(!0),G(null),hn(u).then(U=>{O===w.current&&(Pt.set(u,{snapshot:U,fetchedAt:Date.now()}),N(U),I(!1))}).catch(U=>{O===w.current&&(G(U.message||"Failed to load plan limits"),I(!1))})},[u]);const D=[];if(h!=null&&h.rateLimits){const M=[{key:"fiveHour",label:m("terminal:usage.currentSession"),window:h.rateLimits.fiveHour},{key:"sevenDay",label:m("terminal:usage.currentWeekAll"),window:h.rateLimits.sevenDay},{key:"sevenDayOpus",label:m("terminal:usage.currentWeekOpus"),window:h.rateLimits.sevenDayOpus},{key:"sevenDaySonnet",label:m("terminal:usage.currentWeekSonnet"),window:h.rateLimits.sevenDaySonnet}];for(const O of M)O.window&&D.push({...O,window:O.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:m("terminal:usage.limits")}),P&&!h&&e.jsxs("div",{className:"plan-limits-tooltip__muted",children:[m("common:status.loading"),"…"]}),!P&&L&&!h&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:m("terminal:usage.limitsError",{message:L})}),D.length>0?e.jsx("div",{className:"plan-limits-tooltip__gauges",children:D.map(({key:M,label:O,window:U})=>{const xe=Math.max(0,Math.min(100,U.utilization)),Z=xn(xe);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:O}),e.jsx("span",{className:"plan-limits-tooltip__gauge-percent",style:{color:Z},children:m("terminal:usage.percentUsed",{percent:Math.round(xe)})})]}),e.jsx("div",{className:"plan-limits-tooltip__bar",children:e.jsx("div",{className:"plan-limits-tooltip__bar-fill",style:{width:`${xe}%`,background:Z}})}),e.jsx("div",{className:"plan-limits-tooltip__reset",children:m("terminal:usage.resets",{time:gn(U.resetsAt)})})]},M)})}):h&&!P&&e.jsx("div",{className:"plan-limits-tooltip__muted",children:h.rateLimitsError?m("terminal:usage.limitsError",{message:h.rateLimitsError}):h.cliHint})]})}function ma({agentId:u,disabled:r,contextSummary:m,children:h}){return e.jsx(fn,{position:"top",maxWidth:320,disabled:r,className:"plan-limits-tooltip-wrapper",triggerStyle:{display:"inline-flex",alignItems:"center"},content:e.jsx(pa,{agentId:u,contextSummary:m}),children:h})}const fa=a.memo(function({className:r=""}){const{t:m}=Rt(["common"]),[h,N]=bn(),P=a.useRef(null),[I,L]=a.useState(null);a.useLayoutEffect(()=>{const w=P.current;if(!w)return;const D=w.querySelector(".view-mode-toggle__btn--active");D&&L({left:D.offsetLeft,width:D.offsetWidth})},[h]);const G=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:P,children:[I&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:I.left,width:I.width}}),wn.map(w=>e.jsxs("button",{className:`view-mode-toggle__btn ${h===w?"view-mode-toggle__btn--active":""}`,onClick:()=>G(w),title:m(`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:m(`common:viewMode.labels.${w}`)})]},w))]})}),bt=3,wt=280,qt=320,Lt=240,Yt=64,ha=["simple","chat","advanced"],ga={simple:"Simple",chat:"Chat",advanced:"Advanced"},xa={simple:"○",chat:"◐",advanced:"◉"},ba={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Kt="flat-clear-context";function wa(u){const r=u.split("/").filter(Boolean);return r.length===0?u:r.slice(-2).join("/")}function _a(u){if(u.provider==="codex"){const P=u.codexModel||"gpt-5.3-codex",I=aa[P];return{model:(I==null?void 0:I.label)||P}}if(u.provider==="opencode")return{model:u.opencodeModel||"opencode"};const r=u.model||"sonnet",m=ia[r],h=u.effort,N=h?sa[h]:void 0;return{model:(m==null?void 0:m.label)||r,effort:N==null?void 0:N.label}}function va(u,r){if(r.type==="rectangle"&&r.width&&r.height){const m=r.width/2,h=r.height/2;return u.x>=r.center.x-m&&u.x<=r.center.x+m&&u.z>=r.center.z-h&&u.z<=r.center.z+h}if(r.type==="circle"&&r.radius){const m=u.x-r.center.x,h=u.z-r.center.z;return m*m+h*h<=r.radius*r.radius}return!1}const Ca=Fn.memo(function({agentId:r,terminalViewMode:m,onTerminalViewModeChange:h,inspectorOpen:N,onToggleInspector:P,onImageClick:I,onFileClick:L,onBashClick:G,onViewMarkdown:w,onRequestClearSubordinates:D,onOpenBuilding:M,keyboard:O,canNavigateBack:U,canNavigateForward:xe,onNavigateBack:Z,onNavigateForward:be,agentInfoOpen:Ee,onToggleAgentInfo:st,onHeaderContextMenu:ae,onBuildingContextMenu:we}){var ut,pt,K,Ye;const f=Gt(r),H=tn(),_e=Wn(),Me=a.useRef(null),We=a.useRef(null),{displayedAgentId:ve,fadingOut:_t}=Hn(r),it=Gt(ve),He=!!_e.interactiveMode&&((f==null?void 0:f.provider)??"claude")==="claude"&&!!(f!=null&&f.sessionId),[J,Ue]=a.useState(!1);a.useEffect(()=>{Ue(!1)},[r]),a.useEffect(()=>{!He&&J&&Ue(!1)},[He,J]),a.useEffect(()=>{const s=We.current;if(!s)return;const l=d=>{d.button===3?(d.preventDefault(),d.stopPropagation(),Z()):d.button===4&&(d.preventDefault(),d.stopPropagation(),be())},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)}},[Z,be]),a.useEffect(()=>{const s=We.current;if(!s)return;let l=0,c=0,d=0;const Se=250,ze=600,Ke=80,he=1.5,Et=X=>{let $=X instanceof HTMLElement?X:null;for(;$&&$!==s;){const Ze=window.getComputedStyle($).overflowX;if((Ze==="auto"||Ze==="scroll")&&$.scrollWidth>$.clientWidth)return!0;$=$.parentElement}return!1},Oe=X=>{const $=Date.now();if($<d){X.preventDefault();return}if(Math.abs(X.deltaX)<=Math.abs(X.deltaY)*he){l=0;return}if(Et(X.target)){l=0;return}$-c>Se&&(l=0),c=$,l+=X.deltaX,l<=-Ke?(l=0,d=$+ze,X.preventDefault(),Z()):l>=Ke&&(l=0,d=$+ze,X.preventDefault(),be())};return s.addEventListener("wheel",Oe,{passive:!1}),()=>s.removeEventListener("wheel",Oe)},[Z,be]);const Ce=en(),se=a.useMemo(()=>{if(!f)return null;const s=new Set,l=[];for(const c of Ce.values())c.archived||c.directories.length===0||c.assignedAgentIds.includes(r)&&(s.add(c.id),l.push(c));for(const c of Ce.values())c.archived||c.directories.length===0||s.has(c.id)||va({x:f.position.x,z:f.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})))},[f,r,Ce]),{branches:ie,fetchRemote:le,fetchingDirs:lt}=Un(se),Ve=a.useMemo(()=>{var c;const s=b.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of H.values())d.type==="terminal"&&b.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name,hasUrl:!!((c=d.terminalStatus)!=null&&c.url)});return l},[r,H]),Ie=a.useMemo(()=>{var c;const s=b.getAreaForAgent(r);if(!s)return[];const l=[];for(const d of H.values())d.type==="server"&&((c=d.pm2)!=null&&c.enabled)&&b.isPositionInArea(d.position,s)&&l.push({id:d.id,name:d.name});return l},[r,H]),je=a.useMemo(()=>{const s=b.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of H.values())c.type==="database"&&c.database&&b.isPositionInArea(c.position,s)&&l.push({id:c.id,name:c.name});return l},[r,H]),Ne=Vn(),Te=a.useMemo(()=>{const s=b.getAreaForAgent(r);if(!s)return[];const l=[];for(const c of H.values())if(c.type==="tests"&&b.isPositionInArea(c.position,s)){const d=!!c.folderPath&&Ne.some(Se=>Xn(Se,c.folderPath));l.push({id:c.id,name:c.name,working:d})}return l},[r,H,Ne]),[,Q]=a.useReducer(s=>s+1,0),re=((ut=Me.current)==null?void 0:ut.search.searchMode)??!1,ke=a.useCallback(()=>{var s;(s=Me.current)==null||s.search.toggleSearch(),Q()},[]),oe=Gn(),Je=oe.isPending(Kt),[ye,Pe]=a.useState(null),q=ye?H.get(ye):null,{height:vt,onResizeStart:Ct}=qn(),{sidePanelWidth:Le,handleSidePanelResizeStart:jt}=Yn(),[Ae,rt]=a.useState(()=>Dt(S.GIT_PANEL_OPEN,!1)),[ce,ot]=a.useState(()=>Dt(S.BUILDINGS_PANEL_OPEN,!1)),[De,ct]=a.useState(!1),Nt=a.useCallback(()=>{ct(s=>{const l=!s;return l&&Kn.setEnabled(!0),l})},[]),kt=a.useCallback(()=>ct(!1),[]),yt=a.useCallback(()=>{rt(s=>{const l=!s;return ge(S.GIT_PANEL_OPEN,l),l})},[]),Xe=a.useCallback(()=>{ot(s=>{const l=!s;return ge(S.BUILDINGS_PANEL_OPEN,l),l})},[]),v=a.useCallback(()=>{rt(!1),ge(S.GIT_PANEL_OPEN,!1)},[]),de=a.useCallback(()=>{ot(!1),ge(S.BUILDINGS_PANEL_OPEN,!1)},[]),Y=Zn();a.useEffect(()=>{if(!ye)return;Ve.some(l=>l.id===ye)||Pe(null)},[ye,Ve]);const[ee,ue]=a.useState(!1),Qe=a.useRef(null);if(a.useEffect(()=>{if(!ee)return;const s=l=>{Qe.current&&!Qe.current.contains(l.target)&&ue(!1)};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[ee]),!f)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 pe=f.contextStats,et=!!pe,dt=pe?pe.totalTokens:f.contextUsed||0,Ge=pe?pe.contextWindow:f.contextLimit||2e5,Re=pe?pe.usedPercent:Math.round(dt/Ge*100),te=Math.max(0,Math.min(100,Re)),me=Math.round(te*10)/10,At=Math.round((100-te)*10)/10,V=te>=80?"#ff4a4a":te>=60?"#ff9e4a":te>=40?"#ffd700":"#4aff9e",ne=(dt/1e3).toFixed(1),tt=(Ge/1e3).toFixed(1),fe=f.cwd,qe=fe?wa(fe):null,$e=((pt=f.subordinateIds)==null?void 0:pt.length)||0,St=$e>0;return e.jsxs("div",{ref:We,className:`flat-terminal-wrapper ${Ae||ce||De?"flat-terminal-wrapper--with-side-panel":""} ${_t?"pane-fading-out":""}`,style:{"--guake-side-panel-width":`min(${Le}px, 70%)`},children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${Ee?"flat-terminal-wrapper__header-main--active":""}`,onClick:st,onContextMenu:s=>{s.preventDefault(),s.stopPropagation(),ae({x:s.clientX,y:s.clientY})},title:Ee?"Hide agent info":"Show agent info","aria-pressed":Ee,children:[e.jsx(nn,{agent:f,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:f.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:an(f.status)},children:f.status})]}),f.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:f.taskLabel,children:["📋 ",f.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:f.provider==="codex"?"/assets/codex.png":f.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:f.provider,className:"flat-terminal-wrapper__header-provider-icon",title:f.provider==="codex"?"Codex Agent":f.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:s,effort:l}=_a(f);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:[ha.map(s=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${!J&&m===s?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>{Ue(!1),h(s)},title:ba[s],"aria-pressed":!J&&m===s,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:xa[s]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:ga[s]})]},s)),He&&e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${J?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>Ue(s=>!s),title:"Classic TUI — attach to the live interactive claude session in a terminal","aria-pressed":J,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:Z,disabled:!U,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:be,disabled:!xe,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 ${re?"flat-terminal-wrapper__action-btn--active":""}`,onClick:ke,title:re?"Close search":"Search messages","aria-pressed":re,children:e.jsx(p,{name:re?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${Je?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>oe.handleClick(Kt,()=>{var s;b.clearContext(r),(s=Me.current)==null||s.historyLoader.clearHistory()}),title:Je?"Click again to confirm clear context":"Clear context",children:e.jsx(p,{name:Je?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${Ae?"flat-terminal-wrapper__action-btn--active":""}`,onClick:yt,title:Ae?"Hide git panel":"Show git changes","aria-pressed":Ae,children:e.jsx(p,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ce?"flat-terminal-wrapper__action-btn--active":""}`,onClick:Xe,title:ce?"Hide buildings panel":"Show area buildings","aria-pressed":ce,children:e.jsx(p,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:Qe,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ee?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>ue(s=>!s),title:"More actions","aria-expanded":ee,children:"⋮"}),ee&&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 ${De?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{Nt(),ue(!1)},title:De?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(p,{name:"bug",size:14}),e.jsx("span",{children:De?"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:()=>{b.collapseContext(r),ue(!1)},disabled:f.status!=="idle",title:f.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"})]}),St&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{D(r,$e),ue(!1)},children:[e.jsx(p,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",$e," subordinate",$e===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:()=>{b.killAgent(r),ue(!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:P,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:()=>b.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(p,{name:"cross",size:14})})]})]}),J&&He?e.jsx(da,{agentId:r}):ve&&it?e.jsx(Jn,{ref:Me,agentId:ve,agent:it,viewMode:m,isOpen:!0,onImageClick:I,onFileClick:L,onBashClick:G,onViewMarkdown:w,keyboard:O,hasModalOpen:!1},ve):null,q&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:Ct,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${q.name}`,style:{height:vt},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:q.name}),!((K=q.terminalStatus)!=null&&K.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>Pe(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:(Ye=q.terminalStatus)!=null&&Ye.url?e.jsx(Qt,{terminalUrl:q.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:[f.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"})]}),fe&&qe&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${fe}`,"aria-label":`Open ${fe} in file explorer`,role:"button",tabIndex:0,onClick:()=>b.openFileExplorer(fe),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),b.openFileExplorer(fe))},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:qe})]}),se&&se.map(({areaId:s,areaName:l,dir:c})=>{const d=ie.get(c),Se=lt.has(c),ze=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:()=>b.openFileExplorerForAreaFolder(s,c),children:[e.jsx(p,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:ze}),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 ${Se?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Ke=>{Ke.stopPropagation(),le(c)},children:e.jsx(p,{name:Se?"hourglass":"download",size:12})})]})]},`${s}:${c}`)}),e.jsx(ma,{agentId:r,disabled:((f==null?void 0:f.provider)??"claude")!=="claude",contextSummary:et?`Context: ${ne}k / ${tt}k tokens (${me}% used)`:void 0,children:e.jsxs("span",{className:"flat-terminal-wrapper__context",tabIndex:0,role:"button",onClick:()=>b.setContextModalAgentId(r),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),b.setContextModalAgentId(r))},title:((f==null?void 0:f.provider)??"claude")!=="claude"?et?`Context usage: ${ne}k / ${tt}k tokens (${me}% 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:`${te}%`,backgroundColor:V}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:V},children:[ne,"k/",tt,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",At,"% free)"]}),!et&&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"}),Ve.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:Ve.map(s=>{const l=ye===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){Pe(null);return}s.hasUrl||b.sendBuildingCommand(s.id,"start"),Pe(s.id)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),we(s.id,{x:c.clientX,y:c.clientY})},children:e.jsx(p,{name:"terminal",size:14})},s.id)})}),Ie.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:Ie.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${s.name}`,onClick:()=>M(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"scroll",size:14})},s.id))}),je.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:je.map(s=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${s.name}`,onClick:()=>M(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(s.id,{x:l.clientX,y:l.clientY})},children:e.jsx(p,{name:"hard-drives",size:14})},s.id))}),Te.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area tests",children:Te.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:()=>M(s.id),onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),we(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(Qn,{})})]}),Ae&&e.jsx(ea,{agentId:r,agents:Y,onClose:v,branchInfoMap:ie,fetchRemote:le,fetchingDirs:lt,onResizeStart:s=>jt(s,"right")}),ce&&e.jsx(ta,{agentId:r,onClose:de}),De&&e.jsx(na,{agentId:r,onClose:kt})]})});function Aa({onAgentClick:u,onBuildingClick:r,onBuildingDoubleClick:m,onBuildingPopup:h,onAreaContextMenu:N,onOpenSpawnModal:P,onOpenBossSpawnModal:I,onOpenAreaModal:L}){const{t:G}=Rt(["common"]),w=_n(),D=vn(),[M,O]=a.useState(null),[U,xe]=a.useState(null),[Z,be]=a.useState(null);Cn("flatview-image-modal",M!==null,()=>O(null));const[Ee,st]=a.useState(null),[ae,we]=a.useState(null),[f,H]=a.useState(null),[_e,Me]=a.useState(null),[We,ve]=a.useState(!1),_t=a.useCallback(()=>{ve(t=>!t)},[]),it=a.useCallback(()=>{ve(!1)},[]),[He,J]=a.useState(()=>{const t=Ft(S.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Ue=a.useCallback(t=>{J(t),Wt(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")&&J(i)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[Ce,se]=a.useState(()=>Dt(S.FLAT_INSPECTOR_OPEN,!1)),[ie,le]=a.useState(!1),lt=a.useCallback(()=>le(t=>!t),[]),Ve=a.useCallback(()=>le(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:ie}}))},[ie]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:Ce}}))},[Ce]),a.useEffect(()=>{const t=()=>le(C=>!C),n=()=>{se(C=>{const k=!C;return ge(S.FLAT_INSPECTOR_OPEN,k),k})},i=()=>{le(!1),se(!1),ge(S.FLAT_INSPECTOR_OPEN,!1)},g=()=>le(!1),x=()=>{se(!1),ge(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 Ie=a.useRef(null),je=a.useRef(null),[Ne,Te]=a.useState(()=>{const t=Ht(S.FLAT_MIDDLE_WIDTH,0);return t>=wt?t:null}),[Q,re]=a.useState(()=>{const t=Ht(S.FLAT_INSPECTOR_WIDTH,0);return t>=Lt?t:null}),ke=a.useCallback(t=>{if(typeof window>"u")return t;const n=Q!==null?bt+Q:0,i=window.innerWidth-Yt-bt-qt-n;return Math.max(wt,Math.min(Math.max(i,wt),t))},[Q]),oe=a.useCallback(t=>{var x;if(typeof window>"u")return t;const n=(x=Ie.current)==null?void 0:x.querySelector(".flat-middle"),i=(n==null?void 0:n.getBoundingClientRect().width)??wt,g=window.innerWidth-Yt-i-bt-qt-bt;return Math.max(Lt,Math.min(Math.max(g,Lt),t))},[]);a.useEffect(()=>{if(Ne===null&&Q===null)return;const t=()=>{Te(n=>{if(n===null)return n;const i=ke(n);return i===n?n:i}),re(n=>{if(n===null)return n;const i=oe(n);return i===n?n:i})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[Ne,Q,ke,oe]);const Je=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=Ie.current)==null?void 0:i.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),je.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),ye=a.useCallback(t=>{var i;if(t.button!==0)return;const n=(i=Ie.current)==null?void 0:i.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),je.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),Pe=a.useCallback(t=>{const n=je.current;if(!n||t.pointerId!==n.pointerId)return;const i=t.clientX-n.startX;n.kind==="middle"?Te(ke(n.startWidth+i)):re(oe(n.startWidth-i))},[ke,oe]),q=a.useCallback(t=>{const n=je.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(je.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=ke(n.startWidth+g);Te(x),xt(S.FLAT_MIDDLE_WIDTH,x)}else{const x=oe(n.startWidth-g);re(x),xt(S.FLAT_INSPECTOR_WIDTH,x)}},[ke,oe]),vt=a.useCallback(()=>{Te(null),xt(S.FLAT_MIDDLE_WIDTH,0)},[]),Ct=a.useCallback(()=>{re(null),xt(S.FLAT_INSPECTOR_WIDTH,0)},[]),[Le,jt]=a.useState(()=>Ft(S.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Ae=a.useCallback(t=>{jt(t),Wt(S.FLAT_INSPECTOR_VIEW,t)},[]),rt=a.useCallback(()=>{se(t=>{const n=!t;return ge(S.FLAT_INSPECTOR_OPEN,n),n})},[]),ce=a.useCallback(()=>{se(!1),ge(S.FLAT_INSPECTOR_OPEN,!1)},[]),ot=jn(),De=a.useCallback((t,n)=>{O({url:t,name:n})},[]),ct=a.useCallback((t,n)=>{xe({command:t,output:n,isLive:!1})},[]),Nt=a.useCallback((t,n)=>{var x;const i=D.size>0?Array.from(D)[0]:null,g=i?(x=b.getState().agents.get(i))==null?void 0:x.cwd:void 0;b.setFileViewerPath(t,n,g)},[D]),kt=a.useCallback(t=>{be(t)},[]),yt=a.useCallback((t,n)=>{st({agentId:t,count:n})},[]),Xe=a.useCallback(t=>{m?m(t):r(t)},[r,m]),v=a.useMemo(()=>D.size>0?Array.from(D)[0]:null,[D]);a.useEffect(()=>{ve(!1)},[v]);const de=a.useRef([]),Y=a.useRef(-1),ee=a.useRef(!1),ue=a.useRef(null),[Qe,pe]=a.useState(!1),[et,dt]=a.useState(!1),Ge=a.useRef(!1),Re=a.useRef(null),te=a.useRef(!1),me=a.useMemo(()=>new Set(w.map(t=>t.id)),[w]),At=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]),V=a.useCallback(()=>{const t=de.current,n=Y.current;pe(n>0),dt(n>=0&&n<t.length-1)},[]),ne=a.useCallback(t=>{const n=de.current;if(n.length===0)return;let i=Y.current+t;for(;i>=0&&i<n.length;){const g=n[i];if(me.has(g)){ee.current=!0,Y.current=i,V(),b.selectAgent(g);return}i+=t}},[me,V]),tt=a.useCallback(()=>ne(-1),[ne]),fe=a.useCallback(()=>ne(1),[ne]);ra(a.useCallback(()=>{const t=de.current,n=Y.current;return t.length>0&&n>0?(ne(-1),"handled"):"exit"},[ne]));const qe=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(!v){Ge.current=!1,Re.current=null;return}if(!Ge.current){qe(v,"replace"),Ge.current=!0,Re.current=v;return}if(te.current){te.current=!1,Re.current=v;return}Re.current!==v&&(qe(v,"push"),Re.current=v)},[v,qe]),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"||!me.has(i)||i===v)return;te.current=!0,ee.current=!0;const g=de.current,x=g.lastIndexOf(i);x>=0?Y.current=x:(g.push(i),Y.current=g.length-1),V(),b.selectAgent(i)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[me,v,V]),a.useEffect(()=>{if(!v){de.current=[],Y.current=-1,V();return}if(ue.current=v,ee.current){ee.current=!1,V();return}const t=de.current,n=Y.current;if(n>=0&&t[n]===v){V();return}const i=n<t.length-1?t.slice(0,n+1):t.slice();i.push(v),i.length>100&&i.shift(),de.current=i,Y.current=i.length-1,V()},[v,V]);const $e=a.useCallback(t=>{u(t),le(!1)},[u]),St=v??"",ut=a.useCallback(()=>{},[]),pt=a.useCallback(t=>{$e(t)},[$e]),K=Ce,[Ye,s]=a.useState(K),[l,c]=a.useState(K);a.useEffect(()=>{if(K){s(!0);return}c(!1);const t=setTimeout(()=>s(!1),240);return()=>clearTimeout(t)},[K]),a.useEffect(()=>{if(!Ye||!K)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>c(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[Ye,K]);const d=a.useRef(null);a.useEffect(()=>{if(v)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=ue.current;!g||!me.has(g)||(n.preventDefault(),b.selectAgent(g))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[v,me]);const[Se,ze]=a.useState(new Set),Ke=a.useCallback(t=>{ze(n=>{const i=new Set(n);return i.has(t)?i.delete(t):i.add(t),i})},[]),[he,Et]=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=>Et(i.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[Oe,X]=a.useState(null),$=a.useCallback(t=>{X(n=>n===t?null:t)},[]),Ze=en(),mt=tn(),[sn]=Nn(),Be=a.useMemo(()=>{const t=new Map,n=[];for(const _ of w){const A=b.getAreaForAgent(_.id);if(!Ut((A==null?void 0:A.id)??null))continue;if(!A||A.archived){n.push(_);continue}const E=t.get(A.id);E?E.push(_):t.set(A.id,[_])}const i=new Map,g=[];for(const _ of mt.values()){let A=!1;for(const E of Ze.values())if(!E.archived&&Vt(E.id)&&b.isPositionInArea(_.position,E)){const B=i.get(E.id);B?B.push(_):i.set(E.id,[_]),A=!0;break}!A&&Ut(null)&&g.push(_)}const x=[];for(const[,_]of Ze){if(_.archived||!Vt(_.id))continue;const A=t.get(_.id),E=i.get(_.id)??[];(A&&A.length>0||E.length>0)&&x.push({area:_,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(_=>_.area.id!=="__unassigned__"),k=x.filter(_=>_.area.id==="__unassigned__");let o=1,y=1;const z=new Map;if(C.length>1){let _=1/0,A=-1/0,E=1/0,B=-1/0;for(const F of C)_=Math.min(_,F.area.center.x),A=Math.max(A,F.area.center.x),E=Math.min(E,F.area.center.z),B=Math.max(B,F.area.center.z);const ft=A-_||1,ht=B-E||1;if(C.length<=4){o=C.length,y=1;const F=[...C].sort((W,Mt)=>W.area.center.x-Mt.area.center.x);for(let W=0;W<F.length;W++)z.set(F[W].area.id,{row:1,col:W+1})}else{const F=[...C].sort((j,R)=>j.area.center.x-R.area.center.x),W=[];for(let j=1;j<F.length;j++)W.push(F[j].area.center.x-F[j-1].area.center.x);const Mt=W.reduce((j,R)=>j+R,0)/W.length||1;let $t=1;for(const j of W)j>Mt*1.3&&$t++;o=Math.max(2,Math.min($t,C.length));const It=[...C].sort((j,R)=>j.area.center.z-R.area.center.z),gt=[];for(let j=1;j<It.length;j++)gt.push(It[j].area.center.z-It[j-1].area.center.z);const cn=gt.reduce((j,R)=>j+R,0)/gt.length||1;let zt=1;for(const j of gt)j>cn*1.3&&zt++;y=Math.max(2,Math.min(zt,C.length)),o=Math.max(o,Math.ceil(C.length/y)),y=Math.max(y,Math.ceil(C.length/o));const dn=ft/o,un=ht/y,Tt=new Set;for(const j of C){let R=Math.min(o-1,Math.max(0,Math.floor((j.area.center.x-_)/dn))),Fe=Math.min(y-1,Math.max(0,Math.floor((j.area.center.z-E)/un))),nt=`${Fe},${R}`,Ot=0;const pn=y*o;for(;Tt.has(nt)&&Ot<pn;)R++,R>=o&&(R=0,Fe=(Fe+1)%y),nt=`${Fe},${R}`,Ot++;Tt.has(nt)&&(Fe=y,R=0,nt=`${Fe},${R}`,y++),Tt.add(nt),z.set(j.area.id,{row:Fe+1,col:R+1})}}}const T=_=>{_.sort((A,E)=>{var ft,ht,F,W;const B=(((ft=A.position)==null?void 0:ft.z)??0)-(((ht=E.position)==null?void 0:ht.z)??0);return B!==0?B:(((F=A.position)==null?void 0:F.x)??0)-(((W=E.position)==null?void 0:W.x)??0)})};for(const _ of C)T(_.agents);for(const _ of k)T(_.agents);return{groups:[...C,...k],gridCols:o,gridRows:y,positions:z}},[w,Ze,mt,sn]),ln=a.useMemo(()=>{if(!ae)return[];const t=w.find(n=>n.id===ae.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:()=>b.cloneAgent(t.id)},{id:"fork-agent",label:"Fork Agent (with history)",icon:e.jsx(p,{name:"git-branch",size:14}),onClick:()=>b.forkAgent(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(p,{name:"trash",size:14}),danger:!0,onClick:()=>{Me({agentId:t.id,name:t.name})}}]:[]},[ae,w,u]),rn=a.useMemo(()=>{var C;if(!f)return[];const t=mt.get(f.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:()=>Xe(t.id)}),i&&(g||n.push({id:"start",label:"Start",icon:e.jsx(p,{name:"play",size:14}),onClick:()=>b.sendBuildingCommand(t.id,"start")}),g&&(n.push({id:"restart",label:"Restart",icon:e.jsx(p,{name:"refresh",size:14}),onClick:()=>b.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(p,{name:"stop",size:14}),onClick:()=>b.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)b.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)b.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)b.sendBuildingCommand(k,"restart")}})),i&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(p,{name:"health",size:14}),onClick:()=>b.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:()=>{b.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:()=>b.deleteBuilding(t.id)}),n},[f,mt,Xe]),on=a.useCallback(t=>{const n=new Set(Be.groups.map(i=>i.area.id));n.delete(t),ze(n),requestAnimationFrame(()=>{const i=d.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"})})},[Be]);return e.jsxs("div",{ref:Ie,className:`flat-view ${K?"flat-view--with-inspector":""} ${v?"flat-view--has-chat":""} ${ie?"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:[ie&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:Ve,"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:P,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:I,title:"Create new boss agent",children:"+ Boss"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--area",onClick:L,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(kn,{activeAgentId:St,onClose:ut,onSelectAgent:pt,collapsedAreas:Se,onToggleArea:Ke,agentListRef:d})})]}),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:Je,onPointerMove:Pe,onPointerUp:q,onPointerCancel:q,onDoubleClick:vt}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":ie?"Close agents sidebar":"Open agents sidebar","aria-expanded":ie,onClick:lt,children:[e.jsx(p,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),v?e.jsx(Ca,{agentId:v,terminalViewMode:He,onTerminalViewModeChange:Ue,inspectorOpen:Ce,onToggleInspector:rt,onImageClick:De,onFileClick:Nt,onBashClick:ct,onViewMarkdown:kt,onRequestClearSubordinates:yt,onOpenBuilding:Xe,keyboard:ot,canNavigateBack:Qe,canNavigateForward:et,onNavigateBack:tt,onNavigateForward:fe,agentInfoOpen:We,onToggleAgentInfo:_t,onHeaderContextMenu:t=>{v&&we({agentId:v,position:t})},onBuildingContextMenu:(t,n)=>{H({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(fa,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Be.gridCols}, 1fr)`},children:Be.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=he&&Oe?((n=Be.positions.get(Oe))==null?void 0:n.row)??null:null;return Be.groups.map(i=>{var k;const g=i.area.id,x=Be.positions.get(g),C=he&&Oe!==g;return he&&t!=null&&(x==null?void 0:x.row)===t&&g!==Oe?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:la(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:()=>he?$(g):on(g),title:he?C?`Expand ${i.area.name}`:`Collapse ${i.area.name}`:`Focus ${i.area.name} in left panel`,"aria-expanded":he?!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}),he&&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",z=y?At.get(o.id):void 0,T=yn(o),_=T.usedPercent>=80?"#ff4a4a":T.usedPercent>=60?"#ff9e4a":T.usedPercent>=40?"#ffd700":"#4aff9e",A=`Context: ${(T.totalTokens/1e3).toFixed(1)}k / ${(T.contextWindow/1e3).toFixed(1)}k (${T.usedPercent}% used, ${T.freePercent}% free)`,E=o.latestTodos&&o.latestTodos.length>0||z&&z.length>0;return e.jsx(An,{todos:o.latestTodos,subordinates:z,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${o.status}`,onClick:()=>u(o.id),onContextMenu:B=>{B.preventDefault(),B.stopPropagation(),we({agentId:o.id,position:{x:B.clientX,y:B.clientY}})},title:E?void 0:`${y?"Boss · ":""}Open chat with ${o.name}
2
+ ${A}`,children:[e.jsx(nn,{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:an(o.status)}}),o.latestTodos&&o.latestTodos.length>0&&e.jsx(Sn,{todos:o.latestTodos,maxDots:6}),y&&z&&z.length>0&&e.jsx(En,{subordinates:z,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:`${T.usedPercent}%`,backgroundColor:_}})})]})},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:z=>{z.stopPropagation(),b.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 z;const y=(z=Mn[o.type])==null?void 0:z.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:T=>{if(h){const _=T.currentTarget.getBoundingClientRect();h(o.id,{x:_.right,y:_.top+_.height/2})}else Xe(o.id)},onContextMenu:T=>{T.preventDefault(),T.stopPropagation(),H({buildingId:o.id,position:{x:T.clientX,y:T.clientY}})},title:`${o.name} · ${o.type} · ${o.status}`,children:[e.jsx(p,{name:In(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:Tn(o.status)}})]},o.id)})})]},g)})})()})]})})]}),K&&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:ye,onPointerMove:Pe,onPointerUp:q,onPointerCancel:q,onDoubleClick:Ct}),Ye&&e.jsxs("aside",{className:`flat-inspector ${l?"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":Le==="agent",className:`flat-inspector__tab ${Le==="agent"?"flat-inspector__tab--active":""}`,onClick:()=>Ae("agent"),children:"Agent"}),e.jsx("button",{type:"button",role:"tab","aria-selected":Le==="tracking",className:`flat-inspector__tab ${Le==="tracking"?"flat-inspector__tab--active":""}`,onClick:()=>Ae("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:ce,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:Le==="tracking"?e.jsx(Pn,{activeAgentId:v??"",onSelectAgent:t=>{u(t),window.innerWidth<=768&&ce()}}):(()=>{if(!v)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===v);return t?e.jsx(Ln,{agent:t,onFocusAgent:n=>{u(n),window.innerWidth<=768&&ce()},onKillAgent:n=>b.killAgent(n)}):e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Agent not found"})})})()})]}),M&&e.jsx(Dn,{url:M.url,name:M.name,onClose:()=>O(null)}),U&&e.jsx(Rn,{state:U,onClose:()=>xe(null)}),e.jsx($n,{agent:v?w.find(t=>t.id===v)??null:null,content:Z,onClose:()=>be(null)}),Ee&&e.jsx(zn,{action:"clear-subordinates",selectedAgentId:Ee.agentId,subordinateCount:Ee.count,onClose:()=>st(null),onClearHistory:()=>{}}),e.jsx(On,{agent:v?w.find(t=>t.id===v)??null:null,isOpen:We&&!!v,onClose:it}),e.jsx(Xt,{isOpen:ae!==null,position:(ae==null?void 0:ae.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:ln,onClose:()=>we(null)}),e.jsx(Xt,{isOpen:f!==null,position:(f==null?void 0:f.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:rn,onClose:()=>H(null)}),e.jsx(Bn,{isOpen:_e!==null,title:G("common:confirm.removeAgentTitle"),message:G("common:confirm.removeAgentMessage",{name:(_e==null?void 0:_e.name)??""}),confirmLabel:G("common:buttons.remove"),cancelLabel:G("common:buttons.cancel"),variant:"danger",onConfirm:()=>{_e&&b.removeAgentFromServer(_e.agentId)},onClose:()=>Me(null)})]})}export{Aa as FlatView};
@@ -0,0 +1 @@
1
+ import{r as l,b5 as Ue,b6 as Je,j as e,I as P,u as Z,b7 as ns,ac as is,f as Ke,s as _,b8 as ms,b9 as gs,a_ as fs,ba as xs,C as he,G as se,H as X,h as ye,i as ke,bb as bs,bc as js,bd as vs,be as ws,bf as Ns,bg as ys,P as ks,bh as Ce,a7 as Cs,bi as os,bj as Ss,bk as Ve,bl as As,bm as Ts,bn as _s,bo as Is,bp as Es,bq as Ps,br as Ls,aU as $s,X as Ds,S as Ne,bs as Fs,bt as Os,aW as Rs,bu as ze,Y as Ee,b2 as Us,bv as Me,bw as zs}from"./main-CAmYbJhQ.js";import{g as Ms,d as Bs,u as Vs}from"./area-logos-N2igqdil.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const He="deivid11/tide-commander",Ks=`https://api.github.com/repos/${He}/releases/latest`,Hs=`https://api.github.com/repos/${He}/releases?per_page=3`,qs=3600*1e3,Ze="app_update_dismissed_version",Xe="1.140.0";function Ws(){var y,S;const[s,a]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Xe}),t=((S=(y=Ue)==null?void 0:y.getPlatform)==null?void 0:S.call(y))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(x=>parseInt(x,10)||0),d=(u,f)=>{const x=o(u),h=o(f),g=Math.max(x.length,h.length);for(let p=0;p<g;p++){const A=x[p]||0,M=h[p]||0;if(A>M)return 1;if(A<M)return-1}return 0},r=async u=>{var x,h;if(Ue&&Je&&((h=(x=Ue).isNativePlatform)==null?void 0:h.call(x))===!0){const g=await Je.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:g.data,status:g.status}}else{const g=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return g.ok?{data:await g.json(),status:g.status}:{data:null,status:g.status}}},c=l.useCallback(async(u=!1)=>{a(f=>({...f,isChecking:!0,error:null}));try{const[f,x]=await Promise.all([r(Ks),r(Hs)]);if(f.status!==200)throw new Error(`GitHub API error: ${f.status}`);const h=f.data,g=h.tag_name;let p=[];x.status===200&&x.data&&(p=x.data.map(v=>({version:v.tag_name,name:v.name,publishedAt:v.published_at,releaseUrl:v.html_url})));const A=localStorage.getItem(Ze);if(!u&&A===g)return a(v=>({...v,isChecking:!1,updateAvailable:!1,recentReleases:p})),null;if(!(d(g,Xe)>0))return a(v=>({...v,isChecking:!1,updateAvailable:!1,recentReleases:p})),null;const F=h.assets.find(v=>v.name.endsWith(".apk")&&v.content_type==="application/vnd.android.package-archive"),H={version:g,name:h.name,changelog:h.body,releaseUrl:h.html_url,apkUrl:(F==null?void 0:F.browser_download_url)||null,apkSize:(F==null?void 0:F.size)||null,publishedAt:h.published_at};return a(v=>({...v,isChecking:!1,updateAvailable:!0,updateInfo:H,recentReleases:p})),H}catch(f){const x=f instanceof Error?f.message:"Failed to check for updates";return a(h=>({...h,isChecking:!1,error:x})),null}},[]),b=l.useCallback(async()=>{var u,f,x;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(f=s.updateInfo)!=null&&f.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(x=s.updateInfo)!=null&&x.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),a(h=>({...h,error:null}))}catch(h){const g=h instanceof Error?h.message:"Failed to open download";a(p=>({...p,error:g}))}},[s.updateInfo,t]),i=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Ze,s.updateInfo.version),a(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),j=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${He}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),f=setInterval(()=>{c()},qs);return()=>{clearTimeout(u),clearInterval(f)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:b,dismissUpdate:i,openReleasePage:j}}const ls="tide-toolbox-collapse";function Gs(s,a){try{const t=localStorage.getItem(`${ls}-${s}`);if(t!==null)return t==="true"}catch{}return a}function Ys(s,a){try{localStorage.setItem(`${ls}-${s}`,String(a))}catch{}}function G({title:s,storageKey:a,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,b]=l.useState(()=>a?Gs(a,t):t),i=()=>{const y=!c;b(y),a&&Ys(a,y)},j=o||c;return e.jsxs("div",{className:`collapsible-section ${j?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:i,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(P,{name:j?"caret-down":"caret-right",size:10})})]})]}),j&&e.jsx("div",{className:"collapsible-content",children:d})]})}function Js({area:s,isSelected:a,onClick:t,onDelete:o}){const{t:d}=Z(["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 ${a?"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 Zs({building:s,isSelected:a,onClick:t,onEdit:o}){var b;const{t:d}=Z(["config"]),r=((b=s.pm2Status)==null?void 0:b.ports)||[],c=(i,j)=>{i.stopPropagation(),window.open(`http://${window.location.hostname}:${j}`,"_blank")};return e.jsxs("div",{className:`building-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:ns[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(P,{name:is(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(i=>e.jsxs("a",{href:`http://${window.location.hostname}:${i}`,className:"building-port-link",onClick:j=>c(j,i),title:`Open :${i}`,children:[":",i]},i))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:i=>{i.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx(P,{name:"gear",size:14})})]})}function Xs({building:s,onClose:a,onOpenModal:t}){var j,y,S,u,f,x,h,g;const{t:o}=Z(["config","common"]),{buildingLogs:d}=Ke(),r=_.getBuildingLogs(s.id),c=ms[s.style||"server-rack"],b=p=>{_.sendBuildingCommand(s.id,p)},i=p=>{window.open(p,"_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(P,{name:is(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:ns[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:a,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:()=>b("start"),disabled:!((j=s.commands)!=null&&j.start)||s.status==="running",title:((y=s.commands)==null?void 0:y.start)||o("config:buildings.noStartCommand"),children:[e.jsx(P,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>b("stop"),disabled:!((S=s.commands)!=null&&S.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx(P,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>b("restart"),disabled:!((f=s.commands)!=null&&f.restart),title:((x=s.commands)==null?void 0:x.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx(P,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>b("healthCheck"),disabled:!((h=s.commands)!=null&&h.healthCheck),title:((g=s.commands)==null?void 0:g.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx(P,{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((p,A)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>i(p.url),title:p.url,children:[e.jsx(P,{name:"link",size:12})," ",p.label||p.url]},A))})]}),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:()=>_.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((p,A)=>e.jsx("div",{className:"building-editor-log-entry",children:p},A))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx(P,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const Qs=[{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 et({area:s,onClose:a,onOpenFolder:t}){var te;const{t:o}=Z(["config","common"]),[d,r]=l.useState(s.name),[c,b]=l.useState(s.prompt||""),[i,j]=l.useState(!1),[y,S]=l.useState(""),[u,f]=l.useState(!1),x=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{b(s.prompt||"")},[s.id,s.prompt]);const h=N=>{const $=N.target.value;r($),_.updateArea(s.id,{name:$})},g=N=>{_.updateArea(s.id,{color:N})},p=N=>{const $=N.target.value;b($),_.updateArea(s.id,{prompt:$})},A=()=>{y.trim()&&(_.addDirectoryToArea(s.id,y.trim()),S(""),j(!1))},M=(N,$)=>{$.stopPropagation(),_.removeDirectoryFromArea(s.id,N)},F=()=>{_.bringAreaToFront(s.id)},H=()=>{_.sendAreaToBack(s.id)},v=l.useCallback(()=>{let N=2,$=2;s.type==="rectangle"&&s.width&&s.height?(N=s.width,$=s.height):s.type==="circle"&&s.radius&&(N=s.radius*1.414,$=s.radius*1.414);const V=Math.min(N,$)*.4;return{width:Math.round(V*10)/10,height:Math.round(V*10)/10}},[s.type,s.width,s.height,s.radius]),U=async N=>{var V;const $=(V=N.target.files)==null?void 0:V[0];if($){f(!0);try{const w=await Vs(s.id,$),L=v();_.updateArea(s.id,{logo:{filename:w.filename,position:"center",width:L.width,height:L.height,keepAspectRatio:!0,opacity:.8}})}catch(w){console.error("Failed to upload logo:",w)}finally{f(!1),x.current&&(x.current.value="")}}},B=async()=>{try{await Bs(s.id),_.updateArea(s.id,{logo:void 0})}catch(N){console.error("Failed to remove logo:",N)}},W=N=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,position:N}})},k=N=>{if(!s.logo)return;const $=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const V=s.logo.height/s.logo.width;_.updateArea(s.id,{logo:{...s.logo,width:$,height:Math.round($*V*10)/10}})}else _.updateArea(s.id,{logo:{...s.logo,width:$}})},O=N=>{if(!s.logo)return;const $=parseFloat(N.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const V=s.logo.width/s.logo.height;_.updateArea(s.id,{logo:{...s.logo,height:$,width:Math.round($*V*10)/10}})}else _.updateArea(s.id,{logo:{...s.logo,height:$}})},K=()=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},q=N=>{s.logo&&_.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:a,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:h,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:gs.map(N=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===N?"selected":""}`,style:{backgroundColor:N},onClick:()=>g(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:F,title:o("config:areas.bringToFront"),children:[e.jsx(P,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:H,title:o("config:areas.sendToBack"),children:[e.jsx(P,{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:[(te=s.logo)!=null&&te.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:Ms(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:B,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var N;return(N=x.current)==null?void 0:N.click()},disabled:u,children:u?"...":e.jsx(P,{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:Qs.map(({key:N,labelKey:$})=>{var V;return e.jsx("button",{className:`area-logo-pos-btn ${((V=s.logo)==null?void 0:V.position)===N?"active":""}`,onClick:()=>W(N),children:o(`config:areas.${$}`)},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:k,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:O,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:K}),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:q,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=x.current)==null?void 0:N.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:x,type:"file",accept:"image/*",style:{display:"none"},onChange:U})]})]}),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(P,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:N.split("/").pop()||N}),e.jsx("button",{className:"area-folder-remove",onClick:$=>M(N,$),title:o("config:areas.removeFolder"),children:"×"})]},N)),i?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(fs,{value:y,onChange:S,onSubmit:A,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:A,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>j(!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:p,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 st(){const{t:s}=Z(["config","common"]),a=xs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,b]=l.useState({name:"",key:"",value:"",description:""}),[i,j]=l.useState(null),y=()=>{o(!0),r(null),b({name:"",key:"",value:"",description:""})},S=p=>{r(p.id),o(!1),b({name:p.name,key:p.key,value:p.value,description:p.description||""})},u=()=>{o(!1),r(null),b({name:"",key:"",value:"",description:""})},f=()=>{!c.name.trim()||!c.key.trim()||(d?_.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}):_.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())},x=p=>{j(p)},h=()=>{i&&(_.deleteSecret(i),d===i&&u())},g=p=>{navigator.clipboard.writeText(`{{${p}}}`)};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:a.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):a.map(p=>e.jsxs("div",{className:`secret-item ${d===p.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:p.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>g(p.key),title:s("config:secrets.copyPlaceholder"),children:`{{${p.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>S(p),title:s("common:buttons.edit"),children:e.jsx(P,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>x(p.id),title:s("common:buttons.delete"),children:"×"})]})]}),p.description&&e.jsx("div",{className:"secret-item-description",children:p.description})]},p.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:p=>b({...c,name:p.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:p=>b({...c,key:p.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:p=>b({...c,value:p.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:p=>b({...c,description:p.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:f,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:i!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:h,onClose:()=>j(null)})]})}async function tt(){const s=se(),a=await fetch(`${X()}/api/agents/system-settings/prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch system prompt: ${a.statusText}`);return(await a.json()).prompt||""}async function at(s){const a=se(),t=await fetch(`${X()}/api/agents/system-settings/prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({prompt:s})});if(!t.ok)throw new Error(`Failed to update system prompt: ${t.statusText}`)}async function nt(){const s=se(),a=await fetch(`${X()}/api/agents/system-settings/prompt`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to clear system prompt: ${a.statusText}`)}async function it(){const s=se(),a=await fetch(`${X()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch echo prompt setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function ot(s){const a=se(),t=await fetch(`${X()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function lt(){const s=se(),a=await fetch(`${X()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch codex binary path: ${a.statusText}`);return(await a.json()).path||""}async function ct(s){const a=se(),t=await fetch(`${X()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function rt(){const s=se(),a=await fetch(`${X()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch tmux mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function dt(s){const a=se(),t=await fetch(`${X()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function ut(){const s=se(),a=await fetch(`${X()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch interactive mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function pt(s){const a=se(),t=await fetch(`${X()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function ht(){const s=se(),a=await fetch(`${X()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch backup status: ${a.statusText}`);return a.json()}async function mt(s){const a=se(),t=await fetch(`${X()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},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 gt({checked:s,onChange:a,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=>a(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function ft(){const{t:s}=Z(["config","common"]),[a,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[b,i]=l.useState(!1),[j,y]=l.useState(!1),[S,u]=l.useState(null),[f,x]=l.useState(null),[h,g]=l.useState(null),[p,A]=l.useState(null),[M,F]=l.useState(!1),[H,v]=l.useState(null);l.useEffect(()=>{ye(ke("/api/config/categories")).then(w=>w.json()).then(w=>{const L=Array.isArray(w)?w:[];t(L),d(new Set(L.map(D=>D.id)))}).catch(w=>console.error("Failed to fetch config categories:",w))},[]),l.useEffect(()=>{ht().then(A).catch(w=>{console.error("Failed to fetch backup status:",w),v(w.message||"Failed to fetch backup status")})},[]);const U=async w=>{if(!M){F(!0),v(null);try{const L=await mt(w);A(L)}catch(L){v(L.message||"Failed to update backup setting")}finally{F(!1)}}},B=w=>{d(L=>{const D=new Set(L);return D.has(w)?D.delete(w):D.add(w),D})},W=w=>{c(L=>{const D=new Set(L);return D.has(w)?D.delete(w):D.add(w),D})},k=()=>d(new Set(a.map(w=>w.id))),O=()=>d(new Set),K=()=>{f&&c(new Set(f.categories.map(w=>w.id)))},q=()=>c(new Set),te=async()=>{var w;if(o.size!==0){i(!0),g(null);try{const L=Array.from(o).join(","),D=await ye(ke(`/api/config/export?categories=${L}`));if(!D.ok)throw new Error("Export failed");const Q=await D.blob(),ee=window.URL.createObjectURL(Q),T=document.createElement("a");T.href=ee;const C=D.headers.get("Content-Disposition"),Y=((w=C==null?void 0:C.match(/filename="(.+)"/))==null?void 0:w[1])||"tide-commander-config.zip";T.download=Y,document.body.appendChild(T),T.click(),document.body.removeChild(T),window.URL.revokeObjectURL(ee),g({type:"success",text:s("config:data.exportSuccess")})}catch(L){g({type:"error",text:L.message||"Export failed"})}finally{i(!1)}}},N=async w=>{var D;const L=(D=w.target.files)==null?void 0:D[0];if(L){u(L),g(null),x(null),c(new Set);try{const Q=await ye(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await L.arrayBuffer()});if(!Q.ok){const C=await Q.json();throw new Error(C.error||"Failed to preview config file")}const ee=await Q.json(),T=Array.isArray(ee.categories)?ee.categories:[];x({...ee,categories:T}),c(new Set(T.map(C=>C.id)))}catch(Q){g({type:"error",text:Q.message||"Failed to read config file"}),u(null)}}},$=async()=>{if(!(!S||r.size===0)){y(!0),g(null);try{const w=Array.from(r).join(","),L=await ye(ke(`/api/config/import?categories=${w}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await S.arrayBuffer()}),D=await L.json();if(!L.ok)throw new Error(D.error||"Import failed");g({type:"success",text:D.message||s("config:data.importSuccess")}),u(null),x(null),c(new Set)}catch(w){g({type:"error",text:w.message||"Import failed"})}finally{y(!1)}}},V=()=>{u(null),x(null),c(new Set),g(null)};return e.jsxs("div",{className:"data-section",children:[h&&e.jsx("div",{className:`data-message data-message-${h.type}`,children:h.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(gt,{checked:!!(p!=null&&p.enabled),disabled:M||!p,onChange:U})]}),e.jsxs("div",{className:"data-backup-info",children:[p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:p.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!p.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:p.scriptPath})]}),p.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(p.lastRunAt).toLocaleString(),p.lastRunOk===!0&&" — ok",p.lastRunOk===!1&&p.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",p.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),H&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:H})]})]}),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:k,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:O,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:a.map(w=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(w.id),onChange:()=>B(w.id)}),e.jsx("span",{className:"data-category-name",children:w.name})]},w.id))}),e.jsx("button",{className:"data-action-btn export",onClick:te,disabled:b||o.size===0,children:b?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")})}),S?f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:S.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(f.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:K,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:q,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:f.categories.map(w=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(w.id),onChange:()=>W(w.id)}),e.jsx("span",{className:"data-category-name",children:w.name}),w.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",w.fileCount," ",s("config:data.files"),")"]})]},w.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:V,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:$,disabled:j||r.size===0,children:j?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")})]})]})]})}function xt(){const[s,a]=l.useState(()=>bs()),t=o=>{a(o);const d=ws(o);Ns(d)};return e.jsx("div",{className:"theme-selector",children:e.jsx("div",{className:"theme-selector-grid",children:js.map(o=>e.jsxs("button",{className:`theme-option ${s===o.id?"active":""}`,onClick:()=>t(o.id),title:o.description,children:[e.jsx("div",{className:"theme-preview",children:e.jsxs("div",{className:"theme-preview-bg",style:{backgroundColor:o.colors.bgPrimary},children:[e.jsx("div",{className:"theme-preview-accent",style:{backgroundColor:o.colors.accentBlue}}),e.jsx("div",{className:"theme-preview-claude",style:{backgroundColor:o.colors.accentClaude}})]})}),e.jsx("span",{className:"theme-name",children:o.name})]},o.id))})})}function bt(){const{t:s}=Z(["config"]),{installInfo:a,phase:t,output:o,error:d,newVersion:r,autoRestart:c,refreshInstallInfo:b,runUpdate:i,reset:j}=ys(),[y,S]=l.useState(!1),u=l.useRef(null);l.useEffect(()=>{b()},[b]),l.useEffect(()=>{u.current&&(u.current.scrollTop=u.current.scrollHeight)},[o]);const f=l.useCallback(()=>{S(!0)},[]),x=l.useCallback(()=>{S(!1)},[]),h=l.useCallback(()=>{S(!1),i()},[i]),g=l.useCallback(()=>{j(),S(!1),b()},[j,b]);return a?a.isGlobalInstall?a.autoUpdateSupported?!a.updateAvailable&&t==="idle"?null:e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),t==="idle"&&!y&&a.updateAvailable&&e.jsxs("div",{className:"about-autoupdate-row",children:[e.jsxs("span",{className:"about-autoupdate-versions",children:[e.jsx("span",{className:"about-autoupdate-current",children:a.currentVersion}),e.jsx("span",{className:"about-autoupdate-arrow",children:"→"}),e.jsx("span",{className:"about-autoupdate-latest",children:a.latestVersion})]}),e.jsx("button",{className:"about-update-btn download",onClick:f,children:s("config:about.autoUpdateButton")})]}),t==="idle"&&y&&e.jsxs("div",{className:"about-autoupdate-confirm",children:[e.jsx("div",{className:"about-autoupdate-confirm-title",children:s("config:about.autoUpdateConfirmTitle")}),e.jsx("div",{className:"about-autoupdate-confirm-body",children:s("config:about.autoUpdateConfirmBody")}),e.jsxs("div",{className:"about-autoupdate-confirm-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:x,children:s("config:about.autoUpdateCancel")}),e.jsx("button",{className:"about-update-btn download",onClick:h,children:s("config:about.autoUpdateConfirm")})]})]}),(t==="running"||t==="success"||t==="failed")&&e.jsxs("div",{className:"about-autoupdate-stream",children:[e.jsxs("div",{className:"about-autoupdate-stream-title",children:[t==="running"&&s("config:about.autoUpdateRunning"),t==="success"&&s("config:about.autoUpdateSuccess"),t==="failed"&&s("config:about.autoUpdateFailed")]}),e.jsx("pre",{ref:u,className:"about-autoupdate-output",children:o||"..."}),t==="success"&&e.jsxs("div",{className:"about-autoupdate-success-hint",children:[r&&e.jsxs("div",{className:"about-autoupdate-newversion",children:["v",r]}),e.jsx("div",{children:s(c?"config:about.autoUpdateReconnectHint":"config:about.autoUpdateRestartHint")})]}),t==="failed"&&d&&e.jsx("div",{className:"about-update-error",children:d}),(t==="success"||t==="failed")&&e.jsx("div",{className:"about-autoupdate-stream-actions",children:e.jsx("button",{className:"about-update-btn changelog",onClick:g,children:s("config:about.autoUpdateClose")})})]})]}):e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.autoUpdatePackageManagerNotice",{pm:a.packageManager})}),a.suggestedManualCommand&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"about-autoupdate-manualhint",children:s("config:about.autoUpdateManualCommand")}),e.jsx("pre",{className:"about-autoupdate-manualcmd",children:a.suggestedManualCommand})]})]}):e.jsxs("div",{className:"about-autoupdate",children:[e.jsx("div",{className:"about-autoupdate-title",children:s("config:about.autoUpdateTitle")}),e.jsx("div",{className:"about-autoupdate-devnote",children:s("config:about.autoUpdateDevMode")})]}):null}function jt(){const{t:s}=Z(["config"]),{updateAvailable:a,updateInfo:t,recentReleases:o,isChecking:d,error:r,currentVersion:c,isAndroid:b,checkForUpdate:i,downloadAndInstall:j,openReleasePage:y}=Ws(),[S,u]=l.useState(!1),f=h=>h?`${(h/(1024*1024)).toFixed(1)} MB`:"",x=h=>new Date(h).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"});return e.jsxs("div",{className:"about-section",children:[e.jsxs("div",{className:"about-logo",children:[e.jsx("span",{className:"about-logo-icon",children:e.jsx(P,{name:"waves",size:24})}),e.jsx("span",{className:"about-logo-text",children:"Tide Commander"})]}),e.jsxs("div",{className:"about-version",children:[e.jsx("span",{className:"about-version-label",children:s("config:about.version")}),e.jsxs("div",{className:"about-version-info",children:[e.jsx("span",{className:"about-version-value",children:c}),a&&t?e.jsx("span",{className:"about-version-update-badge",onClick:y,title:`Update available: ${t.version}`,children:t.version}):e.jsxs("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"about-version-status",children:["(",s("config:about.updated"),")"]})]})]}),e.jsx(bt,{}),e.jsx("div",{className:"about-changelog-row",children:e.jsx("button",{className:"about-update-btn changelog",onClick:()=>u(!0),children:s("config:about.changelog")})}),e.jsxs("div",{className:"about-update",children:[a&&t?e.jsxs("div",{className:"about-update-available",children:[e.jsxs("div",{className:"about-update-header",children:[e.jsx("span",{className:"about-update-badge",children:s("config:about.updateAvailable")}),e.jsx("span",{className:"about-update-version",children:t.version})]}),t.apkSize&&e.jsxs("div",{className:"about-update-size",children:[s("config:about.sizeLabel"),": ",f(t.apkSize)]}),r&&e.jsx("div",{className:"about-update-error",children:r}),e.jsxs("div",{className:"about-update-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:y,children:s("config:about.changelog")}),b&&t.apkUrl?e.jsx("button",{className:"about-update-btn download",onClick:j,children:s("config:about.downloadAPK")}):e.jsx("button",{className:"about-update-btn download",onClick:y,children:s("config:about.viewRelease")})]})]}):e.jsxs("div",{className:"about-update-check",children:[e.jsx("span",{className:"about-update-status",children:s(d?"config:about.checkingUpdates":"config:about.upToDate")}),e.jsx("button",{className:"about-update-btn check",onClick:()=>i(!0),disabled:d,children:d?"...":s("config:about.check")})]}),o.length>0&&e.jsxs("div",{className:"about-releases",children:[e.jsx("div",{className:"about-releases-title",children:s("config:about.recentReleases")}),e.jsx("div",{className:"about-releases-list",children:o.map(h=>e.jsxs("a",{href:h.releaseUrl,target:"_blank",rel:"noopener noreferrer",className:`about-release-item ${h.version===`v${c}`||h.version===c?"current":""}`,children:[e.jsx("span",{className:"about-release-version",children:h.version}),e.jsx("span",{className:"about-release-date",children:x(h.publishedAt)})]},h.version))})]})]}),e.jsx("div",{className:"about-description",children:s("config:about.tagline")}),e.jsxs("div",{className:"about-principles",children:[e.jsx("div",{className:"about-principles-title",children:s("config:about.corePrinciples")}),e.jsxs("ul",{className:"about-principles-list",children:[e.jsx("li",{children:s("config:about.principle1")}),e.jsx("li",{children:s("config:about.principle2")}),e.jsx("li",{children:s("config:about.principle3")}),e.jsx("li",{children:s("config:about.principle4")})]})]}),e.jsx("div",{className:"about-links",children:e.jsxs("a",{href:"https://github.com/deivid11/tide-commander",target:"_blank",rel:"noopener noreferrer",className:"about-link",children:[e.jsx("span",{className:"about-link-icon",children:e.jsx(P,{name:"package",size:14})}),e.jsx("span",{children:s("config:about.repository")})]})}),e.jsxs("div",{className:"about-credits",children:[e.jsx("div",{className:"about-credits-title",children:s("config:about.specialThanks")}),e.jsxs("div",{className:"about-credit-item",children:[e.jsx("a",{href:"https://kenney.nl",target:"_blank",rel:"noopener noreferrer",className:"about-credit-link",children:"Kenney.nl"}),e.jsx("span",{className:"about-credit-desc",children:s("config:about.kenneyCredit")})]}),e.jsxs("div",{className:"about-credit-item",children:[e.jsx("a",{href:"https://claude.ai/code",target:"_blank",rel:"noopener noreferrer",className:"about-credit-link",children:"Claude Code"}),e.jsx("span",{className:"about-credit-desc",children:s("config:about.claudeCodeCredit")})]})]}),S&&e.jsx(vs,{onClose:()=>u(!1)})]})}const vt={gmail:"✉️",slack:"💬",jira:"📋","google-calendar":"📅",docx:"📄",whatsapp:"📱"};function wt({onOpenModal:s}){const[a,t]=l.useState([]),[o,d]=l.useState(!0),r=l.useCallback(async()=>{try{const c=await ye(ke("/api/integrations"));if(!c.ok)return;const b=await c.json();t(b)}catch{}finally{d(!1)}},[]);return l.useEffect(()=>{r()},[r]),o?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"Loading..."}):a.length===0?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"No integrations available."}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[a.map(c=>{const b=vt[c.id]||"🔌",i=!!c.status.error,j=c.status.connected,y=i?"#f38ba8":j?"#a6e3a1":"#fab387",S=i?"Error":j?"Connected":"Setup Required",u=i?"✗":j?"✓":"⚠";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"3px 8px",borderRadius:4,background:"var(--surface-1, #181825)",border:"1px solid var(--border, #313244)",fontSize:12,minHeight:26},children:[e.jsx("span",{style:{fontSize:13,flexShrink:0},children:b}),e.jsx("span",{style:{flex:1,minWidth:0,color:"var(--text-primary, #cdd6f4)",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:c.name}),e.jsx("span",{style:{color:y,fontSize:10,fontWeight:500,whiteSpace:"nowrap"},title:S,children:u}),e.jsx("button",{onClick:()=>s(c.id),title:`Configure ${c.name}`,style:{background:"none",border:"none",cursor:"pointer",padding:"1px 3px",fontSize:12,color:"var(--text-secondary, #a6adc8)",borderRadius:3,flexShrink:0,lineHeight:1},onMouseEnter:f=>{f.target.style.color="var(--text-primary, #cdd6f4)"},onMouseLeave:f=>{f.target.style.color="var(--text-secondary, #a6adc8)"},children:"⚙️"})]},c.id)}),e.jsx("button",{onClick:()=>s(),style:{background:"none",border:"1px dashed var(--border, #313244)",borderRadius:4,padding:"3px 8px",cursor:"pointer",color:"var(--text-secondary, #a6adc8)",fontSize:11,textAlign:"center",marginTop:2},onMouseEnter:c=>{c.target.style.borderColor="var(--accent, #89b4fa)",c.target.style.color="var(--accent, #89b4fa)"},onMouseLeave:c=>{c.target.style.borderColor="var(--border, #313244)",c.target.style.color="var(--text-secondary, #a6adc8)"},children:"Manage All Integrations"})]})}const Pe="__global__";function Nt({isOpen:s,onClose:a,initialAgentId:t}){const{t:o}=Z(["config"]),d=ks(),[r,c]=l.useState(""),[b,i]=l.useState(""),[j,y]=l.useState(!1),[S,u]=l.useState(""),[f,x]=l.useState(""),[h,g]=l.useState(null),[p,A]=l.useState(null),[M,F]=l.useState(!1),[H,v]=l.useState(!1),[U,B]=l.useState(!1),[W,k]=l.useState(null),O=l.useMemo(()=>[...d].sort((T,C)=>T.name.localeCompare(C.name)),[d]),K=l.useMemo(()=>d.find(T=>T.id===r),[d,r]),q=r===Pe;l.useEffect(()=>{if(!s)return;const T=t&&d.some(C=>C.id===t)?t:Pe;c(T),y(!1),tt().then(C=>i(C)).catch(()=>i("")).finally(()=>y(!0))},[s]),l.useEffect(()=>{const T=r===Pe?b:(K==null?void 0:K.customPrompt)??"";u(T),x(T),F(!1),g(null),A(null)},[r,j]);const te=T=>{const C=T.target.value;u(C),F(C!==f),g(null),A(null)},N=async()=>{if(r)try{g(null),A(null),q?(await at(S),i(S),A(o("config:systemPrompt.savedGlobal"))):(_.updateAgentProperties(r,{customPrompt:S}),A(o("config:systemPrompt.saved"))),x(S),F(!1)}catch(T){g(T instanceof Error?T.message:"Failed to save system prompt")}},$=()=>{v(!0)},V=async()=>{if(r)try{g(null),A(null),q?(await nt(),i(""),A(o("config:systemPrompt.clearedGlobal"))):(_.updateAgentProperties(r,{customPrompt:""}),A(o("config:systemPrompt.cleared"))),u(""),x(""),F(!1)}catch(T){g(T instanceof Error?T.message:"Failed to clear system prompt")}},w=()=>{u(f),F(!1),g(null),A(null)},L=T=>{if(T!==r){if(M){k(T),B(!0);return}c(T)}},D=()=>{if(M){k(null),B(!0);return}a()},Q=()=>{if(B(!1),W){const T=W;k(null),c(T)}else a()},ee=T=>{T.key==="Escape"&&(T.preventDefault(),D())};return s?e.jsxs(Ce,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:D,children:e.jsxs("div",{className:"system-prompt-modal",onClick:T=>T.stopPropagation(),onKeyDown:ee,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:o("config:systemPrompt.title")}),e.jsx("button",{className:"modal-close",onClick:D,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{className:"modal-description",children:o("config:systemPrompt.description")}),e.jsxs("div",{className:"agent-picker",children:[e.jsx("label",{htmlFor:"system-prompt-agent",className:"editor-label",children:o("config:systemPrompt.agentLabel")}),e.jsxs("div",{className:"agent-picker-row",children:[q?e.jsx(P,{name:"globe",size:20,className:"agent-picker-icon"}):K&&e.jsx(Cs,{classId:K.class,size:20,className:"agent-picker-icon"}),e.jsxs("select",{id:"system-prompt-agent",className:"agent-picker-select",value:r,onChange:T=>L(T.target.value),children:[e.jsxs("option",{value:Pe,children:[o("config:systemPrompt.globalOption"),b?" • ✦":""]}),O.map(T=>e.jsxs("option",{value:T.id,children:[T.name,T.customPrompt?" • ✦":""]},T.id))]})]})]}),h&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"warn",size:14})}),h]}),p&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"check",size:14})}),p]}),e.jsxs("div",{className:"editor-wrapper",children:[e.jsxs("div",{className:"editor-header",children:[e.jsx("label",{htmlFor:"prompt-input",className:"editor-label",children:o("config:systemPrompt.editPrompt")}),e.jsxs("span",{className:"char-count",children:[S.length," ",o("config:systemPrompt.characters")]})]}),e.jsx("textarea",{id:"prompt-input",className:"prompt-editor",value:S,onChange:te,placeholder:o("config:systemPrompt.placeholder"),rows:18,disabled:q&&!j,autoFocus:!0}),e.jsx("div",{className:"editor-hint",children:o(q?"config:systemPrompt.hintGlobal":"config:systemPrompt.hint")})]})]}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:$,disabled:!S||!r,children:o("config:systemPrompt.clear")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:D,children:"Close"}),e.jsx("button",{className:"btn btn-secondary",onClick:w,disabled:!M,children:o("config:systemPrompt.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:N,disabled:!M||!r,children:o("config:systemPrompt.save")})]})]})]})}),e.jsx(he,{isOpen:H,title:o("config:systemPrompt.clear"),message:o(q?"config:systemPrompt.confirmClearGlobal":"config:systemPrompt.confirmClear"),confirmLabel:o("config:systemPrompt.clear"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V()},onClose:()=>v(!1)}),e.jsx(he,{isOpen:U,title:"Unsaved Changes",message:"You have unsaved changes for this agent. Discard them?",confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"danger",onConfirm:Q,onClose:()=>{B(!1),k(null)}})]}):null}const Qe={enabled:!1,baseUrl:"",defaultSessionId:"",webhookVerifyToken:"",showIncomingToasts:!0},yt=2500,kt=12e4;function es(s){return{enabled:s.enabled??!1,baseUrl:s.baseUrl??"",defaultSessionId:s.defaultSessionId??"",webhookVerifyToken:s.webhookVerifyToken??"",showIncomingToasts:s.showIncomingToasts??!0}}function Ct(s,a){return s.enabled===a.enabled&&s.baseUrl===a.baseUrl&&s.defaultSessionId===a.defaultSessionId&&s.webhookVerifyToken===a.webhookVerifyToken&&s.showIncomingToasts===a.showIncomingToasts}function St({isOpen:s,onClose:a}){const{t}=Z(["config"]),[o,d]=l.useState(Qe),[r,c]=l.useState(Qe),[b,i]=l.useState(!1),[j,y]=l.useState([]),[S,u]=l.useState(!0),[f,x]=l.useState(null),[h,g]=l.useState(null),[p,A]=l.useState(""),[M,F]=l.useState(!1),[H,v]=l.useState(""),[U,B]=l.useState(null),[W,k]=l.useState(null),[O,K]=l.useState(null),q=l.useRef(null),te=l.useRef(0),[N,$]=l.useState(""),[V,w]=l.useState(""),[L,D]=l.useState(null),[Q,ee]=l.useState(!1),[T,C]=l.useState(!1),[Y,ae]=l.useState(!1),[le,ne]=l.useState(!1),[ue,je]=l.useState(null),ve=!Ct(o,r),re=l.useCallback(()=>{q.current&&(clearTimeout(q.current),q.current=null)},[]),me=l.useCallback(async()=>{try{u(!0),x(null),g(null);const[m,R]=await Promise.all([os(),Ss()]),ie=es(m);if(d(ie),c(ie),i(!!R.configured),R.configured)try{const fe=await Ve();y(Array.isArray(fe)?fe:[])}catch{y([])}else y([])}catch(m){x(m instanceof Error?m.message:t("config:whatsapp.errors.loadFailed"))}finally{u(!1)}},[t]),E=l.useCallback(async()=>{try{const m=await Ve();y(Array.isArray(m)?m:[])}catch{}},[]);l.useEffect(()=>(s?me():(re(),B(null),k(null),K(null),A(""),F(!1),D(null)),()=>{re()}),[s,me,re]);const pe=(m,R)=>{d(ie=>({...ie,[m]:R})),x(null),g(null)},ce=async()=>{try{x(null),g(null);const m=await Es({enabled:o.enabled,baseUrl:o.baseUrl.trim(),defaultSessionId:o.defaultSessionId.trim(),webhookVerifyToken:o.webhookVerifyToken,showIncomingToasts:o.showIncomingToasts});window.dispatchEvent(new CustomEvent("tide:whatsapp-config-updated"));const R=es(m);d(R),c(R),g(t("config:whatsapp.saved"))}catch(m){x(m instanceof Error?m.message:t("config:whatsapp.errors.saveFailed"))}},$e=()=>{d(r),x(null),g(null)},ge=()=>{if(ve){C(!0);return}a()},De=m=>{m.key==="Escape"&&(m.preventDefault(),ge())},Fe=async()=>{const m=p.trim();if(m)try{x(null),g(null),await Ts(m),A(""),F(!1),i(!0),g(t("config:whatsapp.apiKeySaved"))}catch(R){x(R instanceof Error?R.message:t("config:whatsapp.errors.apiKeySaveFailed"))}},Se=()=>{ae(!0)},Oe=async()=>{try{x(null),g(null),await Ps(),i(!1),g(t("config:whatsapp.apiKeyCleared"))}catch(m){x(m instanceof Error?m.message:t("config:whatsapp.errors.apiKeyClearFailed"))}},we=l.useCallback(async m=>{if(Date.now()>te.current){K(t("config:whatsapp.pairingTimeout")),B(null),k(null),re(),E();return}try{const R=await As(m);if(R.status&&["connected","paired","open","ready"].includes(R.status.toLowerCase())){K(t("config:whatsapp.pairingSuccess")),B(null),k(null),re(),E();return}const fe=R.qrUrl??R.qr??null;fe&&k(fe)}catch(R){K(R instanceof Error?R.message:t("config:whatsapp.errors.qrFetchFailed"))}q.current=setTimeout(()=>{we(m)},yt)},[E,re,t]),Ae=async()=>{const m=H.trim();if(m)try{x(null),g(null),K(null),k(null),re(),await _s(m),v(""),B(m),te.current=Date.now()+kt,we(m),E()}catch(R){x(R instanceof Error?R.message:t("config:whatsapp.errors.sessionCreateFailed"))}},Te=()=>{re(),B(null),k(null),K(null)},_e=m=>{je(m),ne(!0)},Re=async()=>{if(ue)try{x(null),g(null),await Ls(ue),U===ue&&Te(),E(),g(t("config:whatsapp.sessionDeleted"))}catch(m){x(m instanceof Error?m.message:t("config:whatsapp.errors.sessionDeleteFailed"))}finally{je(null)}},Ie=async()=>{const m=N.trim(),R=V.trim();if(!(!m||!R))try{ee(!0),D(null);const ie=o.defaultSessionId.trim()||void 0;await Is(m,R,ie),D({kind:"success",text:t("config:whatsapp.testSent")})}catch(ie){D({kind:"error",text:ie instanceof Error?ie.message:t("config:whatsapp.errors.testSendFailed")})}finally{ee(!1)}};return s?e.jsxs(Ce,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:ge,children:e.jsxs("div",{className:"whatsapp-config-modal",onClick:m=>m.stopPropagation(),onKeyDown:De,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsapp.title")}),e.jsx("button",{className:"modal-close",onClick:ge,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:S?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsapp.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:t("config:whatsapp.description")}),f&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"warn",size:14})}),f]}),h&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"check",size:14})}),h]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.general")}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-enabled",className:"wa-label",children:t("config:whatsapp.enabled")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-enabled",type:"checkbox",checked:o.enabled,onChange:m=>pe("enabled",m.target.checked)}),e.jsx("span",{className:"wa-toggle-track",children:e.jsx("span",{className:"wa-toggle-thumb"})})]})]}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-show-toasts",className:"wa-label",children:t("config:whatsapp.showIncomingToasts")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-show-toasts",type:"checkbox",checked:o.showIncomingToasts,onChange:m=>pe("showIncomingToasts",m.target.checked)}),e.jsx("span",{className:"wa-toggle-track",children:e.jsx("span",{className:"wa-toggle-thumb"})})]})]}),e.jsx("span",{className:"wa-hint",children:t("config:whatsapp.showIncomingToastsHelp")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-base-url",className:"wa-label",children:t("config:whatsapp.baseUrl")}),e.jsx("input",{id:"wa-base-url",type:"text",className:"wa-input",placeholder:"http://localhost:3007",value:o.baseUrl,onChange:m=>pe("baseUrl",m.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-default-session",className:"wa-label",children:t("config:whatsapp.defaultSessionId")}),e.jsx("input",{id:"wa-default-session",type:"text",className:"wa-input",placeholder:t("config:whatsapp.defaultSessionIdPlaceholder"),value:o.defaultSessionId,onChange:m=>pe("defaultSessionId",m.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-webhook-token",className:"wa-label",children:t("config:whatsapp.webhookVerifyToken")}),e.jsx("input",{id:"wa-webhook-token",type:"text",className:"wa-input",placeholder:t("config:whatsapp.webhookVerifyTokenPlaceholder"),value:o.webhookVerifyToken,onChange:m=>pe("webhookVerifyToken",m.target.value)})]})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.apiKey")}),e.jsx("div",{className:"wa-key-status",children:b?e.jsxs("span",{className:"wa-status wa-status-ok",children:[e.jsx(P,{name:"check",size:12})," ",t("config:whatsapp.configured")]}):e.jsxs("span",{className:"wa-status wa-status-warn",children:[e.jsx(P,{name:"warn",size:12})," ",t("config:whatsapp.notConfigured")]})}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:M?"text":"password",className:"wa-input",placeholder:t("config:whatsapp.apiKeyPlaceholder"),value:p,onChange:m=>A(m.target.value)}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>F(m=>!m),title:t(M?"config:whatsapp.hideKey":"config:whatsapp.showKey"),children:e.jsx(P,{name:M?"eye-closed":"eye",size:14})}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Fe,disabled:!p.trim(),children:t("config:whatsapp.saveKey")}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:Se,disabled:!b,children:t("config:whatsapp.clearKey")})]}),e.jsx("span",{className:"wa-hint",children:t("config:whatsapp.apiKeyHint")})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.sessions")}),e.jsx("div",{className:"wa-sessions-list",children:!Array.isArray(j)||j.length===0?e.jsx("div",{className:"wa-empty",children:t("config:whatsapp.noSessions")}):j.map(m=>e.jsxs("div",{className:"wa-session-row",children:[e.jsxs("div",{className:"wa-session-info",children:[e.jsx("span",{className:"wa-session-id",children:m.id}),e.jsx("span",{className:`wa-session-status status-${(m.status??"unknown").toLowerCase()}`,children:m.status||"—"}),m.pairedNumber&&e.jsx("span",{className:"wa-session-paired",children:m.pairedNumber})]}),e.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:()=>_e(m.id),children:t("config:whatsapp.deleteSession")})]},m.id))}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:"text",className:"wa-input",placeholder:t("config:whatsapp.addSessionPlaceholder"),value:H,onChange:m=>v(m.target.value),onKeyDown:m=>{m.key==="Enter"&&Ae()}}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ae,disabled:!H.trim()||U!==null,children:t("config:whatsapp.addSession")})]}),U&&e.jsxs("div",{className:"wa-qr-panel",children:[e.jsxs("div",{className:"wa-qr-header",children:[e.jsx("span",{children:t("config:whatsapp.qrPrompt",{id:U})}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,children:t("config:whatsapp.cancelPairing")})]}),W?e.jsx("div",{className:"wa-qr-image",children:e.jsx("img",{src:W,alt:"WhatsApp pairing QR code"})}):e.jsxs("div",{className:"wa-qr-loading",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsapp.waitingForQr")})]})]}),O&&!U&&e.jsx("div",{className:"wa-pairing-message",children:O})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:t("config:whatsapp.sections.testMessage")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-to",className:"wa-label",children:t("config:whatsapp.testTo")}),e.jsx("input",{id:"wa-test-to",type:"text",className:"wa-input",placeholder:t("config:whatsapp.testToPlaceholder"),value:N,onChange:m=>$(m.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-message",className:"wa-label",children:t("config:whatsapp.testMessageBody")}),e.jsx("textarea",{id:"wa-test-message",className:"wa-textarea",rows:4,placeholder:t("config:whatsapp.testMessageBodyPlaceholder"),value:V,onChange:m=>w(m.target.value)})]}),e.jsx("div",{className:"wa-field-inline wa-field-end",children:e.jsx("button",{type:"button",className:"btn btn-primary",onClick:Ie,disabled:!N.trim()||!V.trim()||Q,children:t(Q?"config:whatsapp.sending":"config:whatsapp.sendTest")})}),L&&e.jsxs("div",{className:`alert ${L.kind==="success"?"alert-success":"alert-error"}`,children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:L.kind==="success"?"check":"warn",size:14})}),L.text]})]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left"}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:ge,children:t("config:whatsapp.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:$e,disabled:!ve||S,children:t("config:whatsapp.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:ce,disabled:!ve||S,children:t("config:whatsapp.save")})]})]})]})}),e.jsx(he,{isOpen:T,title:t("config:whatsapp.unsavedTitle"),message:t("config:whatsapp.unsavedMessage"),confirmLabel:t("config:whatsapp.closeAnyway"),cancelLabel:t("config:whatsapp.keepEditing"),variant:"danger",onConfirm:()=>{C(!1),a()},onClose:()=>C(!1)}),e.jsx(he,{isOpen:Y,title:t("config:whatsapp.clearKey"),message:t("config:whatsapp.confirmClearKey"),confirmLabel:t("config:whatsapp.clearKey"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Oe()},onClose:()=>ae(!1)}),e.jsx(he,{isOpen:le,title:t("config:whatsapp.deleteSession"),message:t("config:whatsapp.confirmDeleteSession",{id:ue??""}),confirmLabel:t("config:whatsapp.deleteSession"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Re()},onClose:()=>{ne(!1),je(null)}})]}):null}const cs=["messages","statusChanges","taskComplete","errors","planReady","agentSpawned","agentStopped"];function qe(s=!1){const a=se(),t={};return a&&(t.Authorization=`Bearer ${a}`),s&&(t["Content-Type"]="application/json"),t}async function We(s,a){try{const t=await s.json();if(t&&typeof t.error=="string")return t.error;if(t&&typeof t.message=="string")return t.message}catch{}return`${a}: ${s.statusText}`}async function At(){const s=await fetch(`${X()}/api/whatsapp/notification-config`,{headers:qe()});if(!s.ok)throw new Error(await We(s,"Failed to fetch WhatsApp notification config"));return s.json()}async function Tt(s){const a=await fetch(`${X()}/api/whatsapp/notification-config`,{method:"PATCH",headers:qe(!0),body:JSON.stringify(s)});if(!a.ok)throw new Error(await We(a,"Failed to update WhatsApp notification config"));return a.json()}async function _t(){const s=await fetch(`${X()}/api/whatsapp/notification-config`,{method:"DELETE",headers:qe()});if(!s.ok)throw new Error(await We(s,"Failed to reset WhatsApp notification config"));return s.json()}const Le={messages:!0,statusChanges:!0,taskComplete:!0,errors:!0,planReady:!0,agentSpawned:!0,agentStopped:!0},ss={filter:{...Le},recipient:""};function It(s,a){if(s.recipient!==a.recipient)return!1;for(const t of cs)if(s.filter[t]!==a.filter[t])return!1;return!0}function Et({isOpen:s,onClose:a}){const{t}=Z(["config"]),[o,d]=l.useState(ss),[r,c]=l.useState(ss),[b,i]=l.useState(!0),[j,y]=l.useState(null),[S,u]=l.useState(null),[f,x]=l.useState(!1),[h,g]=l.useState(!1),p=!It(o,r),A=l.useCallback(async()=>{try{i(!0),y(null),u(null);const k=await At(),O={filter:{...Le,...k.filter},recipient:k.recipient??""};d(O),c(O)}catch(k){y(k instanceof Error?k.message:t("config:whatsappNotifications.errors.loadFailed"))}finally{i(!1)}},[t]);l.useEffect(()=>{s&&A()},[s,A]);const M=(k,O)=>{d(K=>({...K,filter:{...K.filter,[k]:O}})),y(null),u(null)},F=k=>{d(O=>({...O,recipient:k})),y(null),u(null)},H=async()=>{try{y(null),u(null);const k=await Tt({filter:o.filter,recipient:o.recipient.trim()}),O={filter:{...Le,...k.filter},recipient:k.recipient??""};d(O),c(O),u(t("config:whatsappNotifications.saved"))}catch(k){y(k instanceof Error?k.message:t("config:whatsappNotifications.errors.saveFailed"))}},v=()=>{d(r),y(null),u(null)},U=async()=>{try{y(null),u(null);const k=await _t(),O={filter:{...Le,...k.filter},recipient:k.recipient??""};d(O),c(O),u(t("config:whatsappNotifications.resetDone"))}catch(k){y(k instanceof Error?k.message:t("config:whatsappNotifications.errors.resetFailed"))}},B=()=>{if(p){x(!0);return}a()},W=k=>{k.key==="Escape"&&(k.preventDefault(),B())};return s?e.jsxs(Ce,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:B,children:e.jsxs("div",{className:"whatsapp-notifications-modal",onClick:k=>k.stopPropagation(),onKeyDown:W,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsappNotifications.title")}),e.jsx("button",{className:"modal-close",onClick:B,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:b?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:t("config:whatsappNotifications.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:t("config:whatsappNotifications.description")}),j&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"warn",size:14})}),j]}),S&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(P,{name:"check",size:14})}),S]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:t("config:whatsappNotifications.sections.recipient")}),e.jsxs("div",{className:"wan-field",children:[e.jsx("label",{htmlFor:"wan-recipient",className:"wan-label",children:t("config:whatsappNotifications.recipientLabel")}),e.jsx("input",{id:"wan-recipient",type:"text",className:"wan-input",placeholder:t("config:whatsappNotifications.recipientPlaceholder"),value:o.recipient,onChange:k=>F(k.target.value)}),e.jsx("span",{className:"wan-hint",children:t("config:whatsappNotifications.recipientHint")})]})]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:t("config:whatsappNotifications.sections.events")}),e.jsx("p",{className:"wan-section-hint",children:t("config:whatsappNotifications.eventsHint")}),cs.map(k=>e.jsxs("div",{className:"wan-toggle-row",children:[e.jsxs("div",{className:"wan-toggle-info",children:[e.jsx("span",{className:"wan-toggle-title",children:t(`config:whatsappNotifications.events.${k}.title`)}),e.jsx("span",{className:"wan-toggle-help",children:t(`config:whatsappNotifications.events.${k}.help`)})]}),e.jsxs("label",{className:"wan-toggle",children:[e.jsx("input",{type:"checkbox",checked:o.filter[k],onChange:O=>M(k,O.target.checked)}),e.jsx("span",{className:"wan-toggle-track",children:e.jsx("span",{className:"wan-toggle-thumb"})})]})]},k))]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:()=>g(!0),disabled:b,children:t("config:whatsappNotifications.resetToDefaults")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:B,children:t("config:whatsappNotifications.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:v,disabled:!p||b,children:t("config:whatsappNotifications.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:H,disabled:!p||b,children:t("config:whatsappNotifications.save")})]})]})]})}),e.jsx(he,{isOpen:f,title:t("config:whatsappNotifications.unsavedTitle"),message:t("config:whatsappNotifications.unsavedMessage"),confirmLabel:t("config:whatsappNotifications.closeAnyway"),cancelLabel:t("config:whatsappNotifications.keepEditing"),variant:"danger",onConfirm:()=>{x(!1),a()},onClose:()=>x(!1)}),e.jsx(he,{isOpen:h,title:t("config:whatsappNotifications.resetToDefaults"),message:t("config:whatsappNotifications.confirmReset"),confirmLabel:t("config:whatsappNotifications.resetToDefaults"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{U(),g(!1)},onClose:()=>g(!1)})]}):null}function rs(s){const a=s.replace(/@.*$/,"");return/^\d{10,15}$/.test(a)?a.startsWith("521")&&a.length===13?`+52 1 ${a.slice(3,5)} ${a.slice(5,9)} ${a.slice(9)}`:a.startsWith("52")&&a.length===12?`+52 ${a.slice(2,4)} ${a.slice(4,8)} ${a.slice(8)}`:a.startsWith("1")&&a.length===11?`+1 ${a.slice(1,4)} ${a.slice(4,7)} ${a.slice(7)}`:`+${a}`:s}function Pt(s,a=Date.now()){const t=s*1e3,o=a-t;if(o<0)return ts(t);const d=Math.floor(o/6e4);if(d<1)return"now";if(d<60)return`${d}m`;const r=Math.floor(d/60);if(r<24)return`${r}h`;const c=Math.floor(r/24);return c===1?"yesterday":c<7?`${c}d`:ts(t)}function ts(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Lt(s){const a=s*1e3;return new Date(a).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function ds(s){switch(s){case"image":return"📷";case"audio":return"🎤";case"video":return"📹";case"document":return"📎";case"location":return"📍";case"contact":return"👤";case"sticker":return"🌟";case"reaction":return"👍";case"unknown":return"❓";case"text":default:return null}}function $t(s,a){return s.length<=a?s:s.slice(0,Math.max(0,a-1)).trimEnd()+"…"}function Dt({chats:s,selectedChatId:a,loading:t,error:o,onSelect:d,onRefresh:r,now:c}){const{t:b}=Z(["config","common"]);return e.jsxs("div",{className:"whatsapp-history-chatlist",children:[e.jsxs("div",{className:"whatsapp-history-chatlist__header",children:[e.jsx("span",{className:"whatsapp-history-chatlist__title",children:b("config:whatsappHistory.chats")}),e.jsx("button",{type:"button",className:"whatsapp-history-chatlist__refresh",onClick:r,disabled:t,"aria-label":b("config:whatsappHistory.refresh"),title:b("config:whatsappHistory.refresh"),children:"⟳"})]}),o&&e.jsx("div",{className:"whatsapp-history-chatlist__error",children:o}),t&&s.length===0&&e.jsxs("div",{className:"whatsapp-history-chatlist__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:b("config:whatsappHistory.loadingChats")})]}),!t&&!o&&s.length===0&&e.jsx("div",{className:"whatsapp-history-chatlist__empty",children:b("config:whatsappHistory.emptyChats")}),e.jsx("ul",{className:"whatsapp-history-chatlist__items",children:s.map(i=>{const j=ds(i.lastMessageType),y=i.lastMessagePreview||`[${i.lastMessageType}]`,S=i.chatId===a,u=rs(i.chatId),f=i.isGroup?i.groupName:i.fromName,x=f||u,h=!!f&&f!==u;return e.jsx("li",{className:`whatsapp-history-chatlist__item ${S?"is-selected":""}`,children:e.jsxs("button",{type:"button",className:"whatsapp-history-chatlist__button",onClick:()=>d(i.chatId),children:[e.jsxs("div",{className:"whatsapp-history-chatlist__row",children:[e.jsx("span",{className:"whatsapp-history-chatlist__name",title:i.chatId,children:x}),e.jsx("span",{className:"whatsapp-history-chatlist__time",children:Pt(i.lastTimestamp,c)})]}),h&&e.jsx("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--jid",children:e.jsx("span",{className:"whatsapp-history-chatlist__jid",children:u})}),e.jsxs("div",{className:"whatsapp-history-chatlist__row whatsapp-history-chatlist__row--secondary",children:[e.jsxs("span",{className:"whatsapp-history-chatlist__preview",children:[i.lastDirection==="outbound"&&e.jsx("span",{className:"whatsapp-history-chatlist__direction",children:"↗ "}),j&&e.jsxs("span",{className:"whatsapp-history-chatlist__preview-icon",children:[j," "]}),$t(y,40)]}),i.unreadCount>0&&e.jsx("span",{className:"whatsapp-history-chatlist__unread",children:i.unreadCount})]})]})},i.chatId)})})]})}function Ft({message:s}){const a=s.direction==="outbound"?"outbound":"inbound",t=ds(s.messageType),o=(s.body??"").trim(),d=o.length>0,r=d?null:`[${s.messageType}]`;return e.jsx("div",{className:`whatsapp-history-bubble whatsapp-history-bubble--${a}`,children:e.jsxs("div",{className:"whatsapp-history-bubble__inner",children:[t&&e.jsx("span",{className:"whatsapp-history-bubble__type-icon",title:s.messageType,children:t}),d?e.jsx("span",{className:"whatsapp-history-bubble__body",children:o}):e.jsx("span",{className:"whatsapp-history-bubble__placeholder",children:r}),s.audioTranscription&&e.jsxs("span",{className:"whatsapp-history-bubble__transcription",children:["“",s.audioTranscription,"”"]}),s.mediaPath&&e.jsx("a",{className:"whatsapp-history-bubble__media-link",href:s.mediaPath,target:"_blank",rel:"noopener noreferrer",children:s.mediaFilename||"open media"}),e.jsx("span",{className:"whatsapp-history-bubble__time",children:Lt(s.timestamp)})]})})}const Ot=["all","inbound","outbound"],Rt=["all","text","image","audio","video","document","sticker","location","contact","reaction","unknown"];function Ut({direction:s,type:a,onDirectionChange:t,onTypeChange:o,disabled:d}){const{t:r}=Z(["config"]);return e.jsxs("div",{className:"whatsapp-history-filters",children:[e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:r("config:whatsappHistory.direction")}),e.jsx("select",{value:s,onChange:c=>t(c.target.value),disabled:d,children:Ot.map(c=>e.jsx("option",{value:c,children:r(`config:whatsappHistory.directionValues.${c}`)},c))})]}),e.jsxs("label",{className:"whatsapp-history-filters__field",children:[e.jsx("span",{children:r("config:whatsappHistory.type")}),e.jsx("select",{value:a,onChange:c=>o(c.target.value),disabled:d,children:Rt.map(c=>e.jsx("option",{value:c,children:r(`config:whatsappHistory.typeValues.${c}`)},c))})]})]})}const zt=80;function Mt({chatId:s,messages:a,loading:t,loadingMore:o,error:d,hasMore:r,direction:c,type:b,onDirectionChange:i,onTypeChange:j,onLoadMore:y}){const{t:S}=Z(["config"]),u=l.useRef(null),f=l.useRef(null),x=l.useRef(!1),h=l.useRef(null);l.useEffect(()=>{f.current!==s&&(f.current=s,x.current=!1)},[s]),l.useLayoutEffect(()=>{u.current&&(x.current||a.length!==0&&(u.current.scrollTop=u.current.scrollHeight,x.current=!0))},[s,a.length]),l.useLayoutEffect(()=>{if(!u.current||h.current===null)return;const A=u.current.scrollHeight-h.current;h.current=null,A>0&&(u.current.scrollTop+=A)},[a.length]);const g=l.useCallback(()=>{!r||o||t||(u.current&&(h.current=u.current.scrollHeight),y())},[r,o,t,y]),p=l.useCallback(A=>{if(!x.current)return;A.currentTarget.scrollTop<=zt&&g()},[g]);return s?e.jsxs("div",{className:"whatsapp-history-messages",children:[e.jsxs("div",{className:"whatsapp-history-messages__header",children:[e.jsx("div",{className:"whatsapp-history-messages__title",children:rs(s)}),e.jsx(Ut,{direction:c,type:b,onDirectionChange:i,onTypeChange:j,disabled:t})]}),e.jsxs("div",{className:"whatsapp-history-messages__scroll",ref:u,onScroll:p,children:[r&&e.jsx("div",{className:"whatsapp-history-messages__load-more-row",children:e.jsx("button",{type:"button",className:"whatsapp-history-messages__load-more",onClick:g,disabled:o||t,children:S(o?"config:whatsappHistory.loadingOlder":"config:whatsappHistory.loadOlder")})}),d&&e.jsx("div",{className:"whatsapp-history-messages__error",children:d}),t&&a.length===0&&e.jsxs("div",{className:"whatsapp-history-messages__loading",children:[e.jsx("span",{className:"spinner"}),e.jsx("span",{children:S("config:whatsappHistory.loadingMessages")})]}),!t&&!d&&a.length===0&&e.jsx("div",{className:"whatsapp-history-messages__empty",children:S("config:whatsappHistory.emptyMessages")}),a.map(A=>e.jsx(Ft,{message:A},Bt(A)))]})]}):e.jsx("div",{className:"whatsapp-history-messages whatsapp-history-messages--empty",children:e.jsx("div",{className:"whatsapp-history-messages__placeholder",children:S("config:whatsappHistory.selectChat")})})}function Bt(s){return typeof s.id=="number"?`id:${s.id}`:s.messageId?`mid:${s.messageId}`:`t:${s.timestamp}:${s.fromJid}:${(s.body??"").slice(0,16)}`}function us(){const s=se(),a={};return s&&(a.Authorization=`Bearer ${s}`),a}async function ps(s,a){try{const t=await s.json();if(t&&typeof t.error=="string")return t.error;if(t&&typeof t.message=="string")return t.message}catch{}return`${a}: ${s.statusText}`}async function Vt(s){const a=`${X()}/api/whatsapp/chats/${encodeURIComponent(s)}`,t=await fetch(a,{headers:us()});if(!t.ok)throw new Error(await ps(t,"Failed to fetch WhatsApp chats"));return t.json()}async function as(s,a,t={}){const o=new URLSearchParams;t.cursor&&o.set("cursor",t.cursor),typeof t.limit=="number"&&o.set("limit",String(t.limit)),t.direction&&o.set("direction",t.direction),t.type&&o.set("type",t.type);const d=o.toString(),r=`${X()}/api/whatsapp/chats/${encodeURIComponent(s)}/${encodeURIComponent(a)}/messages${d?`?${d}`:""}`,c=await fetch(r,{headers:us()});if(!c.ok)throw new Error(await ps(c,"Failed to fetch WhatsApp messages"));return c.json()}const Kt=50;function Ht({isOpen:s,onClose:a}){const{t}=Z(["config"]),[o,d]=l.useState([]),[r,c]=l.useState(null),[b,i]=l.useState(null),[j,y]=l.useState([]),[S,u]=l.useState(!1),[f,x]=l.useState(null),[h,g]=l.useState(null),[p,A]=l.useState([]),[M,F]=l.useState(!1),[H,v]=l.useState(!1),[U,B]=l.useState(null),[W,k]=l.useState(null),[O,K]=l.useState("all"),[q,te]=l.useState("all"),[N,$]=l.useState(()=>Date.now()),V=l.useRef(0);l.useEffect(()=>{if(!s)return;const C=window.setInterval(()=>$(Date.now()),6e4);return()=>window.clearInterval(C)},[s]),l.useEffect(()=>{if(!s)return;let C=!1;return(async()=>{var Y;try{i(null);const[ae,le]=await Promise.all([Ve().catch(()=>[]),os().catch(()=>null)]);if(C)return;d(ae);const ne=(le==null?void 0:le.defaultSessionId)||((Y=ae[0])==null?void 0:Y.id)||null;c(ue=>ue??ne)}catch(ae){if(C)return;i(ae instanceof Error?ae.message:String(ae))}})(),()=>{C=!0}},[s]);const w=l.useCallback(async C=>{u(!0),x(null);try{const Y=await Vt(C);y(Y.chats)}catch(Y){x(Y instanceof Error?Y.message:String(Y))}finally{u(!1)}},[]);l.useEffect(()=>{!s||!r||(g(null),A([]),k(null),w(r))},[s,r,w]);const L=l.useMemo(()=>{const C={limit:Kt};return O!=="all"&&(C.direction=O),q!=="all"&&(C.type=q),C},[O,q]),D=l.useCallback(async(C,Y,ae)=>{const le=++V.current;F(!0),B(null),A([]),k(null);try{const ne=await as(C,Y,ae);if(le!==V.current)return;A([...ne.messages].reverse()),k(ne.nextCursor)}catch(ne){if(le!==V.current)return;B(ne instanceof Error?ne.message:String(ne))}finally{le===V.current&&F(!1)}},[]);l.useEffect(()=>{!s||!r||!h||D(r,h,L)},[s,r,h,L,D]);const Q=l.useCallback(async()=>{if(!(!r||!h||!W)){v(!0),B(null);try{const C=await as(r,h,{...L,cursor:W});A(Y=>[...[...C.messages].reverse(),...Y]),k(C.nextCursor)}catch(C){B(C instanceof Error?C.message:String(C))}finally{v(!1)}}},[r,h,W,L]),ee=l.useCallback(()=>{r&&w(r)},[r,w]),T=l.useCallback(C=>{C.key==="Escape"&&(C.preventDefault(),a())},[a]);return s?e.jsx(Ce,{children:e.jsx("div",{className:"modal-overlay visible",onClick:a,children:e.jsxs("div",{className:"whatsapp-history-modal",onClick:C=>C.stopPropagation(),onKeyDown:T,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:t("config:whatsappHistory.title")}),e.jsx("div",{className:"whatsapp-history-modal__session",children:e.jsxs("label",{children:[e.jsx("span",{children:t("config:whatsappHistory.session")}),e.jsxs("select",{value:r??"",onChange:C=>c(C.target.value||null),disabled:o.length===0,children:[o.length===0&&e.jsx("option",{value:"",children:t("config:whatsappHistory.noSessions")}),o.map(C=>e.jsxs("option",{value:C.id,children:[C.id,C.pairedNumber?` (${C.pairedNumber})`:""]},C.id))]})]})}),e.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),b&&e.jsx("div",{className:"whatsapp-history-modal__alert",children:b}),e.jsxs("div",{className:"whatsapp-history-modal__body",children:[e.jsx(Dt,{chats:j,selectedChatId:h,loading:S,error:f,onSelect:g,onRefresh:ee,now:N}),e.jsx(Mt,{chatId:h,messages:p,loading:M,loadingMore:H,error:U,hasMore:W!==null,direction:O,type:q,onDirectionChange:K,onTypeChange:te,onLoadMore:Q})]})]})})}):null}function qt({isOpen:s,onClose:a,onOpenConfig:t,onOpenNotifications:o,onOpenHistory:d}){const{t:r}=Z(["config"]);if(l.useEffect(()=>{if(!s)return;const b=i=>{i.key==="Escape"&&(i.preventDefault(),a())};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[s,a]),!s)return null;const c=b=>{a(),b()};return e.jsx(Ce,{children:e.jsx("div",{className:"modal-overlay visible",onClick:a,children:e.jsxs("div",{className:"whatsapp-hub-modal",onClick:b=>b.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{children:[e.jsx("span",{className:"whatsapp-hub-modal__icon",children:"📱"}),r("config:whatsappHub.title",{defaultValue:"WhatsApp"})]}),e.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close",children:e.jsx(P,{name:"close",size:16})})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{className:"whatsapp-hub-modal__intro",children:r("config:whatsappHub.intro",{defaultValue:"Pick what you want to manage for the WhatsApp integration."})}),e.jsxs("div",{className:"whatsapp-hub-modal__options",children:[e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>c(t),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(P,{name:"gear",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:r("config:whatsappHub.config",{defaultValue:"Integration config"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:r("config:whatsappHub.configDesc",{defaultValue:"Server URL, API key, sessions and pairing."})})]})]}),e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>c(o),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(P,{name:"bell",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:r("config:whatsappHub.notifications",{defaultValue:"Notifications"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:r("config:whatsappHub.notificationsDesc",{defaultValue:"Which agent events get forwarded and to whom."})})]})]}),e.jsxs("button",{type:"button",className:"whatsapp-hub-modal__option",onClick:()=>c(d),children:[e.jsx("span",{className:"whatsapp-hub-modal__option-icon",children:e.jsx(P,{name:"hourglass",size:18})}),e.jsxs("span",{className:"whatsapp-hub-modal__option-text",children:[e.jsx("span",{className:"whatsapp-hub-modal__option-title",children:r("config:whatsappHub.history",{defaultValue:"History"})}),e.jsx("span",{className:"whatsapp-hub-modal__option-desc",children:r("config:whatsappHub.historyDesc",{defaultValue:"Browse persisted chats and messages."})})]})]})]})]})]})})})}const Wt=[{value:"auto",label:"Auto",icon:"🕐"},{value:"dawn",label:"Dawn",icon:"🌅"},{value:"day",label:"Day",icon:"☀️"},{value:"dusk",label:"Dusk",icon:"🌇"},{value:"night",label:"Night",icon:"🌙"}],Gt=[{value:"none",label:"Grass",icon:"🌱"},{value:"concrete",label:"Concrete",icon:"🏗️"},{value:"galactic",label:"Galactic",icon:"🌌"},{value:"metal",label:"Metal",icon:"⚙️"},{value:"hex",label:"Hex",icon:"⬡"},{value:"circuit",label:"Circuit",icon:"🔌"},{value:"pokemon-stadium",label:"Pokemon",icon:"🔴"}],Yt=[{value:"static",label:"Static",icon:"🧍"},{value:"idle",label:"Idle",icon:"🚶"},{value:"walk",label:"Walk",icon:"🚶‍♂️"},{value:"sprint",label:"Sprint",icon:"🏃"},{value:"jump",label:"Jump",icon:"⬆️"},{value:"fall",label:"Fall",icon:"⬇️"},{value:"crouch",label:"Crouch",icon:"🧎"},{value:"sit",label:"Sit",icon:"🪑"},{value:"die",label:"Die",icon:"💀"},{value:"emote-yes",label:"Yes",icon:"👍"},{value:"emote-no",label:"No",icon:"👎"}],Jt=[{value:"normal",label:"Normal",icon:"🎨"},{value:"bw",label:"B&W",icon:"⬛"},{value:"sepia",label:"Sepia",icon:"🟤"},{value:"cool",label:"Cool",icon:"❄️"},{value:"warm",label:"Warm",icon:"🔥"},{value:"neon",label:"Neon",icon:"💜"}],Zt=[{key:"showTrees",icon:"🌳",label:"Trees"},{key:"showBushes",icon:"🌿",label:"Bushes"},{key:"showHouse",icon:"🏠",label:"House"},{key:"showLamps",icon:"💡",label:"Lamps"},{key:"showGrass",icon:"🟩",label:"Grass"},{key:"showClouds",icon:"☁️",label:"Clouds"}],Xt=[{value:null,label:"Auto",color:"linear-gradient(135deg, #4a90d9 0%, #0a1a2a 100%)"},{value:"#4a90d9",label:"Day Blue",color:"#4a90d9"},{value:"#0a1a2a",label:"Night",color:"#0a1a2a"},{value:"#ff6b35",label:"Sunset",color:"#ff6b35"},{value:"#1a0a2e",label:"Purple",color:"#1a0a2e"},{value:"#2d5a27",label:"Matrix",color:"#2d5a27"},{value:"#8b0000",label:"Blood",color:"#8b0000"},{value:"#000000",label:"Void",color:"#000000"}],Qt={showTrees:"trees",showBushes:"bushes",showHouse:"house",showLamps:"lamps",showGrass:"grass",showClouds:"clouds"},ea={none:"grass","pokemon-stadium":"pokemon"},sa={"emote-yes":"yes","emote-no":"no"},ta={"":"auto","#4a90d9":"dayBlue","#0a1a2a":"night","#ff6b35":"sunset","#1a0a2e":"purple","#2d5a27":"matrix","#8b0000":"blood","#000000":"void"};function oe({checked:s,onChange:a}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,onChange:t=>a(t.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function be({options:s,value:a,onChange:t,iconOnly:o=!1}){return e.jsx("div",{className:"chip-selector",children:s.map(d=>e.jsxs("button",{className:`chip ${a===d.value?"active":""}`,onClick:()=>t(d.value),title:d.label,children:[e.jsx("span",{className:"chip-icon",children:d.icon}),!o&&e.jsx("span",{className:"chip-label",children:d.label})]},d.value))})}function I({text:s,query:a}){if(!a.trim())return e.jsx(e.Fragment,{children:s});const t=s.toLowerCase(),o=a.toLowerCase(),d=t.indexOf(o);if(d===-1)return e.jsx(e.Fragment,{children:s});const r=s.slice(0,d),c=s.slice(d,d+a.length),b=s.slice(d+a.length);return e.jsxs(e.Fragment,{children:[r,e.jsx("mark",{className:"search-highlight",children:c}),b]})}const aa=[{id:"general",title:"General",keywords:["history","hide costs","grid","fps","power saving","performance","limit","editor","external editor","language","idioma","语言","vibration","haptic","intensity","tab title","tmux","process persistence","interactive","tui","terminal","experimental","claude"]},{id:"agentNames",title:"Agent Names",keywords:["agent","names","custom","characters","rename"]},{id:"defaultClass",title:"Default Spawn Class",keywords:["default","class","spawn","agent","scout","builder","random"]},{id:"appearance",title:"Appearance",keywords:["theme","appearance","color","dark","light","style","look"]},{id:"connection",title:"Connection",keywords:["backend","url","auth","token","reconnect","server","api","connect","codex","opencode","binary","path"]},{id:"scene",title:"Scene",keywords:["character","size","indicator","scale","time","dawn","day","dusk","night","auto"]},{id:"terrain",title:"Terrain",keywords:["trees","bushes","house","lamps","grass","clouds","fog","brightness","floor","sky","color","environment","battlefield","size","grid","simple","minimal","dark","clean"]},{id:"modelStyle",title:"Agent Model Style",keywords:["saturation","roughness","metalness","glow","emissive","reflections","wireframe","color mode","material","shader"]},{id:"animations",title:"Animations",keywords:["idle","working","animation","walk","run","sprint","jump","sit","crouch"]},{id:"secrets",title:"Secrets",keywords:["secrets","api","key","password","credentials","env","environment"]},{id:"systemPrompt",title:"System Prompt",keywords:["system","prompt","global","instructions","ai","agent","rules","guidelines"]},{id:"data",title:"Data",keywords:["export","import","backup","restore","save","load","json"]},{id:"integrations",title:"Integrations",keywords:["integrations","integraciones","plugins","gmail","slack","jira","calendar","docx","email","whatsapp","notifications","notification","baileys","history","historial","chat","messages","inbox","config","setup"]},{id:"workflows",title:"Workflows",keywords:["workflow","automation","state machine","editor","actions","transitions","pipeline"]},{id:"triggers",title:"Triggers",keywords:["trigger","event","webhook","cron","slack","email","jira","matching","fire"]},{id:"monitoring",title:"Monitoring",keywords:["monitoring","logs","triggers","events","history","workflow","traces","audit","timeline"]},{id:"statistics",title:"Statistics",keywords:["statistics","stats","usage","tokens","token","claude","chart","graph","pie","cost"]},{id:"experimental",title:"Experimental",keywords:["experimental","2d","view","voice","assistant","speech","tts","text to speech","echo","prompt","duplicate"]},{id:"about",title:"About",keywords:["about","version","update","credits","github","releases"]}],Be=[{value:"auto",label:"Auto",icon:"🌐"},{value:"en",label:"English",icon:"🇺🇸"},{value:"zh-CN",label:"中文",icon:"🇨🇳"},{value:"es",label:"Español",icon:"🇪🇸"},{value:"hi",label:"हिन्दी",icon:"🇮🇳"},{value:"pt",label:"Português",icon:"🇧🇷"},{value:"ru",label:"Русский",icon:"🇷🇺"},{value:"ja",label:"日本語",icon:"🇯🇵"},{value:"de",label:"Deutsch",icon:"🇩🇪"},{value:"fr",label:"Français",icon:"🇫🇷"},{value:"it",label:"Italiano",icon:"🇮🇹"}];function na({config:s,onChange:a,searchQuery:t="",onOpenIntegrationsModal:o,onOpenMonitoringModal:d,onOpenStatisticsModal:r,onOpenWorkflowEditor:c,onOpenTriggerManager:b}){var Ge;const{t:i}=Z(["config","common"]),j=Ke(),y=$s(),[S,u]=l.useState(()=>Ds(Ne.DEFAULT_AGENT_CLASS)||"scout"),[f,x]=l.useState(j.settings.historyLimit),[h,g]=l.useState(()=>Fs()),[p,A]=l.useState(!1),[M,F]=l.useState(""),[H,v]=l.useState(()=>se()),[U,B]=l.useState(!1),[W,k]=l.useState(!1),[O,K]=l.useState(""),[q,te]=l.useState(!1),[N,$]=l.useState(!1),[V,w]=l.useState(!1),[L,D]=l.useState(!1),[Q,ee]=l.useState(!1),[T,C]=l.useState(""),[Y,ae]=l.useState(!1);l.useEffect(()=>{lt().then(C).catch(()=>{})},[]),l.useEffect(()=>{it().then(n=>{n!==j.settings.experimentalEchoPrompt&&_.updateSettings({experimentalEchoPrompt:n})}).catch(()=>{})},[]),l.useEffect(()=>{rt().then(n=>{n!==j.settings.tmuxMode&&_.updateSettings({tmuxMode:n})}).catch(()=>{})},[]),l.useEffect(()=>{ut().then(n=>{n!==j.settings.interactiveMode&&_.updateSettings({interactiveMode:n})}).catch(()=>{})},[]),l.useEffect(()=>Os(n=>{g(n),A(!1)}),[]);const le=Wt.map(n=>({...n,label:i(`config:time.${n.value}`)})),ne=Gt.map(n=>({...n,label:i(`config:floor.${ea[n.value]||n.value}`)})),ue=Yt.map(n=>({...n,label:i(`config:animation.${sa[n.value]||n.value}`)})),je=Jt.map(n=>({...n,label:i(`config:colorMode.${n.value}`)})),ve=Zt.map(n=>({...n,label:i(`config:terrain.${Qt[n.key]}`)})),re=Xt.map(n=>({...n,label:i(`config:sky.${ta[n.value??""]}`)})),me=t.trim()?aa.filter(n=>{const z=t.toLowerCase();return n.title.toLowerCase().includes(z)||n.keywords.some(de=>de.toLowerCase().includes(z))}).map(n=>n.id):null,E=n=>me?me.includes(n):!0,pe=E("integrations"),ce=j.settings.customAgentNames||[],$e=ce.length>0?ce:Rs,ge=()=>{const n=O.trim();n&&!ce.includes(n)&&(_.updateSettings({customAgentNames:[...ce,n]}),K(""))},De=n=>{_.updateSettings({customAgentNames:ce.filter(z=>z!==n)})},Fe=()=>{_.updateSettings({customAgentNames:[]})},Se=()=>{const n=M.trim();if(n){if(h.includes(n)){F("");return}g([...h,n]),A(!0),F("")}},Oe=n=>{g(h.filter((z,de)=>de!==n)),A(!0)},we=(n,z)=>{const de=n+z;if(de<0||de>=h.length)return;const xe=h.slice();[xe[n],xe[de]]=[xe[de],xe[n]],g(xe),A(!0)},Ae=()=>{zs(h),A(!1),Me()},Te=n=>{v(n),B(!0)},_e=()=>{Ee(Ne.AUTH_TOKEN,H),B(!1),Me()},Re=n=>{C(n),ae(!0)},Ie=()=>{ct(T).catch(()=>{}),ae(!1)},m=n=>{a({...s,terrain:{...s.terrain,...n}})},R=n=>{a({...s,modelStyle:{...s.modelStyle,...n}})},ie=n=>{a({...s,animations:{...s.animations,...n}})},fe=n=>{x(n),_.updateSettings({historyLimit:n})},hs=n=>{const z=s.terrain[n];typeof z=="boolean"&&m({[n]:!z})},J=t.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-section",children:[me&&me.length===0&&e.jsx("div",{className:"config-no-results",children:i("config:noResults",{query:t})}),E("general")&&e.jsxs(G,{title:i("config:sections.general"),storageKey:"general",defaultOpen:!0,forceOpen:J&&E("general"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.history"),query:t})}),e.jsx("input",{type:"number",className:"config-input config-input-sm",value:f,onChange:n=>fe(parseInt(n.target.value)||100),min:50,max:2e3,step:50})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.hideCosts"),query:t})}),e.jsx(oe,{checked:j.settings.hideCost,onChange:n=>_.updateSettings({hideCost:n})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.grid"),query:t})}),e.jsx(oe,{checked:s.gridVisible,onChange:n=>a({...s,gridVisible:n})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.showFPS"),query:t})}),e.jsx(oe,{checked:j.settings.showFPS,onChange:n=>_.updateSettings({showFPS:n})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.fpsLimit"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"120",step:"10",value:s.fpsLimit,onChange:n=>a({...s,fpsLimit:parseInt(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.fpsLimit===0?"∞":s.fpsLimit})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Experimental: Reduce FPS when idle to save power",children:[e.jsx(I,{text:i("config:general.powerSaving"),query:t})," ",e.jsx(P,{name:"bolt",size:12})]}),e.jsx(oe,{checked:j.settings.powerSaving,onChange:n=>_.updateSettings({powerSaving:n})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:"Wrap agent processes in tmux sessions so they survive server restarts (requires tmux installed)",children:e.jsx(I,{text:i("config:general.tmuxMode"),query:t})}),e.jsx(oe,{checked:j.settings.tmuxMode,onChange:async n=>{_.updateSettings({tmuxMode:n});try{await dt(n)}catch(z){console.error("Failed to sync tmux mode setting to server:",z)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Experimental: run Claude agents as the real interactive `claude` TUI inside tmux, reconstructing the conversation from the session transcript (requires tmux). Takes effect on server restart.",children:[e.jsx(I,{text:i("config:general.interactiveMode"),query:t})," ",e.jsx(P,{name:"bolt",size:12})]}),e.jsx(oe,{checked:j.settings.interactiveMode,onChange:async n=>{_.updateSettings({interactiveMode:n});try{await pt(n)}catch(z){console.error("Failed to sync interactive mode setting to server:",z)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.vibrationIntensity"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"5",step:"1",value:j.settings.vibrationIntensity,onChange:n=>_.updateSettings({vibrationIntensity:parseInt(n.target.value)})}),e.jsx("span",{className:"config-value",children:j.settings.vibrationIntensity===0?i("config:vibrationValues.off"):j.settings.vibrationIntensity===1?i("config:vibrationValues.ultraLight"):j.settings.vibrationIntensity===2?i("config:vibrationValues.veryLight"):j.settings.vibrationIntensity===3?i("config:vibrationValues.light"):j.settings.vibrationIntensity===4?i("config:vibrationValues.medium"):i("config:vibrationValues.heavy")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.externalEditor"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:i("config:general.externalEditorPlaceholder"),value:j.settings.externalEditorCommand||"",onChange:n=>_.updateSettings({externalEditorCommand:n.target.value})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.tabTitle"),query:t})}),e.jsx("input",{type:"text",className:"config-input",placeholder:i("config:general.tabTitlePlaceholder"),value:j.settings.tabTitle||"",onChange:n=>_.updateSettings({tabTitle:n.target.value})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:general.language"),query:t})}),e.jsx(be,{options:Be,value:localStorage.getItem("tide-commander-language-mode")==="manual"?((Ge=Be.find(n=>n.value!=="auto"&&ze.language.startsWith(n.value.split("-")[0])))==null?void 0:Ge.value)||"en":"auto",onChange:n=>{var z;if(n==="auto"){localStorage.setItem("tide-commander-language-mode","auto");const de=navigator.language,xe=((z=Be.find(Ye=>Ye.value!=="auto"&&de.startsWith(Ye.value.split("-")[0])))==null?void 0:z.value)||"en";ze.changeLanguage(xe)}else localStorage.setItem("tide-commander-language-mode","manual"),ze.changeLanguage(n)}})]})]}),E("agentNames")&&e.jsx(G,{title:i("config:sections.agentNames"),storageKey:"agentNames",defaultOpen:!1,forceOpen:J&&E("agentNames"),children:e.jsxs("div",{className:"agent-names-section",children:[e.jsx("span",{className:"config-hint",children:ce.length>0?i("config:agentNames.customConfigured",{count:ce.length}):i("config:agentNames.usingDefaults")}),e.jsxs("div",{className:"agent-names-input-row",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",placeholder:i("config:agentNames.addPlaceholder"),value:O,onChange:n=>K(n.target.value),onKeyDown:n=>{n.key==="Enter"&&ge()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:ge,disabled:!O.trim(),title:i("config:agentNames.addName"),children:"+"})]}),e.jsx("div",{className:"agent-names-list",children:$e.map((n,z)=>e.jsxs("div",{className:"agent-name-chip",children:[e.jsx("span",{className:"agent-name-text",children:n}),ce.length>0&&e.jsx("button",{className:"agent-name-remove",onClick:()=>De(n),title:i("common:buttons.remove"),children:"x"})]},`${n}-${z}`))}),ce.length>0&&e.jsx("button",{className:"config-btn config-btn-link",onClick:Fe,children:i("common:buttons.resetToDefaults")})]})}),E("defaultClass")&&e.jsx(G,{title:"Default Spawn Class",storageKey:"defaultClass",defaultOpen:!1,forceOpen:J&&E("defaultClass"),children:e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-hint",children:'Class pre-selected when the spawn modal opens. "Random" picks a different class each time.'}),e.jsxs("div",{className:"agent-names-list",style:{flexWrap:"wrap",gap:"6px",marginTop:"8px"},children:[e.jsx("div",{className:`agent-name-chip${S==="random"?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{u("random"),Ee(Ne.DEFAULT_AGENT_CLASS,"random")},children:e.jsx("span",{className:"agent-name-text",children:"🎲 Random"})}),Object.entries(Us).map(([n,z])=>e.jsx("div",{className:`agent-name-chip${S===n?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{u(n),Ee(Ne.DEFAULT_AGENT_CLASS,n)},children:e.jsxs("span",{className:"agent-name-text",children:[z.icon," ",n.charAt(0).toUpperCase()+n.slice(1)]})},n)),y.map(n=>e.jsx("div",{className:`agent-name-chip${S===n.id?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{u(n.id),Ee(Ne.DEFAULT_AGENT_CLASS,n.id)},children:e.jsxs("span",{className:"agent-name-text",children:[n.icon," ",n.name]})},n.id))]})]})}),E("appearance")&&e.jsx(G,{title:i("config:sections.appearance"),storageKey:"appearance",defaultOpen:!1,forceOpen:J&&E("appearance"),children:e.jsx(xt,{})}),E("connection")&&e.jsxs(G,{title:i("config:sections.connection"),storageKey:"connection",defaultOpen:!1,forceOpen:J&&E("connection"),children:[e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:connection.backendUrl"),query:t})}),e.jsx("div",{className:"backend-urls-list",children:h.map((n,z)=>e.jsxs("div",{className:"backend-url-row",children:[e.jsx("span",{className:"backend-url-priority",title:i("config:connection.priorityLabel",{defaultValue:"Priority"}),children:z+1}),e.jsx("span",{className:"backend-url-text",title:n,children:n}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>we(z,-1),disabled:z===0,title:i("config:connection.moveUp",{defaultValue:"Move up"}),children:"↑"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>we(z,1),disabled:z===h.length-1,title:i("config:connection.moveDown",{defaultValue:"Move down"}),children:"↓"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Oe(z),title:i("common:buttons.remove"),children:"x"})]},`${n}-${z}`))}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:M,onChange:n=>F(n.target.value),placeholder:i("config:connection.addUrlPlaceholder",{defaultValue:"http://host:port"}),onKeyDown:n=>{n.key==="Enter"&&Se()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:Se,disabled:!M.trim(),title:i("config:connection.addUrl",{defaultValue:"Add URL"}),children:"+"}),p&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ae,title:i("config:connection.saveAndReconnect"),children:i("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:i("config:connection.urlsHint",{defaultValue:"Tried in order on connect; the first reachable host wins. Leave empty for auto-detect."})})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:connection.authToken"),query:t})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:W?"text":"password",className:"config-input config-input-full",value:H,onChange:n=>Te(n.target.value),placeholder:i("config:connection.tokenPlaceholder"),onKeyDown:n=>{n.key==="Enter"&&U&&_e()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>k(!W),title:i(W?"config:connection.hideToken":"config:connection.showToken"),children:e.jsx(P,{name:W?"eye-closed":"eye",size:14})}),U&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:_e,title:i("config:connection.saveAndReconnect"),children:i("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:i("config:connection.tokenRequired")})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:connection.codexBinaryPath"),query:t})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:T,onChange:n=>Re(n.target.value),placeholder:i("config:connection.codexBinaryPathPlaceholder"),onKeyDown:n=>{n.key==="Enter"&&Y&&Ie()}}),Y&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:Ie,children:i("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:i("config:connection.codexBinaryPathHint")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("common:buttons.reconnect"),query:t})}),e.jsx("button",{className:"config-btn",onClick:()=>Me(),title:"Force reconnect to server",children:i("common:buttons.reconnect")})]})]}),E("scene")&&e.jsxs(G,{title:i("config:sections.scene"),storageKey:"scene",defaultOpen:!1,forceOpen:J&&E("scene"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:scene.characterSize"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"3.0",step:"0.1",value:s.characterScale,onChange:n=>a({...s,characterScale:parseFloat(n.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.characterScale.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:scene.scale2d",{defaultValue:"2D Scale"}),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale2d,onChange:n=>a({...s,scale2d:parseFloat(n.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.scale2d.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:scene.scale3d",{defaultValue:"3D Scale"}),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale3d,onChange:n=>a({...s,scale3d:parseFloat(n.target.value)})}),e.jsxs("span",{className:"config-value",children:[s.scale3d.toFixed(1),"x"]})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:scene.show2DTaskLabels",{defaultValue:"Show 2D task labels"}),query:t})}),e.jsx(oe,{checked:s.show2DTaskLabels,onChange:n=>a({...s,show2DTaskLabels:n})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:scene.time"),query:t})}),e.jsx(be,{options:le,value:s.timeMode,onChange:n=>a({...s,timeMode:n}),iconOnly:!0})]})]}),E("terrain")&&e.jsxs(G,{title:i("config:sections.terrain"),storageKey:"terrain",defaultOpen:!1,forceOpen:J&&E("terrain"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:terrainSettings.simpleMode",{defaultValue:"Simple Mode"}),query:t})}),e.jsx(oe,{checked:s.terrain.simpleMode??!1,onChange:n=>m({simpleMode:n})})]}),e.jsx("div",{className:"terrain-icons",style:{opacity:s.terrain.simpleMode?.4:1,pointerEvents:s.terrain.simpleMode?"none":"auto"},children:ve.map(n=>e.jsx("button",{className:`terrain-icon-btn ${s.terrain[n.key]?"active":""}`,onClick:()=>hs(n.key),title:n.label,children:n.icon},n.key))}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:terrainSettings.fog"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.terrain.fogDensity,onChange:n=>m({fogDensity:parseFloat(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.fogDensity===0?i("config:fogValues.off"):s.terrain.fogDensity<=1?i("config:fogValues.low"):i("config:fogValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:terrainSettings.brightness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.2",max:"2",step:"0.1",value:s.terrain.brightness,onChange:n=>m({brightness:parseFloat(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.brightness<=.5?i("config:brightnessValues.dark"):s.terrain.brightness<=1.2?i("config:brightnessValues.normal"):i("config:brightnessValues.bright")})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:terrainSettings.floor"),query:t})}),e.jsx(be,{options:ne,value:s.terrain.floorStyle,onChange:n=>m({floorStyle:n}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:terrainSettings.sky"),query:t})}),e.jsx("div",{className:"sky-color-selector",children:re.map(n=>e.jsx("button",{className:`sky-color-btn ${s.terrain.skyColor===n.value?"active":""}`,onClick:()=>m({skyColor:n.value}),title:n.label,style:{background:n.color}},n.value??"auto"))})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:terrainSettings.battlefieldSize"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"30",max:"200",step:"10",value:s.terrain.battlefieldSize,onChange:n=>m({battlefieldSize:parseInt(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.battlefieldSize})]})]}),E("modelStyle")&&e.jsxs(G,{title:i("config:sections.modelStyle"),storageKey:"modelStyle",defaultOpen:!1,forceOpen:J&&E("modelStyle"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:modelStyleSettings.saturation"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.modelStyle.saturation,onChange:n=>R({saturation:parseFloat(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.saturation<=.3?i("config:saturationValues.gray"):s.modelStyle.saturation<=1.2?i("config:saturationValues.normal"):i("config:saturationValues.vivid")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:modelStyleSettings.roughness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.roughness,onChange:n=>R({roughness:parseFloat(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.roughness<0?i("config:roughnessValues.auto"):s.modelStyle.roughness<=.3?i("config:roughnessValues.glossy"):s.modelStyle.roughness<=.7?i("config:roughnessValues.normal"):i("config:roughnessValues.matte")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:modelStyleSettings.metalness"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.metalness,onChange:n=>R({metalness:parseFloat(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.metalness<0?i("config:metalnessValues.auto"):s.modelStyle.metalness<=.3?i("config:metalnessValues.plastic"):s.modelStyle.metalness<=.7?i("config:metalnessValues.mixed"):i("config:metalnessValues.metal")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:modelStyleSettings.glow"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"1",step:"0.05",value:s.modelStyle.emissiveBoost,onChange:n=>R({emissiveBoost:parseFloat(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.emissiveBoost<=.1?i("config:glowValues.off"):s.modelStyle.emissiveBoost<=.4?i("config:glowValues.low"):s.modelStyle.emissiveBoost<=.7?i("config:glowValues.med"):i("config:glowValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:modelStyleSettings.reflections"),query:t})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"2",step:"0.1",value:s.modelStyle.envMapIntensity,onChange:n=>R({envMapIntensity:parseFloat(n.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.envMapIntensity<0?i("config:reflectionValues.auto"):s.modelStyle.envMapIntensity<=.3?i("config:reflectionValues.low"):s.modelStyle.envMapIntensity<=1?i("config:reflectionValues.normal"):i("config:reflectionValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:modelStyleSettings.wireframe"),query:t})}),e.jsx(oe,{checked:s.modelStyle.wireframe,onChange:n=>R({wireframe:n})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:modelStyleSettings.colorMode"),query:t})}),e.jsx(be,{options:je,value:s.modelStyle.colorMode,onChange:n=>R({colorMode:n}),iconOnly:!0})]})]}),E("animations")&&e.jsxs(G,{title:i("config:sections.animations"),storageKey:"animations",defaultOpen:!1,forceOpen:J&&E("animations"),children:[e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:animationSettings.idle"),query:t})}),e.jsx(be,{options:ue,value:s.animations.idleAnimation,onChange:n=>ie({idleAnimation:n}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:animationSettings.working"),query:t})}),e.jsx(be,{options:ue,value:s.animations.workingAnimation,onChange:n=>ie({workingAnimation:n}),iconOnly:!0})]})]}),E("secrets")&&e.jsx(G,{title:i("config:sections.secrets"),storageKey:"secrets",defaultOpen:!1,forceOpen:J&&E("secrets"),children:e.jsx(st,{})}),E("systemPrompt")&&e.jsx(G,{title:i("config:sections.systemPrompt"),storageKey:"systemPrompt",defaultOpen:!1,forceOpen:J&&E("systemPrompt"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(I,{text:i("config:systemPrompt.title"),query:t})}),e.jsx("button",{className:"config-button",onClick:()=>te(!0),children:i("config:systemPrompt.editPrompt")})]})}),E("data")&&e.jsx(G,{title:i("config:sections.data"),storageKey:"data",defaultOpen:!1,forceOpen:J&&E("data"),children:e.jsx(ft,{})}),pe&&e.jsx(G,{title:i("config:sections.integrations"),storageKey:"integrations",defaultOpen:!1,forceOpen:J&&pe,children:e.jsx(wt,{onOpenModal:n=>{n==="whatsapp"?ee(!0):o==null||o(n)}})}),E("workflows")&&e.jsxs(G,{title:"Workflows",storageKey:"workflows",defaultOpen:!1,forceOpen:J&&E("workflows"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"Create and manage automated workflow pipelines with visual state machine editor",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>c==null?void 0:c(),children:"Open Workflow Editor"})})]}),E("triggers")&&e.jsxs(G,{title:"Triggers",storageKey:"triggers",defaultOpen:!1,forceOpen:J&&E("triggers"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"Create and manage event-driven triggers that fire agents with templates",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>b==null?void 0:b(),children:"Open Trigger Manager"})})]}),E("monitoring")&&e.jsxs(G,{title:"Monitoring",storageKey:"monitoring",defaultOpen:!1,forceOpen:J&&E("monitoring"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"View event logs, trigger history, workflow traces, and system stats",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>d==null?void 0:d(),children:"Open Monitoring & Logs"})})]}),E("statistics")&&e.jsxs(G,{title:"Statistics",storageKey:"statistics",defaultOpen:!1,forceOpen:J&&E("statistics"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(I,{text:"View token usage charts and system-wide agent statistics",query:t})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>r==null?void 0:r(),children:"Open Statistics"})})]}),E("experimental")&&e.jsxs(G,{title:i("config:sections.experimental"),storageKey:"experimental",defaultOpen:!1,forceOpen:J&&E("experimental"),children:[e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Lightweight 2D top-down view for better performance",children:[e.jsx(I,{text:i("config:experimental.2dView"),query:t})," ",e.jsx(P,{name:"map",size:12})]}),e.jsx(oe,{checked:j.settings.experimental2DView,onChange:n=>_.updateSettings({experimental2DView:n})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Voice assistant for hands-free agent control",children:[e.jsx(I,{text:i("config:experimental.voiceAssistant"),query:t})," ",e.jsx(P,{name:"microphone",size:12})]}),e.jsx(oe,{checked:j.settings.experimentalVoiceAssistant,onChange:n=>_.updateSettings({experimentalVoiceAssistant:n})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Text-to-speech for reading agent responses",children:[e.jsx(I,{text:i("config:experimental.tts"),query:t})," ",e.jsx(P,{name:"speaker-on",size:12})]}),e.jsx(oe,{checked:j.settings.experimentalTTS,onChange:n=>_.updateSettings({experimentalTTS:n})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",title:"Duplicate system prompt for improved LLM attention coverage. Increases input token usage.",children:e.jsx(I,{text:i("config:experimental.echoPrompt"),query:t})}),e.jsx(oe,{checked:j.settings.experimentalEchoPrompt,onChange:async n=>{_.updateSettings({experimentalEchoPrompt:n});try{await ot(n)}catch(z){console.error("Failed to sync echo prompt setting to server:",z)}}})]}),e.jsx("span",{className:"config-hint",children:i("config:experimental.hint")})]}),E("about")&&e.jsx(G,{title:i("config:sections.about"),storageKey:"about",defaultOpen:!1,forceOpen:J&&E("about"),children:e.jsx(jt,{})})]}),e.jsx(Nt,{isOpen:q,onClose:()=>te(!1)}),e.jsx(St,{isOpen:N,onClose:()=>$(!1)}),e.jsx(Et,{isOpen:V,onClose:()=>w(!1)}),e.jsx(Ht,{isOpen:L,onClose:()=>D(!1)}),e.jsx(qt,{isOpen:Q,onClose:()=>ee(!1),onOpenConfig:()=>$(!0),onOpenNotifications:()=>w(!0),onOpenHistory:()=>D(!0)})]})}function ra({onConfigChange:s,onToolChange:a,config:t,isOpen:o,onClose:d,onOpenBuildingModal:r,onOpenAreaExplorer:c,onOpenIntegrationsModal:b,onOpenMonitoringModal:i,onOpenStatisticsModal:j,onOpenWorkflowEditor:y,onOpenTriggerManager:S}){const{t:u}=Z(["config","common"]),f=Ke(),x=Array.from(f.areas.values()),h=Array.from(f.buildings.values()),[g,p]=l.useState(""),A=l.useRef(null);if(l.useEffect(()=>{const v=U=>{U.key==="Escape"&&o&&d()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[o,d]),l.useEffect(()=>{if(o&&A.current){if(typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches)return;const U=setTimeout(()=>{var B;(B=A.current)==null||B.focus()},50);return()=>clearTimeout(U)}},[o]),!o)return null;const M=v=>{const U=f.activeTool===v?null:v;a(U)},F=v=>{_.selectArea(f.selectedAreaId===v?null:v),a("select")},H=(v,U)=>{v.stopPropagation(),_.deleteArea(U)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"toolbox-backdrop",onClick:d}),e.jsxs("aside",{className:"toolbox",children:[e.jsxs("div",{className:"toolbox-header",children:[e.jsx("span",{children:u("config:title")}),e.jsx("button",{className:"toolbox-close-btn",onClick:d,title:u("common:buttons.close"),children:"×"})]}),e.jsxs("div",{className:"toolbox-search",children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"M21 21l-4.35-4.35"})]}),e.jsx("input",{ref:A,type:"text",placeholder:u("config:searchPlaceholder"),value:g,onChange:v=>p(v.target.value),className:"toolbox-search-input"}),g&&e.jsx("button",{className:"toolbox-search-clear",onClick:()=>p(""),children:"×"})]}),e.jsxs("div",{className:"toolbox-content",children:[e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsxs(G,{title:u("config:areas.title",{count:x.length}),storageKey:"areas",children:[e.jsxs("div",{className:"tool-buttons",children:[e.jsx("button",{className:`tool-btn ${f.activeTool==="select"?"active":""}`,onClick:()=>M("select"),title:u("config:tools.select"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"})})})}),e.jsx("button",{className:`tool-btn ${f.activeTool==="rectangle"?"active":""}`,onClick:()=>M("rectangle"),title:u("config:tools.rectangle"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",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("button",{className:`tool-btn ${f.activeTool==="circle"?"active":""}`,onClick:()=>M("circle"),title:u("config:tools.circle"),children:e.jsx("span",{children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("circle",{cx:"12",cy:"12",r:"9"})})})})]}),e.jsx("div",{className:"areas-list",children:x.length===0?e.jsx("div",{className:"areas-empty",children:u("config:areas.drawToCreate")}):x.map(v=>e.jsx(Js,{area:v,isSelected:f.selectedAreaId===v.id,onClick:()=>F(v.id),onDelete:U=>H(U,v.id)},v.id))})]})}),f.selectedAreaId&&e.jsx(et,{area:f.areas.get(f.selectedAreaId),onClose:()=>_.selectArea(null),onOpenFolder:c}),e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsx(G,{title:u("config:buildings.title",{count:h.length}),storageKey:"buildings",headerExtra:e.jsx("button",{className:"add-building-btn",onClick:v=>{v.stopPropagation(),r==null||r()},title:u("config:buildings.addBuilding"),children:"+"}),children:e.jsx("div",{className:"buildings-list",children:h.length===0?e.jsx("div",{className:"buildings-empty",children:u("config:buildings.clickToAdd")}):h.map(v=>e.jsx(Zs,{building:v,isSelected:f.selectedBuildingIds.has(v.id),onClick:()=>{_.selectBuilding(f.selectedBuildingIds.has(v.id)?null:v.id)},onEdit:()=>r==null?void 0:r(v.id)},v.id))})})}),f.selectedBuildingIds.size===1&&(()=>{const v=Array.from(f.selectedBuildingIds)[0],U=f.buildings.get(v);return U?e.jsx(Xs,{building:U,onClose:()=>_.selectBuilding(null),onOpenModal:()=>r==null?void 0:r(v)}):null})(),e.jsx(na,{config:t,onChange:s,searchQuery:g,onOpenIntegrationsModal:b,onOpenMonitoringModal:i,onOpenStatisticsModal:j,onOpenWorkflowEditor:y,onOpenTriggerManager:S})]})]})]})}export{ra as Toolbox};