tide-commander 1.84.2 → 1.84.4

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 (39) hide show
  1. package/dist/assets/{BossLogsModal-CbPseg-c.js → BossLogsModal-RKUS5he3.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-CXcaXAij.js → BossSpawnModal-Z-KIzG1l.js} +1 -1
  3. package/dist/assets/{ControlsModal-BYUbRQcz.js → ControlsModal-sWKF7juv.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-BxlBxk13.js → DockerLogsModal-Chv6wO7i.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor--JOJfC7s.js → EmbeddedEditor-BnJunhJ5.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-DF8Frc6X.js → GmailOAuthSetup-CD24tWFR.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-DxZLW8IT.js → GoogleOAuthSetup-D7lmU7_z.js} +1 -1
  8. package/dist/assets/{IframeModal-DmnSRljV.js → IframeModal-B7M2Iclq.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-iiKDU2g_.js → IntegrationsPanel-BXniP3m6.js} +2 -2
  10. package/dist/assets/{LogViewerModal-DoxVD2wb.js → LogViewerModal-BkbO5Lcx.js} +1 -1
  11. package/dist/assets/{MonitoringModal-HwuPAK8z.js → MonitoringModal-BLwOrxXn.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-Chx1wmpC.js → PM2LogsModal-Cc5muLh8.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-DGTRZ7H7.js → RestoreArchivedAreaModal-C2kLOEom.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-NCptTu5l.js → Scene2DCanvas-B_ILFcMh.js} +1 -1
  15. package/dist/assets/{SceneManager-CwvQOFBU.js → SceneManager-C24V9ffc.js} +1 -1
  16. package/dist/assets/{SkillsPanel-CNbLb0Fu.js → SkillsPanel-B7M9i9GP.js} +2 -2
  17. package/dist/assets/{SpawnModal-DAjrIVss.js → SpawnModal-C47v5dNY.js} +1 -1
  18. package/dist/assets/{SubordinateAssignmentModal-5HP1CzQT.js → SubordinateAssignmentModal-KRP5mXby.js} +1 -1
  19. package/dist/assets/{TriggerManagerPanel-VSxCT-cD.js → TriggerManagerPanel-CLmwH7fs.js} +2 -2
  20. package/dist/assets/{WorkflowEditorPanel-DfXfdv46.js → WorkflowEditorPanel-CFubZORK.js} +2 -2
  21. package/dist/assets/{index-CdSYWPJD.js → index-5oP0HT38.js} +3 -3
  22. package/dist/assets/index-7TgA90RK.js +1 -0
  23. package/dist/assets/index-BEc3pZNf.js +1 -0
  24. package/dist/assets/{index-BEmul9y0.js → index-C0L5LEWi.js} +4 -4
  25. package/dist/assets/{index-DYml8LTk.js → index-CO5NGvTa.js} +1 -1
  26. package/dist/assets/index-CmE9RJAK.css +1 -0
  27. package/dist/assets/index-CztWNLcY.js +2 -0
  28. package/dist/assets/{index-0eWL2WB3.js → index-D3lbWfGO.js} +2 -2
  29. package/dist/assets/{index-BiAN1sxE.js → index-D94lnP2P.js} +5 -5
  30. package/dist/assets/{index-BfWMRkdP.js → index-DQVaH0CS.js} +1 -1
  31. package/dist/assets/{main-BlnQCHb9.js → main-DFVcOIIz.js} +4 -4
  32. package/dist/assets/{web-W5mpcw2a.js → web-BRpVSwLu.js} +1 -1
  33. package/dist/assets/{web-C-VeqfnM.js → web-DskROW-O.js} +1 -1
  34. package/dist/index.html +1 -1
  35. package/package.json +1 -1
  36. package/dist/assets/index-BR9_mEVJ.css +0 -1
  37. package/dist/assets/index-Bwtfr8vQ.js +0 -1
  38. package/dist/assets/index-DRsHxeh_.js +0 -1
  39. package/dist/assets/index-PmiCO3k8.js +0 -2
@@ -0,0 +1 @@
1
+ import{a9 as as,u as ts,ap as vs,aq as bs,ar as zs,j as s,I as F,Y as Is,as as Es,at as $s,au as Ds,av as Ms,r as c,a0 as Ls,af as Ps,P as Ss,O as Xs,E as Ys,aw as Rs,ax as Gs,ay as Us,az as ms,aA as _s,s as M,aB as Fs,n as U}from"./main-DFVcOIIz.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const fs=as.memo(({agent:a,isSelected:A,isKeyboardFocused:L=!1,onSelect:P,onDoubleClick:n,onChat:g,onFocus:h,onKill:w,onDragStart:S})=>{const{t:x}=ts(["dashboard","common"]),X=vs().has(a.id),N=bs(a.status),B=zs(a),j=Ms(B),I=a.taskLabel?s.jsxs(s.Fragment,{children:[s.jsx(F,{name:"task",size:12})," ",a.taskLabel]}):a.currentTask||a.lastAssignedTask,m=a.status==="idle"&&a.lastActivity>0,[,H]=as.useState(0);return as.useEffect(()=>{if(!m)return;const b=window.setInterval(()=>H(T=>T+1),15e3);return()=>window.clearInterval(b)},[m]),s.jsxs("div",{className:`dash-card dash-card--${N} ${A?"dash-card--selected":""} ${L?"dash-card--keyboard-focused":""}`,"data-agent-id":a.id,onClick:P,onDoubleClick:b=>{b.stopPropagation(),n()},onDragStart:b=>{S==null||S(a),b.dataTransfer.effectAllowed="move"},draggable:!0,title:x("cards.doubleClickHint"),children:[s.jsxs("div",{className:"dash-card__row1",children:[s.jsx("span",{className:`dash-card__status-dot dash-card__status-dot--${N}`}),s.jsx("span",{className:"dash-card__name",children:a.name}),s.jsxs("span",{className:"dash-card__class",children:[s.jsx(Is,{agent:a,size:14})," ",a.class]}),s.jsxs("span",{className:`dash-card__provider dash-card__provider--${a.provider}`,children:[s.jsx(F,{name:a.provider==="codex"||a.provider==="opencode"?"status-pending":"robot",size:11,weight:a.provider==="codex"||a.provider==="opencode"?"fill":"regular",color:a.provider==="codex"?"#a16207":a.provider==="opencode"?"#4ade80":void 0})," ",a.provider]}),X&&s.jsx("span",{className:"dash-card__unseen-badge",title:"New output available - click to view",children:"!"})]}),s.jsxs("div",{className:"dash-card__row2",children:[s.jsx("span",{className:`dash-card__status dash-card__status--${N}`,children:X?"Unseen":a.status}),s.jsxs("div",{className:"dash-card__context",children:[s.jsx("div",{className:"dash-card__context-bar",children:s.jsx("div",{className:`dash-card__context-fill dash-card__context-fill--${j}`,style:{width:`${B}%`}})}),s.jsxs("span",{className:`dash-card__context-pct dash-card__context-pct--${j}`,children:[B,"%"]})]})]}),s.jsxs("div",{className:"dash-card__row3",children:[s.jsxs("span",{className:"dash-card__workdir",title:a.cwd,children:[s.jsx(F,{name:"folder",size:11})," ",a.cwd.split("/").pop()||a.cwd]}),m&&s.jsxs("span",{className:"dash-card__idle-time",style:{color:Ds(a.lastActivity)},title:$s(a.lastActivity),children:[s.jsx(F,{name:"status-waiting-input",size:10})," ",Es(a.lastActivity)]})]}),I&&s.jsx("div",{className:"dash-card__row4",children:s.jsx("span",{className:"dash-card__task",children:I})}),s.jsxs("div",{className:"dash-card__actions",children:[g&&s.jsx("button",{className:"dash-card__action-btn dash-card__action-btn--chat",onClick:b=>{b.stopPropagation(),g()},title:x("cards.openTerminal"),children:x("cards.chat")}),w&&s.jsx("button",{className:"dash-card__action-btn dash-card__action-btn--danger",onClick:b=>{b.stopPropagation(),w()},title:x("cards.killAgent"),children:x("cards.stop")})]})]})});fs.displayName="AgentCard";const ws=({buildings:a,onSelectBuilding:A})=>{const{t:L}=ts(["dashboard"]),P=c.useMemo(()=>Array.from(a.values()).sort((n,g)=>n.name.localeCompare(g.name)),[a]);return s.jsxs("div",{className:"dashboard-view__buildings",children:[s.jsxs("div",{className:"dashboard-view__buildings-header",children:[s.jsx("span",{className:"dashboard-view__buildings-title",children:L("buildings.title")}),s.jsx("span",{className:"dashboard-view__buildings-count",children:P.length})]}),s.jsx("div",{className:"dashboard-view__buildings-row",children:P.map(n=>{const g=bs(n.status),h=Ls(n.type);return s.jsxs("button",{className:`dash-pill dash-pill--${g}`,onClick:()=>A==null?void 0:A(n.id),title:`${n.name} (${n.type}) - ${n.status}`,children:[s.jsx("span",{className:"dash-pill__icon",children:s.jsx(F,{name:h,size:14})}),s.jsx("span",{className:"dash-pill__name",children:n.name}),s.jsx("span",{className:`dash-pill__dot dash-pill__dot--${g}`})]},n.id)})})]})};ws.displayName="BuildingPills";function Ws({onSelectAgent:a,onFocusAgent:A,onKillAgent:L,onSelectBuilding:P,onOpenTerminal:n,onFocusZone:g}){const{t:h}=ts(["dashboard","common"]),w=Ps(),S=Ss(),x=Xs(),rs=Ys(),X=vs(),[N,B]=c.useState(""),[j,I]=c.useState("all"),[m,H]=c.useState("zone"),[b,T]=c.useState(new Set),[k,J]=c.useState(null),[ps,W]=c.useState(null),[Y,Q]=c.useState(!1),[p,Z]=c.useState(null),K=c.useMemo(()=>{const e=Array.from(w.values());return{total:e.length,working:e.filter(i=>i.status==="working"||i.status==="waiting"||i.status==="waiting_permission").length,idle:e.filter(i=>i.status==="idle").length,error:e.filter(i=>i.status==="error"||i.status==="offline"||i.status==="orphaned").length}},[w]),ns=c.useMemo(()=>m==="zone"?Rs(w,x):m==="status"?Gs(w,X):Us(w),[w,x,m,X]),V=c.useMemo(()=>{const e=N.toLowerCase().trim(),i=ns.map(l=>({...l,agents:l.agents.filter(_=>{if(j==="working"){if(_.status!=="working"&&_.status!=="waiting"&&_.status!=="waiting_permission")return!1}else if(j==="error"&&_.status!=="error"&&_.status!=="offline"&&_.status!=="orphaned")return!1;return!(e&&!_.name.toLowerCase().includes(e)&&!_.class.toLowerCase().includes(e))})}));return m==="zone"?i:i.filter(l=>l.agents.length>0)},[ns,j,N,m]),O=c.useCallback(e=>e.area?`area:${e.area.id}`:`${m}:${e.label}`,[m]),y=c.useMemo(()=>{const e=[];return V.forEach(i=>{const l=O(i);if(b.has(l))return;const _=m==="status"?ms(i.agents,{prioritizeRecentlyIdle:!0}):_s(i.agents);e.push(..._)}),e},[V,b,m,O]),gs=c.useCallback(e=>{T(i=>{const l=new Set(i);return l.has(e)?l.delete(e):l.add(e),l})},[]),xs=c.useCallback(e=>{n==null||n(e)},[n]),js=c.useCallback(e=>{J(e)},[]),Ns=c.useCallback((e,i)=>{e.preventDefault(),e.dataTransfer.dropEffect="move",W(i)},[]),ks=c.useCallback(()=>{W(null)},[]),ys=c.useCallback(e=>{if(!k)return;if(e===null){const E=M.getState(),t=Array.from(E.areas.values()).find(r=>r.assignedAgentIds.includes(k.id));t&&M.unassignAgentFromArea(k.id,t.id),J(null),W(null);return}const i=x.get(e);if(!i)return;const l=Array.from(w.values()),_=Fs(i,l,k.position);M.updateAgent({...k,position:{...k.position,x:_.x,z:_.z}}),M.assignAgentToArea(k.id,e),J(null),W(null)},[k,x,w]);return c.useEffect(()=>{if(y.length===0){Q(!1),Z(null);return}Y&&(!p||!y.some(e=>e.id===p))&&(Z(y[0].id),a==null||a(y[0].id))},[y,Y,p,a]),c.useEffect(()=>{const e=t=>t instanceof HTMLElement?t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable:!1,i=t=>t instanceof HTMLElement?!!t.closest(".guake-terminal")||t.classList.contains("guake-input")||t.classList.contains("agent-panel-input"):!1,l=t=>{const r=Array.from(document.querySelectorAll(".dash-card[data-agent-id]")).find(z=>z.dataset.agentId===t);r==null||r.scrollIntoView({block:"nearest",inline:"nearest"})},_=(t,r)=>{var ds,os,cs,ls,us,hs;const z=Array.from(document.querySelectorAll(".dash-card[data-agent-id]")).map(d=>{const u=d.dataset.agentId;if(!u)return null;const C=d.getBoundingClientRect();return{id:u,centerX:C.left+C.width/2,centerY:C.top+C.height/2,height:C.height}}).filter(d=>d!==null).sort((d,u)=>d.centerY-u.centerY||d.centerX-u.centerX);if(z.length===0)return t;const ss=z.reduce((d,u)=>d+u.height,0)/z.length,es=Math.max(18,ss*.6),f=[];for(const d of z){const u=f[f.length-1];if(!u){f.push([{id:d.id,centerX:d.centerX,centerY:d.centerY}]);continue}const C=u.reduce((Cs,As)=>Cs+As.centerY,0)/u.length;Math.abs(d.centerY-C)<=es?u.push({id:d.id,centerX:d.centerX,centerY:d.centerY}):f.push([{id:d.id,centerX:d.centerX,centerY:d.centerY}])}f.forEach(d=>d.sort((u,C)=>u.centerX-C.centerX));const R=f.findIndex(d=>d.some(u=>u.id===t));if(R===-1)return((os=(ds=f[0])==null?void 0:ds[0])==null?void 0:os.id)??t;const $=f[R],v=$.findIndex(d=>d.id===t);if(v===-1)return((ls=(cs=f[0])==null?void 0:cs[0])==null?void 0:ls.id)??t;if(r==="left")return((us=$[Math.max(0,v-1)])==null?void 0:us.id)??t;if(r==="right")return((hs=$[Math.min($.length-1,v+1)])==null?void 0:hs.id)??t;const q=r==="up"?Math.max(0,R-1):Math.min(f.length-1,R+1),o=f[q],G=$[v].centerX;let D=o[0],is=Math.abs(D.centerX-G);for(const d of o){const u=Math.abs(d.centerX-G);u<is&&(D=d,is=u)}return(D==null?void 0:D.id)??t},E=t=>{const r=M.getShortcuts(),z=r.find(o=>o.id==="dashboard-selector-toggle"),ss=r.find(o=>o.id==="dashboard-vim-left"),es=r.find(o=>o.id==="dashboard-vim-down"),f=r.find(o=>o.id==="dashboard-vim-up"),R=r.find(o=>o.id==="dashboard-vim-right"),$=r.find(o=>o.id==="open-terminal"),v=M.getState();if(e(t.target))if(!v.terminalOpen&&i(t.target)&&document.activeElement instanceof HTMLElement)document.activeElement.blur();else return;if(U(t,z)){if(y.length===0)return;t.preventDefault(),t.stopPropagation(),Q(!0),Z(o=>{const G=o&&y.some(D=>D.id===o)?o:y[0].id;return a==null||a(G),window.setTimeout(()=>l(G),0),G});return}const q=U(t,ss)||t.key==="ArrowLeft"?"left":U(t,es)||t.key==="ArrowDown"?"down":U(t,f)||t.key==="ArrowUp"?"up":U(t,R)||t.key==="ArrowRight"?"right":null;if(q&&Y&&p){t.preventDefault(),t.stopPropagation();const o=_(p,q);o!==p&&(Z(o),a==null||a(o),window.setTimeout(()=>l(o),0));return}if(U(t,$)){if(v.terminalOpen)return;if(Y&&p&&v.agents.has(p)){t.preventDefault(),n==null||n(p);return}if(v.selectedAgentIds.size===1){t.preventDefault();const o=Array.from(v.selectedAgentIds)[0];n==null||n(o);return}if(v.lastSelectedAgentId&&v.agents.has(v.lastSelectedAgentId)){t.preventDefault(),n==null||n(v.lastSelectedAgentId);return}}};return document.addEventListener("keydown",E,!0),()=>document.removeEventListener("keydown",E,!0)},[y,Y,p,n,a]),c.useEffect(()=>{const e=document.activeElement;e instanceof HTMLElement&&e.closest(".guake-terminal")&&!M.getState().terminalOpen&&e.blur()},[]),s.jsxs("div",{className:"dashboard-view",children:[s.jsxs("div",{className:"dashboard-view__topbar",children:[s.jsxs("div",{className:"dashboard-view__metrics",children:[s.jsxs("button",{className:`dashboard-view__metric-btn ${j==="all"?"dashboard-view__metric-btn--active":""}`,onClick:()=>I("all"),children:[s.jsx("span",{className:"dashboard-view__metric-value",children:K.total}),s.jsx("span",{className:"dashboard-view__metric-label",children:h("common:labels.agents")})]}),s.jsxs("button",{className:`dashboard-view__metric-btn dashboard-view__metric-btn--working ${j==="working"?"dashboard-view__metric-btn--active":""}`,onClick:()=>I("working"),children:[s.jsx("span",{className:"dashboard-view__metric-value",children:K.working}),s.jsx("span",{className:"dashboard-view__metric-label",children:h("common:status.working")})]}),s.jsxs("button",{className:"dashboard-view__metric-btn dashboard-view__metric-btn--idle ",onClick:()=>I("all"),children:[s.jsx("span",{className:"dashboard-view__metric-value",children:K.idle}),s.jsx("span",{className:"dashboard-view__metric-label",children:h("common:status.idle")})]}),s.jsxs("button",{className:`dashboard-view__metric-btn dashboard-view__metric-btn--error ${j==="error"?"dashboard-view__metric-btn--active":""}`,onClick:()=>I("error"),children:[s.jsx("span",{className:"dashboard-view__metric-value",children:K.error}),s.jsx("span",{className:"dashboard-view__metric-label",children:h("common:status.error")})]})]}),s.jsx("input",{className:"dashboard-view__search",type:"text",placeholder:h("searchPlaceholder"),value:N,onChange:e=>B(e.target.value)})]}),s.jsxs("div",{className:"dashboard-view__grouping",children:[s.jsx("button",{className:`dashboard-view__grouping-btn ${m==="zone"?"dashboard-view__grouping-btn--active":""}`,onClick:()=>H("zone"),children:h("grouping.byZone")}),s.jsx("button",{className:`dashboard-view__grouping-btn ${m==="status"?"dashboard-view__grouping-btn--active":""}`,onClick:()=>H("status"),children:h("grouping.byStatus")}),s.jsx("button",{className:`dashboard-view__grouping-btn ${m==="activity"?"dashboard-view__grouping-btn--active":""}`,onClick:()=>H("activity"),children:h("grouping.byActivity")})]}),s.jsxs("div",{className:"dashboard-view__content",children:[V.map(e=>{const i=O(e),l=b.has(i),_=m==="status"?ms(e.agents,{prioritizeRecentlyIdle:!0}):_s(e.agents),E=e.agents.filter(r=>r.status==="working"||r.status==="waiting"||r.status==="waiting_permission").length,t=e.agents.filter(r=>X.has(r.id)).length;return s.jsxs("div",{className:`dashboard-view__zone ${ps===(e.area?e.area.id:null)&&k?"dashboard-view__zone--drag-over":""}`,onDragOver:r=>Ns(r,e.area?e.area.id:null),onDragLeave:ks,onDrop:()=>ys(e.area?e.area.id:null),children:[s.jsxs("div",{className:"dashboard-view__zone-header",onClick:()=>gs(i),children:[s.jsxs("div",{className:"dashboard-view__zone-left",children:[s.jsx("span",{className:`dashboard-view__zone-chevron ${l?"dashboard-view__zone-chevron--collapsed":""}`,children:s.jsx(F,{name:"caret-down",size:12})}),s.jsx("span",{className:"dashboard-view__zone-dot",style:{backgroundColor:e.color}}),s.jsx("span",{className:"dashboard-view__zone-name",children:e.label}),s.jsxs("span",{className:"dashboard-view__zone-count",children:[h("agentCount",{count:e.agents.length}),E>0&&s.jsxs("span",{className:"dashboard-view__zone-working",children:[" · ",E," ",h("working")]}),t>0&&s.jsxs("span",{className:"dashboard-view__zone-unseen",children:[" · ",t," Unseen"]})]})]}),e.area&&g&&s.jsx("button",{className:"dashboard-view__zone-focus",onClick:r=>{r.stopPropagation(),g(e.area.id)},title:h("focusZone"),children:h("focusZone")})]}),!l&&s.jsx("div",{className:"dashboard-view__zone-grid",children:_.map(r=>s.jsx(fs,{agent:r,isSelected:rs.has(r.id),isKeyboardFocused:Y&&p===r.id,onSelect:()=>{a==null||a(r.id),Q(!0),Z(r.id)},onDoubleClick:()=>xs(r.id),onChat:()=>n==null?void 0:n(r.id),onFocus:A?()=>A(r.id):void 0,onKill:L?()=>L(r.id):void 0,onDragStart:js},r.id))})]},i)}),V.length===0&&s.jsx("div",{className:"dashboard-view__empty",children:N?h("noAgentsMatching",{search:N}):h("noAgentsSpawned")}),S.size>0&&s.jsx(ws,{buildings:S,onSelectBuilding:P})]})]})}export{Ws as DashboardView};
@@ -0,0 +1 @@
1
+ import{r as l,aR as Fe,aS as Ve,j as e,I as L,u as ee,aT as Je,a0 as Ze,f as Re,s as A,aU as es,k as ss,l as ce,aV as H,aW as as,aK as ts,aX as ns,C as re,aY as Y,aH as je,aZ as is,a_ as os,a$ as ls,b0 as cs,b1 as ze,b2 as rs,b3 as ds,b4 as Me,b5 as ms,b6 as ps,b7 as us,b8 as hs,b9 as gs,ba as fs,bb as xs,aD as bs,G as js,S as be,bc as vs,bd as Ns,aF as ws,be as Oe,H as Se,aO as ys,bf as De,bg as ks}from"./main-DFVcOIIz.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const _e="deivid11/tide-commander",Ss=`https://api.github.com/repos/${_e}/releases/latest`,Cs=`https://api.github.com/repos/${_e}/releases?per_page=3`,As=3600*1e3,qe="app_update_dismissed_version",We="1.84.4";function Ts(){var b,k;const[s,o]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:We}),a=((k=(b=Fe)==null?void 0:b.getPlatform)==null?void 0:k.call(b))==="android"||!1,i=d=>d.replace(/^v/,"").split(".").map(u=>parseInt(u,10)||0),m=(d,g)=>{const u=i(d),y=i(g),x=Math.max(u.length,y.length);for(let c=0;c<x;c++){const F=u[c]||0,z=y[c]||0;if(F>z)return 1;if(F<z)return-1}return 0},f=async d=>{var u,y;if(Fe&&Ve&&((y=(u=Fe).isNativePlatform)==null?void 0:y.call(u))===!0){const x=await Ve.get({url:d,headers:{Accept:"application/vnd.github.v3+json"}});return{data:x.data,status:x.status}}else{const x=await fetch(d,{headers:{Accept:"application/vnd.github.v3+json"}});return x.ok?{data:await x.json(),status:x.status}:{data:null,status:x.status}}},r=l.useCallback(async(d=!1)=>{o(g=>({...g,isChecking:!0,error:null}));try{const[g,u]=await Promise.all([f(Ss),f(Cs)]);if(g.status!==200)throw new Error(`GitHub API error: ${g.status}`);const y=g.data,x=y.tag_name;let c=[];u.status===200&&u.data&&(c=u.data.map(E=>({version:E.tag_name,name:E.name,publishedAt:E.published_at,releaseUrl:E.html_url})));const F=localStorage.getItem(qe);if(!d&&F===x)return o(E=>({...E,isChecking:!1,updateAvailable:!1,recentReleases:c})),null;if(!(m(x,We)>0))return o(E=>({...E,isChecking:!1,updateAvailable:!1,recentReleases:c})),null;const R=y.assets.find(E=>E.name.endsWith(".apk")&&E.content_type==="application/vnd.android.package-archive"),w={version:x,name:y.name,changelog:y.body,releaseUrl:y.html_url,apkUrl:(R==null?void 0:R.browser_download_url)||null,apkSize:(R==null?void 0:R.size)||null,publishedAt:y.published_at};return o(E=>({...E,isChecking:!1,updateAvailable:!0,updateInfo:w,recentReleases:c})),w}catch(g){const u=g instanceof Error?g.message:"Failed to check for updates";return o(y=>({...y,isChecking:!1,error:u})),null}},[]),n=l.useCallback(async()=>{var d,g,u;if(!((d=s.updateInfo)!=null&&d.apkUrl)){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!a){(u=s.updateInfo)!=null&&u.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),o(y=>({...y,error:null}))}catch(y){const x=y instanceof Error?y.message:"Failed to open download";o(c=>({...c,error:x}))}},[s.updateInfo,a]),h=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(qe,s.updateInfo.version),o(d=>({...d,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),I=l.useCallback(()=>{var d;(d=s.updateInfo)!=null&&d.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${_e}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!a)return;const d=setTimeout(()=>{r()},5e3),g=setInterval(()=>{r()},As);return()=>{clearTimeout(d),clearInterval(g)}},[a,r]),{...s,isAndroid:a,checkForUpdate:r,downloadAndInstall:n,dismissUpdate:h,openReleasePage:I}}const Xe="tide-toolbox-collapse";function Es(s,o){try{const a=localStorage.getItem(`${Xe}-${s}`);if(a!==null)return a==="true"}catch{}return o}function Is(s,o){try{localStorage.setItem(`${Xe}-${s}`,String(o))}catch{}}function U({title:s,storageKey:o,defaultOpen:a=!1,forceOpen:i=!1,children:m,headerExtra:f}){const[r,n]=l.useState(()=>o?Es(o,a):a),h=()=>{const b=!r;n(b),o&&Is(o,b)},I=i||r;return e.jsxs("div",{className:`collapsible-section ${I?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:h,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[f,e.jsx("span",{className:"collapsible-arrow",children:e.jsx(L,{name:I?"caret-down":"caret-right",size:10})})]})]}),I&&e.jsx("div",{className:"collapsible-content",children:m})]})}function Ps({area:s,isSelected:o,onClick:a,onDelete:i}){const{t:m}=ee(["config","common"]),f=s.assignedAgentIds.length,r=s.type==="rectangle"?m("config:areas.rect"):m("config:areas.circle");return e.jsxs("div",{className:`area-item ${o?"selected":""}`,onClick:a,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:[r," ",f>0&&`• ${f} ${f>1?m("common:labels.agents").toLowerCase():m("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:i,title:m("config:areas.deleteArea"),children:"×"})]})}function Ls({building:s,isSelected:o,onClick:a,onEdit:i}){var n;const{t:m}=ee(["config"]),f=((n=s.pm2Status)==null?void 0:n.ports)||[],r=(h,I)=>{h.stopPropagation(),window.open(`http://${window.location.hostname}:${I}`,"_blank")};return e.jsxs("div",{className:`building-item ${o?"selected":""}`,onClick:a,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:Je[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx(L,{name:Ze(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,f.length>0&&e.jsx("span",{className:"building-ports",children:f.map(h=>e.jsxs("a",{href:`http://${window.location.hostname}:${h}`,className:"building-port-link",onClick:I=>r(I,h),title:`Open :${h}`,children:[":",h]},h))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:h=>{h.stopPropagation(),i()},title:m("config:buildings.editBuilding"),children:e.jsx(L,{name:"gear",size:14})})]})}function Fs({building:s,onClose:o,onOpenModal:a}){var I,b,k,d,g,u,y,x;const{t:i}=ee(["config","common"]),{buildingLogs:m}=Re(),f=A.getBuildingLogs(s.id),r=es[s.style||"server-rack"],n=c=>{A.sendBuildingCommand(s.id,c)},h=c=>{window.open(c,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx(L,{name:Ze(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:Je[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:o,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:i("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:i("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:r.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:i("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:i("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>n("start"),disabled:!((I=s.commands)!=null&&I.start)||s.status==="running",title:((b=s.commands)==null?void 0:b.start)||i("config:buildings.noStartCommand"),children:[e.jsx(L,{name:"play",size:12})," ",i("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>n("stop"),disabled:!((k=s.commands)!=null&&k.stop)||s.status==="stopped",title:((d=s.commands)==null?void 0:d.stop)||i("config:buildings.noStopCommand"),children:[e.jsx(L,{name:"stop",size:12,weight:"fill"})," ",i("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>n("restart"),disabled:!((g=s.commands)!=null&&g.restart),title:((u=s.commands)==null?void 0:u.restart)||i("config:buildings.noRestartCommand"),children:[e.jsx(L,{name:"refresh",size:12})," ",i("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>n("healthCheck"),disabled:!((y=s.commands)!=null&&y.healthCheck),title:((x=s.commands)==null?void 0:x.healthCheck)||i("config:buildings.noHealthCheck"),children:[e.jsx(L,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:i("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((c,F)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>h(c.url),title:c.url,children:[e.jsx(L,{name:"link",size:12})," ",c.label||c.url]},F))})]}),f.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[i("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>A.clearBuildingLogs(s.id),title:i("common:buttons.clear"),children:i("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:f.slice(-5).map((c,F)=>e.jsx("div",{className:"building-editor-log-entry",children:c},F))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:a,children:[e.jsx(L,{name:"gear",size:12})," ",i("config:buildings.fullSettings")]})})]})}async function Os(s,o){const a=H(),i=await fetch(ce(`/api/areas/${s}/logo`),{method:"POST",headers:{"Content-Type":o.type||"image/png","X-Filename":encodeURIComponent(o.name),...a?{Authorization:`Bearer ${a}`}:{}},body:o});if(!i.ok){const m=await i.json().catch(()=>({error:i.statusText}));throw new Error(m.error||`Upload failed: ${i.statusText}`)}return i.json()}async function Ds(s){const o=H(),a=await fetch(ce(`/api/areas/${s}/logo`),{method:"DELETE",headers:{...o?{Authorization:`Bearer ${o}`}:{}}});if(!a.ok)throw new Error(`Failed to delete logo: ${a.statusText}`)}function $s(s){return ss(ce(`/api/areas/logos/${s}`))}const Rs=[{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 zs({area:s,onClose:o,onOpenFolder:a}){var oe;const{t:i}=ee(["config","common"]),[m,f]=l.useState(s.name),[r,n]=l.useState(s.prompt||""),[h,I]=l.useState(!1),[b,k]=l.useState(""),[d,g]=l.useState(!1),u=l.useRef(null);l.useEffect(()=>{f(s.name)},[s.id,s.name]),l.useEffect(()=>{n(s.prompt||"")},[s.id,s.prompt]);const y=j=>{const O=j.target.value;f(O),A.updateArea(s.id,{name:O})},x=j=>{A.updateArea(s.id,{color:j})},c=j=>{const O=j.target.value;n(O),A.updateArea(s.id,{prompt:O})},F=()=>{b.trim()&&(A.addDirectoryToArea(s.id,b.trim()),k(""),I(!1))},z=(j,O)=>{O.stopPropagation(),A.removeDirectoryFromArea(s.id,j)},R=()=>{A.bringAreaToFront(s.id)},w=()=>{A.sendAreaToBack(s.id)},E=l.useCallback(()=>{let j=2,O=2;s.type==="rectangle"&&s.width&&s.height?(j=s.width,O=s.height):s.type==="circle"&&s.radius&&(j=s.radius*1.414,O=s.radius*1.414);const K=Math.min(j,O)*.4;return{width:Math.round(K*10)/10,height:Math.round(K*10)/10}},[s.type,s.width,s.height,s.radius]),V=async j=>{var K;const O=(K=j.target.files)==null?void 0:K[0];if(O){g(!0);try{const v=await Os(s.id,O),D=E();A.updateArea(s.id,{logo:{filename:v.filename,position:"center",width:D.width,height:D.height,keepAspectRatio:!0,opacity:.8}})}catch(v){console.error("Failed to upload logo:",v)}finally{g(!1),u.current&&(u.current.value="")}}},B=async()=>{try{await Ds(s.id),A.updateArea(s.id,{logo:void 0})}catch(j){console.error("Failed to remove logo:",j)}},W=j=>{s.logo&&A.updateArea(s.id,{logo:{...s.logo,position:j}})},N=j=>{if(!s.logo)return;const O=parseFloat(j.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const K=s.logo.height/s.logo.width;A.updateArea(s.id,{logo:{...s.logo,width:O,height:Math.round(O*K*10)/10}})}else A.updateArea(s.id,{logo:{...s.logo,width:O}})},T=j=>{if(!s.logo)return;const O=parseFloat(j.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const K=s.logo.width/s.logo.height;A.updateArea(s.id,{logo:{...s.logo,height:O,width:Math.round(O*K*10)/10}})}else A.updateArea(s.id,{logo:{...s.logo,height:O}})},M=()=>{s.logo&&A.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},se=j=>{s.logo&&A.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(j.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:i("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:o,children:"×"})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:i("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:m,onChange:y,placeholder:i("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:i("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:as.map(j=>e.jsx("div",{className:`color-swatch ${s.color===j?"selected":""}`,style:{backgroundColor:j},onClick:()=>x(j)},j))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:i("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:R,title:i("config:areas.bringToFront"),children:[e.jsx(L,{name:"arrow-up",size:12})," ",i("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:w,title:i("config:areas.sendToBack"),children:[e.jsx(L,{name:"arrow-down",size:12})," ",i("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:i("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(oe=s.logo)!=null&&oe.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:$s(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:B,children:i("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var j;return(j=u.current)==null?void 0:j.click()},disabled:d,children:d?"...":e.jsx(L,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:i("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Rs.map(({key:j,labelKey:O})=>{var K;return e.jsx("button",{className:`area-logo-pos-btn ${((K=s.logo)==null?void 0:K.position)===j?"active":""}`,onClick:()=>W(j),children:i(`config:areas.${O}`)},j)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:i("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:i("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:N,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:i("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:T,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:i("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:M}),i("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:i("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:se,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 j;return(j=u.current)==null?void 0:j.click()},disabled:d,children:d?"...":i("config:areas.uploadLogo")}),e.jsx("input",{ref:u,type:"file",accept:"image/*",style:{display:"none"},onChange:V})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:i("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(j=>e.jsxs("div",{className:"area-folder-item",title:j,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>a==null?void 0:a(s.id),title:i("config:areas.openFolder"),children:e.jsx(L,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:j.split("/").pop()||j}),e.jsx("button",{className:"area-folder-remove",onClick:O=>z(j,O),title:i("config:areas.removeFolder"),children:"×"})]},j)),h?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(ts,{value:b,onChange:k,onSubmit:F,placeholder:i("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:F,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>I(!0),children:i("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:i("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:r,onChange:c,placeholder:i("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:i("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:i("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:i("config:areas.rightClickUnassign")})]})]})}function _s(){const{t:s}=ee(["config","common"]),o=ns(),[a,i]=l.useState(!1),[m,f]=l.useState(null),[r,n]=l.useState({name:"",key:"",value:"",description:""}),[h,I]=l.useState(null),b=()=>{i(!0),f(null),n({name:"",key:"",value:"",description:""})},k=c=>{f(c.id),i(!1),n({name:c.name,key:c.key,value:c.value,description:c.description||""})},d=()=>{i(!1),f(null),n({name:"",key:"",value:"",description:""})},g=()=>{!r.name.trim()||!r.key.trim()||(m?A.updateSecret(m,{name:r.name.trim(),key:r.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:r.value,description:r.description.trim()||void 0}):A.createSecret({name:r.name.trim(),key:r.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:r.value,description:r.description.trim()||void 0}),d())},u=c=>{I(c)},y=()=>{h&&(A.deleteSecret(h),m===h&&d())},x=c=>{navigator.clipboard.writeText(`{{${c}}}`)};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:o.length===0&&!a?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):o.map(c=>e.jsxs("div",{className:`secret-item ${m===c.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:c.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>x(c.key),title:s("config:secrets.copyPlaceholder"),children:`{{${c.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>k(c),title:s("common:buttons.edit"),children:e.jsx(L,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>u(c.id),title:s("common:buttons.delete"),children:"×"})]})]}),c.description&&e.jsx("div",{className:"secret-item-description",children:c.description})]},c.id))}),(a||m)&&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:r.name,onChange:c=>n({...r,name:c.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:r.key,onChange:c=>n({...r,key:c.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${r.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:r.value,onChange:c=>n({...r,value:c.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:r.description,onChange:c=>n({...r,description:c.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:d,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:g,disabled:!r.name.trim()||!r.key.trim(),children:s(m?"config:secrets.update":"common:buttons.add")})]})]}),!a&&!m&&e.jsx("button",{className:"secrets-add-btn",onClick:b,children:s("config:secrets.addSecret")}),e.jsx(re,{isOpen:h!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:y,onClose:()=>I(null)})]})}async function Us(){const s=H(),o=await fetch(`${Y()}/api/agents/system-settings/prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok)throw new Error(`Failed to fetch system prompt: ${o.statusText}`);return(await o.json()).prompt||""}async function Bs(s){const o=H(),a=await fetch(`${Y()}/api/agents/system-settings/prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({prompt:s})});if(!a.ok)throw new Error(`Failed to update system prompt: ${a.statusText}`)}async function Ks(){const s=H(),o=await fetch(`${Y()}/api/agents/system-settings/prompt`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}});if(!o.ok)throw new Error(`Failed to clear system prompt: ${o.statusText}`)}async function Vs(){const s=H(),o=await fetch(`${Y()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok)throw new Error(`Failed to fetch echo prompt setting: ${o.statusText}`);return(await o.json()).enabled||!1}async function Ms(s){const o=H(),a=await fetch(`${Y()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({enabled:s})});if(!a.ok)throw new Error(`Failed to update echo prompt setting: ${a.statusText}`)}async function qs(){const s=H(),o=await fetch(`${Y()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok)throw new Error(`Failed to fetch codex binary path: ${o.statusText}`);return(await o.json()).path||""}async function Ws(s){const o=H(),a=await fetch(`${Y()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({path:s})});if(!a.ok)throw new Error(`Failed to update codex binary path: ${a.statusText}`)}async function Hs(){const s=H(),o=await fetch(`${Y()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok)throw new Error(`Failed to fetch tmux mode setting: ${o.statusText}`);return(await o.json()).enabled||!1}async function Gs(s){const o=H(),a=await fetch(`${Y()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({enabled:s})});if(!a.ok)throw new Error(`Failed to update tmux mode setting: ${a.statusText}`)}async function Ys(){const s=H(),o=await fetch(`${Y()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok)throw new Error(`Failed to fetch backup status: ${o.statusText}`);return o.json()}async function Js(s){const o=H(),a=await fetch(`${Y()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({enabled:s})});if(!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.error||`Failed to update backup setting: ${a.statusText}`)}return a.json()}function Zs({checked:s,onChange:o,disabled:a}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:a,onChange:i=>o(i.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function Xs(){const{t:s}=ee(["config","common"]),[o,a]=l.useState([]),[i,m]=l.useState(new Set),[f,r]=l.useState(new Set),[n,h]=l.useState(!1),[I,b]=l.useState(!1),[k,d]=l.useState(null),[g,u]=l.useState(null),[y,x]=l.useState(null),[c,F]=l.useState(null),[z,R]=l.useState(!1),[w,E]=l.useState(null);l.useEffect(()=>{je(ce("/api/config/categories")).then(v=>v.json()).then(v=>{const D=Array.isArray(v)?v:[];a(D),m(new Set(D.map($=>$.id)))}).catch(v=>console.error("Failed to fetch config categories:",v))},[]),l.useEffect(()=>{Ys().then(F).catch(v=>{console.error("Failed to fetch backup status:",v),E(v.message||"Failed to fetch backup status")})},[]);const V=async v=>{if(!z){R(!0),E(null);try{const D=await Js(v);F(D)}catch(D){E(D.message||"Failed to update backup setting")}finally{R(!1)}}},B=v=>{m(D=>{const $=new Set(D);return $.has(v)?$.delete(v):$.add(v),$})},W=v=>{r(D=>{const $=new Set(D);return $.has(v)?$.delete(v):$.add(v),$})},N=()=>m(new Set(o.map(v=>v.id))),T=()=>m(new Set),M=()=>{g&&r(new Set(g.categories.map(v=>v.id)))},se=()=>r(new Set),oe=async()=>{var v;if(i.size!==0){h(!0),x(null);try{const D=Array.from(i).join(","),$=await je(ce(`/api/config/export?categories=${D}`));if(!$.ok)throw new Error("Export failed");const J=await $.blob(),ae=window.URL.createObjectURL(J),X=document.createElement("a");X.href=ae;const G=$.headers.get("Content-Disposition"),ge=((v=G==null?void 0:G.match(/filename="(.+)"/))==null?void 0:v[1])||"tide-commander-config.zip";X.download=ge,document.body.appendChild(X),X.click(),document.body.removeChild(X),window.URL.revokeObjectURL(ae),x({type:"success",text:s("config:data.exportSuccess")})}catch(D){x({type:"error",text:D.message||"Export failed"})}finally{h(!1)}}},j=async v=>{var $;const D=($=v.target.files)==null?void 0:$[0];if(D){d(D),x(null),u(null),r(new Set);try{const J=await je(ce("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await D.arrayBuffer()});if(!J.ok){const G=await J.json();throw new Error(G.error||"Failed to preview config file")}const ae=await J.json(),X=Array.isArray(ae.categories)?ae.categories:[];u({...ae,categories:X}),r(new Set(X.map(G=>G.id)))}catch(J){x({type:"error",text:J.message||"Failed to read config file"}),d(null)}}},O=async()=>{if(!(!k||f.size===0)){b(!0),x(null);try{const v=Array.from(f).join(","),D=await je(ce(`/api/config/import?categories=${v}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await k.arrayBuffer()}),$=await D.json();if(!D.ok)throw new Error($.error||"Import failed");x({type:"success",text:$.message||s("config:data.importSuccess")}),d(null),u(null),r(new Set)}catch(v){x({type:"error",text:v.message||"Import failed"})}finally{b(!1)}}},K=()=>{d(null),u(null),r(new Set),x(null)};return e.jsxs("div",{className:"data-section",children:[y&&e.jsx("div",{className:`data-message data-message-${y.type}`,children:y.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(Zs,{checked:!!(c!=null&&c.enabled),disabled:z||!c,onChange:V})]}),e.jsxs("div",{className:"data-backup-info",children:[c?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:c.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!c.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:c.scriptPath})]}),c.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(c.lastRunAt).toLocaleString(),c.lastRunOk===!0&&" — ok",c.lastRunOk===!1&&c.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",c.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),w&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:w})]})]}),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:N,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:T,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:o.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:i.has(v.id),onChange:()=>B(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name})]},v.id))}),e.jsx("button",{className:"data-action-btn export",onClick:oe,disabled:n||i.size===0,children:n?s("config:data.exporting"):s("config:data.exportCount",{count:i.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")})}),k?g?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:k.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(g.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:M,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:se,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:g.categories.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:f.has(v.id),onChange:()=>W(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name}),v.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",v.fileCount," ",s("config:data.files"),")"]})]},v.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:K,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:O,disabled:I||f.size===0,children:I?s("config:data.importing"):s("config:data.importCount",{count:f.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:j,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}function Qs(){const[s,o]=l.useState(()=>is()),a=i=>{o(i);const m=ls(i);cs(m)};return e.jsx("div",{className:"theme-selector",children:e.jsx("div",{className:"theme-selector-grid",children:os.map(i=>e.jsxs("button",{className:`theme-option ${s===i.id?"active":""}`,onClick:()=>a(i.id),title:i.description,children:[e.jsx("div",{className:"theme-preview",children:e.jsxs("div",{className:"theme-preview-bg",style:{backgroundColor:i.colors.bgPrimary},children:[e.jsx("div",{className:"theme-preview-accent",style:{backgroundColor:i.colors.accentBlue}}),e.jsx("div",{className:"theme-preview-claude",style:{backgroundColor:i.colors.accentClaude}})]})}),e.jsx("span",{className:"theme-name",children:i.name})]},i.id))})})}function ea(){const{t:s}=ee(["config"]),{updateAvailable:o,updateInfo:a,recentReleases:i,isChecking:m,error:f,currentVersion:r,isAndroid:n,checkForUpdate:h,downloadAndInstall:I,openReleasePage:b}=Ts(),k=g=>g?`${(g/(1024*1024)).toFixed(1)} MB`:"",d=g=>new Date(g).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(L,{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:r}),o&&a?e.jsx("span",{className:"about-version-update-badge",onClick:b,title:`Update available: ${a.version}`,children:a.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.jsxs("div",{className:"about-update",children:[o&&a?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:a.version})]}),a.apkSize&&e.jsxs("div",{className:"about-update-size",children:[s("config:about.sizeLabel"),": ",k(a.apkSize)]}),f&&e.jsx("div",{className:"about-update-error",children:f}),e.jsxs("div",{className:"about-update-actions",children:[e.jsx("button",{className:"about-update-btn changelog",onClick:b,children:s("config:about.changelog")}),n&&a.apkUrl?e.jsx("button",{className:"about-update-btn download",onClick:I,children:s("config:about.downloadAPK")}):e.jsx("button",{className:"about-update-btn download",onClick:b,children:s("config:about.viewRelease")})]})]}):e.jsxs("div",{className:"about-update-check",children:[e.jsx("span",{className:"about-update-status",children:s(m?"config:about.checkingUpdates":"config:about.upToDate")}),e.jsx("button",{className:"about-update-btn check",onClick:()=>h(!0),disabled:m,children:m?"...":s("config:about.check")})]}),i.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:i.map(g=>e.jsxs("a",{href:g.releaseUrl,target:"_blank",rel:"noopener noreferrer",className:`about-release-item ${g.version===`v${r}`||g.version===r?"current":""}`,children:[e.jsx("span",{className:"about-release-version",children:g.version}),e.jsx("span",{className:"about-release-date",children:d(g.publishedAt)})]},g.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(L,{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")})]})]})]})}const sa={gmail:"✉️",slack:"💬",jira:"📋","google-calendar":"📅",docx:"📄"};function aa({onOpenModal:s}){const[o,a]=l.useState([]),[i,m]=l.useState(!0),f=l.useCallback(async()=>{try{const r=await je(ce("/api/integrations"));if(!r.ok)return;const n=await r.json();a(n)}catch{}finally{m(!1)}},[]);return l.useEffect(()=>{f()},[f]),i?e.jsx("div",{style:{color:"var(--text-secondary, #a6adc8)",fontSize:12,padding:"4px 0"},children:"Loading..."}):o.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:4},children:[o.map(r=>{const n=sa[r.id]||"🔌",h=!!r.status.error,I=r.status.connected,b=h?"#f38ba8":I?"#a6e3a1":"#fab387",k=h?"Error":I?"Connected":"Setup Required",d=h?"✗":I?"✓":"⚠";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:6,background:"var(--surface-1, #181825)",border:"1px solid var(--border, #313244)",fontSize:13},children:[e.jsx("span",{style:{fontSize:15,flexShrink:0},children:n}),e.jsx("span",{style:{flex:1,color:"var(--text-primary, #cdd6f4)",fontWeight:500},children:r.name}),e.jsxs("span",{style:{color:b,fontSize:11,fontWeight:500,whiteSpace:"nowrap"},children:[d," ",k]}),e.jsx("button",{onClick:()=>s(r.id),title:`Configure ${r.name}`,style:{background:"none",border:"none",cursor:"pointer",padding:"2px 4px",fontSize:14,color:"var(--text-secondary, #a6adc8)",borderRadius:4,flexShrink:0},onMouseEnter:g=>{g.target.style.color="var(--text-primary, #cdd6f4)"},onMouseLeave:g=>{g.target.style.color="var(--text-secondary, #a6adc8)"},children:"⚙️"})]},r.id)}),e.jsx("button",{onClick:()=>s(),style:{background:"none",border:"1px dashed var(--border, #313244)",borderRadius:6,padding:"6px 8px",cursor:"pointer",color:"var(--text-secondary, #a6adc8)",fontSize:12,textAlign:"center",marginTop:2},onMouseEnter:r=>{r.target.style.borderColor="var(--accent, #89b4fa)",r.target.style.color="var(--accent, #89b4fa)"},onMouseLeave:r=>{r.target.style.borderColor="var(--border, #313244)",r.target.style.color="var(--text-secondary, #a6adc8)"},children:"Manage All Integrations"})]})}function ta({isOpen:s,onClose:o}){const{t:a}=ee(["config"]),[i,m]=l.useState(""),[f,r]=l.useState(""),[n,h]=l.useState(!0),[I,b]=l.useState(null),[k,d]=l.useState(null),[g,u]=l.useState(!1),[y,x]=l.useState(!1),[c,F]=l.useState(!1);l.useEffect(()=>{s&&z()},[s]);const z=async()=>{try{h(!0),b(null),d(null);const T=await Us();m(T),r(T),u(!1)}catch(T){b(T instanceof Error?T.message:"Failed to load system prompt")}finally{h(!1)}},R=T=>{const M=T.target.value;m(M),u(M!==f),b(null),d(null)},w=async()=>{try{b(null),d(null),await Bs(i),r(i),u(!1),d(a("config:systemPrompt.saved"))}catch(T){b(T instanceof Error?T.message:"Failed to save system prompt")}},E=()=>{x(!0)},V=async()=>{try{b(null),d(null),await Ks(),m(""),r(""),u(!1),d(a("config:systemPrompt.cleared"))}catch(T){b(T instanceof Error?T.message:"Failed to clear system prompt")}},B=()=>{m(f),u(!1),b(null),d(null)},W=()=>{if(g){F(!0);return}o()},N=T=>{T.key==="Escape"&&(T.preventDefault(),W())};return s?e.jsxs(ze,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:W,children:e.jsxs("div",{className:"system-prompt-modal",onClick:T=>T.stopPropagation(),onKeyDown:N,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:a("config:systemPrompt.title")}),e.jsx("button",{className:"modal-close",onClick:W,"aria-label":"Close",children:e.jsx(L,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:n?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:"Loading system prompt..."})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:a("config:systemPrompt.description")}),I&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(L,{name:"warn",size:14})}),I]}),k&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(L,{name:"check",size:14})}),k]}),e.jsxs("div",{className:"editor-wrapper",children:[e.jsxs("div",{className:"editor-header",children:[e.jsx("label",{htmlFor:"prompt-input",className:"editor-label",children:a("config:systemPrompt.editPrompt")}),e.jsxs("span",{className:"char-count",children:[i.length," ",a("config:systemPrompt.characters")]})]}),e.jsx("textarea",{id:"prompt-input",className:"prompt-editor",value:i,onChange:R,placeholder:a("config:systemPrompt.placeholder"),rows:18,autoFocus:!0}),e.jsx("div",{className:"editor-hint",children:a("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:E,disabled:!i||n,children:a("config:systemPrompt.clear")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:W,children:"Close"}),e.jsx("button",{className:"btn btn-secondary",onClick:B,disabled:!g||n,children:a("config:systemPrompt.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:w,disabled:!g||n,children:a("config:systemPrompt.save")})]})]})]})}),e.jsx(re,{isOpen:y,title:a("config:systemPrompt.clear"),message:a("config:systemPrompt.confirmClear"),confirmLabel:a("config:systemPrompt.clear"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V()},onClose:()=>x(!1)}),e.jsx(re,{isOpen:c,title:"Unsaved Changes",message:"You have unsaved changes. Close anyway?",confirmLabel:"Close anyway",cancelLabel:"Keep editing",variant:"danger",onConfirm:o,onClose:()=>F(!1)})]}):null}const He={enabled:!1,baseUrl:"",defaultSessionId:"",webhookVerifyToken:"",showIncomingToasts:!0},na=2500,ia=12e4;function Ge(s){return{enabled:s.enabled??!1,baseUrl:s.baseUrl??"",defaultSessionId:s.defaultSessionId??"",webhookVerifyToken:s.webhookVerifyToken??"",showIncomingToasts:s.showIncomingToasts??!0}}function oa(s,o){return s.enabled===o.enabled&&s.baseUrl===o.baseUrl&&s.defaultSessionId===o.defaultSessionId&&s.webhookVerifyToken===o.webhookVerifyToken&&s.showIncomingToasts===o.showIncomingToasts}function la({isOpen:s,onClose:o}){const{t:a}=ee(["config"]),[i,m]=l.useState(He),[f,r]=l.useState(He),[n,h]=l.useState(!1),[I,b]=l.useState([]),[k,d]=l.useState(!0),[g,u]=l.useState(null),[y,x]=l.useState(null),[c,F]=l.useState(""),[z,R]=l.useState(!1),[w,E]=l.useState(""),[V,B]=l.useState(null),[W,N]=l.useState(null),[T,M]=l.useState(null),se=l.useRef(null),oe=l.useRef(0),[j,O]=l.useState(""),[K,v]=l.useState(""),[D,$]=l.useState(null),[J,ae]=l.useState(!1),[X,G]=l.useState(!1),[ge,ve]=l.useState(!1),[Ae,de]=l.useState(!1),[S,Z]=l.useState(null),fe=!oa(i,f),te=l.useCallback(()=>{se.current&&(clearTimeout(se.current),se.current=null)},[]),Ne=l.useCallback(async()=>{try{d(!0),u(null),x(null);const[p,t]=await Promise.all([rs(),ds()]),P=Ge(p);if(m(P),r(P),h(!!t.configured),t.configured)try{const q=await Me();b(Array.isArray(q)?q:[])}catch{b([])}else b([])}catch(p){u(p instanceof Error?p.message:a("config:whatsapp.errors.loadFailed"))}finally{d(!1)}},[a]),me=l.useCallback(async()=>{try{const p=await Me();b(Array.isArray(p)?p:[])}catch{}},[]);l.useEffect(()=>(s?Ne():(te(),B(null),N(null),M(null),F(""),R(!1),$(null)),()=>{te()}),[s,Ne,te]);const le=(p,t)=>{m(P=>({...P,[p]:t})),u(null),x(null)},Te=async()=>{try{u(null),x(null);const p=await gs({enabled:i.enabled,baseUrl:i.baseUrl.trim(),defaultSessionId:i.defaultSessionId.trim(),webhookVerifyToken:i.webhookVerifyToken,showIncomingToasts:i.showIncomingToasts});window.dispatchEvent(new CustomEvent("tide:whatsapp-config-updated"));const t=Ge(p);m(t),r(t),x(a("config:whatsapp.saved"))}catch(p){u(p instanceof Error?p.message:a("config:whatsapp.errors.saveFailed"))}},we=()=>{m(f),u(null),x(null)},ue=()=>{if(fe){G(!0);return}o()},Ee=p=>{p.key==="Escape"&&(p.preventDefault(),ue())},ye=async()=>{const p=c.trim();if(p)try{u(null),x(null),await ps(p),F(""),R(!1),h(!0),x(a("config:whatsapp.apiKeySaved"))}catch(t){u(t instanceof Error?t.message:a("config:whatsapp.errors.apiKeySaveFailed"))}},Ie=()=>{ve(!0)},ke=async()=>{try{u(null),x(null),await fs(),h(!1),x(a("config:whatsapp.apiKeyCleared"))}catch(p){u(p instanceof Error?p.message:a("config:whatsapp.errors.apiKeyClearFailed"))}},ne=l.useCallback(async p=>{if(Date.now()>oe.current){M(a("config:whatsapp.pairingTimeout")),B(null),N(null),te(),me();return}try{const t=await ms(p);if(t.status&&["connected","paired","open","ready"].includes(t.status.toLowerCase())){M(a("config:whatsapp.pairingSuccess")),B(null),N(null),te(),me();return}const q=t.qrUrl??t.qr??null;q&&N(q)}catch(t){M(t instanceof Error?t.message:a("config:whatsapp.errors.qrFetchFailed"))}se.current=setTimeout(()=>{ne(p)},na)},[me,te,a]),ie=async()=>{const p=w.trim();if(p)try{u(null),x(null),M(null),N(null),te(),await us(p),E(""),B(p),oe.current=Date.now()+ia,ne(p),me()}catch(t){u(t instanceof Error?t.message:a("config:whatsapp.errors.sessionCreateFailed"))}},xe=()=>{te(),B(null),N(null),M(null)},Pe=p=>{Z(p),de(!0)},Le=async()=>{if(S)try{u(null),x(null),await xs(S),V===S&&xe(),me(),x(a("config:whatsapp.sessionDeleted"))}catch(p){u(p instanceof Error?p.message:a("config:whatsapp.errors.sessionDeleteFailed"))}finally{Z(null)}},_=async()=>{const p=j.trim(),t=K.trim();if(!(!p||!t))try{ae(!0),$(null);const P=i.defaultSessionId.trim()||void 0;await hs(p,t,P),$({kind:"success",text:a("config:whatsapp.testSent")})}catch(P){$({kind:"error",text:P instanceof Error?P.message:a("config:whatsapp.errors.testSendFailed")})}finally{ae(!1)}};return s?e.jsxs(ze,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:ue,children:e.jsxs("div",{className:"whatsapp-config-modal",onClick:p=>p.stopPropagation(),onKeyDown:Ee,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:a("config:whatsapp.title")}),e.jsx("button",{className:"modal-close",onClick:ue,"aria-label":"Close",children:e.jsx(L,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:k?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:a("config:whatsapp.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:a("config:whatsapp.description")}),g&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(L,{name:"warn",size:14})}),g]}),y&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(L,{name:"check",size:14})}),y]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.general")}),e.jsxs("div",{className:"wa-field wa-field-row",children:[e.jsx("label",{htmlFor:"wa-enabled",className:"wa-label",children:a("config:whatsapp.enabled")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-enabled",type:"checkbox",checked:i.enabled,onChange:p=>le("enabled",p.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:a("config:whatsapp.showIncomingToasts")}),e.jsxs("label",{className:"wa-toggle",children:[e.jsx("input",{id:"wa-show-toasts",type:"checkbox",checked:i.showIncomingToasts,onChange:p=>le("showIncomingToasts",p.target.checked)}),e.jsx("span",{className:"wa-toggle-track",children:e.jsx("span",{className:"wa-toggle-thumb"})})]})]}),e.jsx("span",{className:"wa-hint",children:a("config:whatsapp.showIncomingToastsHelp")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-base-url",className:"wa-label",children:a("config:whatsapp.baseUrl")}),e.jsx("input",{id:"wa-base-url",type:"text",className:"wa-input",placeholder:"http://localhost:3007",value:i.baseUrl,onChange:p=>le("baseUrl",p.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-default-session",className:"wa-label",children:a("config:whatsapp.defaultSessionId")}),e.jsx("input",{id:"wa-default-session",type:"text",className:"wa-input",placeholder:a("config:whatsapp.defaultSessionIdPlaceholder"),value:i.defaultSessionId,onChange:p=>le("defaultSessionId",p.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-webhook-token",className:"wa-label",children:a("config:whatsapp.webhookVerifyToken")}),e.jsx("input",{id:"wa-webhook-token",type:"text",className:"wa-input",placeholder:a("config:whatsapp.webhookVerifyTokenPlaceholder"),value:i.webhookVerifyToken,onChange:p=>le("webhookVerifyToken",p.target.value)})]})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.apiKey")}),e.jsx("div",{className:"wa-key-status",children:n?e.jsxs("span",{className:"wa-status wa-status-ok",children:[e.jsx(L,{name:"check",size:12})," ",a("config:whatsapp.configured")]}):e.jsxs("span",{className:"wa-status wa-status-warn",children:[e.jsx(L,{name:"warn",size:12})," ",a("config:whatsapp.notConfigured")]})}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:z?"text":"password",className:"wa-input",placeholder:a("config:whatsapp.apiKeyPlaceholder"),value:c,onChange:p=>F(p.target.value)}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>R(p=>!p),title:a(z?"config:whatsapp.hideKey":"config:whatsapp.showKey"),children:e.jsx(L,{name:z?"eye-closed":"eye",size:14})}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:ye,disabled:!c.trim(),children:a("config:whatsapp.saveKey")}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:Ie,disabled:!n,children:a("config:whatsapp.clearKey")})]}),e.jsx("span",{className:"wa-hint",children:a("config:whatsapp.apiKeyHint")})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.sessions")}),e.jsx("div",{className:"wa-sessions-list",children:!Array.isArray(I)||I.length===0?e.jsx("div",{className:"wa-empty",children:a("config:whatsapp.noSessions")}):I.map(p=>e.jsxs("div",{className:"wa-session-row",children:[e.jsxs("div",{className:"wa-session-info",children:[e.jsx("span",{className:"wa-session-id",children:p.id}),e.jsx("span",{className:`wa-session-status status-${(p.status??"unknown").toLowerCase()}`,children:p.status||"—"}),p.pairedNumber&&e.jsx("span",{className:"wa-session-paired",children:p.pairedNumber})]}),e.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:()=>Pe(p.id),children:a("config:whatsapp.deleteSession")})]},p.id))}),e.jsxs("div",{className:"wa-field wa-field-inline",children:[e.jsx("input",{type:"text",className:"wa-input",placeholder:a("config:whatsapp.addSessionPlaceholder"),value:w,onChange:p=>E(p.target.value),onKeyDown:p=>{p.key==="Enter"&&ie()}}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:ie,disabled:!w.trim()||V!==null,children:a("config:whatsapp.addSession")})]}),V&&e.jsxs("div",{className:"wa-qr-panel",children:[e.jsxs("div",{className:"wa-qr-header",children:[e.jsx("span",{children:a("config:whatsapp.qrPrompt",{id:V})}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:xe,children:a("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:a("config:whatsapp.waitingForQr")})]})]}),T&&!V&&e.jsx("div",{className:"wa-pairing-message",children:T})]}),e.jsxs("section",{className:"wa-section",children:[e.jsx("h3",{className:"wa-section-title",children:a("config:whatsapp.sections.testMessage")}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-to",className:"wa-label",children:a("config:whatsapp.testTo")}),e.jsx("input",{id:"wa-test-to",type:"text",className:"wa-input",placeholder:a("config:whatsapp.testToPlaceholder"),value:j,onChange:p=>O(p.target.value)})]}),e.jsxs("div",{className:"wa-field",children:[e.jsx("label",{htmlFor:"wa-test-message",className:"wa-label",children:a("config:whatsapp.testMessageBody")}),e.jsx("textarea",{id:"wa-test-message",className:"wa-textarea",rows:4,placeholder:a("config:whatsapp.testMessageBodyPlaceholder"),value:K,onChange:p=>v(p.target.value)})]}),e.jsx("div",{className:"wa-field-inline wa-field-end",children:e.jsx("button",{type:"button",className:"btn btn-primary",onClick:_,disabled:!j.trim()||!K.trim()||J,children:a(J?"config:whatsapp.sending":"config:whatsapp.sendTest")})}),D&&e.jsxs("div",{className:`alert ${D.kind==="success"?"alert-success":"alert-error"}`,children:[e.jsx("span",{className:"alert-icon",children:e.jsx(L,{name:D.kind==="success"?"check":"warn",size:14})}),D.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:ue,children:a("config:whatsapp.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:we,disabled:!fe||k,children:a("config:whatsapp.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:Te,disabled:!fe||k,children:a("config:whatsapp.save")})]})]})]})}),e.jsx(re,{isOpen:X,title:a("config:whatsapp.unsavedTitle"),message:a("config:whatsapp.unsavedMessage"),confirmLabel:a("config:whatsapp.closeAnyway"),cancelLabel:a("config:whatsapp.keepEditing"),variant:"danger",onConfirm:()=>{G(!1),o()},onClose:()=>G(!1)}),e.jsx(re,{isOpen:ge,title:a("config:whatsapp.clearKey"),message:a("config:whatsapp.confirmClearKey"),confirmLabel:a("config:whatsapp.clearKey"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{ke()},onClose:()=>ve(!1)}),e.jsx(re,{isOpen:Ae,title:a("config:whatsapp.deleteSession"),message:a("config:whatsapp.confirmDeleteSession",{id:S??""}),confirmLabel:a("config:whatsapp.deleteSession"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{Le()},onClose:()=>{de(!1),Z(null)}})]}):null}const Qe=["messages","statusChanges","taskComplete","errors","planReady","agentSpawned","agentStopped"];function Ue(s=!1){const o=H(),a={};return o&&(a.Authorization=`Bearer ${o}`),s&&(a["Content-Type"]="application/json"),a}async function Be(s,o){try{const a=await s.json();if(a&&typeof a.error=="string")return a.error;if(a&&typeof a.message=="string")return a.message}catch{}return`${o}: ${s.statusText}`}async function ca(){const s=await fetch(`${Y()}/api/whatsapp/notification-config`,{headers:Ue()});if(!s.ok)throw new Error(await Be(s,"Failed to fetch WhatsApp notification config"));return s.json()}async function ra(s){const o=await fetch(`${Y()}/api/whatsapp/notification-config`,{method:"PATCH",headers:Ue(!0),body:JSON.stringify(s)});if(!o.ok)throw new Error(await Be(o,"Failed to update WhatsApp notification config"));return o.json()}async function da(){const s=await fetch(`${Y()}/api/whatsapp/notification-config`,{method:"DELETE",headers:Ue()});if(!s.ok)throw new Error(await Be(s,"Failed to reset WhatsApp notification config"));return s.json()}const Ce={messages:!0,statusChanges:!0,taskComplete:!0,errors:!0,planReady:!0,agentSpawned:!0,agentStopped:!0},Ye={filter:{...Ce},recipient:""};function ma(s,o){if(s.recipient!==o.recipient)return!1;for(const a of Qe)if(s.filter[a]!==o.filter[a])return!1;return!0}function pa({isOpen:s,onClose:o}){const{t:a}=ee(["config"]),[i,m]=l.useState(Ye),[f,r]=l.useState(Ye),[n,h]=l.useState(!0),[I,b]=l.useState(null),[k,d]=l.useState(null),[g,u]=l.useState(!1),[y,x]=l.useState(!1),c=!ma(i,f),F=l.useCallback(async()=>{try{h(!0),b(null),d(null);const N=await ca(),T={filter:{...Ce,...N.filter},recipient:N.recipient??""};m(T),r(T)}catch(N){b(N instanceof Error?N.message:a("config:whatsappNotifications.errors.loadFailed"))}finally{h(!1)}},[a]);l.useEffect(()=>{s&&F()},[s,F]);const z=(N,T)=>{m(M=>({...M,filter:{...M.filter,[N]:T}})),b(null),d(null)},R=N=>{m(T=>({...T,recipient:N})),b(null),d(null)},w=async()=>{try{b(null),d(null);const N=await ra({filter:i.filter,recipient:i.recipient.trim()}),T={filter:{...Ce,...N.filter},recipient:N.recipient??""};m(T),r(T),d(a("config:whatsappNotifications.saved"))}catch(N){b(N instanceof Error?N.message:a("config:whatsappNotifications.errors.saveFailed"))}},E=()=>{m(f),b(null),d(null)},V=async()=>{try{b(null),d(null);const N=await da(),T={filter:{...Ce,...N.filter},recipient:N.recipient??""};m(T),r(T),d(a("config:whatsappNotifications.resetDone"))}catch(N){b(N instanceof Error?N.message:a("config:whatsappNotifications.errors.resetFailed"))}},B=()=>{if(c){u(!0);return}o()},W=N=>{N.key==="Escape"&&(N.preventDefault(),B())};return s?e.jsxs(ze,{children:[e.jsx("div",{className:`modal-overlay ${s?"visible":""}`,onClick:B,children:e.jsxs("div",{className:"whatsapp-notifications-modal",onClick:N=>N.stopPropagation(),onKeyDown:W,children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:a("config:whatsappNotifications.title")}),e.jsx("button",{className:"modal-close",onClick:B,"aria-label":"Close",children:e.jsx(L,{name:"close",size:16})})]}),e.jsx("div",{className:"modal-body",children:n?e.jsxs("div",{className:"loading-state",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:a("config:whatsappNotifications.loading")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"modal-description",children:a("config:whatsappNotifications.description")}),I&&e.jsxs("div",{className:"alert alert-error",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(L,{name:"warn",size:14})}),I]}),k&&e.jsxs("div",{className:"alert alert-success",children:[e.jsx("span",{className:"alert-icon",children:e.jsx(L,{name:"check",size:14})}),k]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:a("config:whatsappNotifications.sections.recipient")}),e.jsxs("div",{className:"wan-field",children:[e.jsx("label",{htmlFor:"wan-recipient",className:"wan-label",children:a("config:whatsappNotifications.recipientLabel")}),e.jsx("input",{id:"wan-recipient",type:"text",className:"wan-input",placeholder:a("config:whatsappNotifications.recipientPlaceholder"),value:i.recipient,onChange:N=>R(N.target.value)}),e.jsx("span",{className:"wan-hint",children:a("config:whatsappNotifications.recipientHint")})]})]}),e.jsxs("section",{className:"wan-section",children:[e.jsx("h3",{className:"wan-section-title",children:a("config:whatsappNotifications.sections.events")}),e.jsx("p",{className:"wan-section-hint",children:a("config:whatsappNotifications.eventsHint")}),Qe.map(N=>e.jsxs("div",{className:"wan-toggle-row",children:[e.jsxs("div",{className:"wan-toggle-info",children:[e.jsx("span",{className:"wan-toggle-title",children:a(`config:whatsappNotifications.events.${N}.title`)}),e.jsx("span",{className:"wan-toggle-help",children:a(`config:whatsappNotifications.events.${N}.help`)})]}),e.jsxs("label",{className:"wan-toggle",children:[e.jsx("input",{type:"checkbox",checked:i.filter[N],onChange:T=>z(N,T.target.checked)}),e.jsx("span",{className:"wan-toggle-track",children:e.jsx("span",{className:"wan-toggle-thumb"})})]})]},N))]})]})}),e.jsxs("div",{className:"modal-footer",children:[e.jsx("div",{className:"footer-buttons-left",children:e.jsx("button",{className:"btn btn-danger",onClick:()=>x(!0),disabled:n,children:a("config:whatsappNotifications.resetToDefaults")})}),e.jsxs("div",{className:"footer-buttons-right",children:[e.jsx("button",{className:"btn btn-secondary",onClick:B,children:a("config:whatsappNotifications.close")}),e.jsx("button",{className:"btn btn-secondary",onClick:E,disabled:!c||n,children:a("config:whatsappNotifications.reset")}),e.jsx("button",{className:"btn btn-primary",onClick:w,disabled:!c||n,children:a("config:whatsappNotifications.save")})]})]})]})}),e.jsx(re,{isOpen:g,title:a("config:whatsappNotifications.unsavedTitle"),message:a("config:whatsappNotifications.unsavedMessage"),confirmLabel:a("config:whatsappNotifications.closeAnyway"),cancelLabel:a("config:whatsappNotifications.keepEditing"),variant:"danger",onConfirm:()=>{u(!1),o()},onClose:()=>u(!1)}),e.jsx(re,{isOpen:y,title:a("config:whatsappNotifications.resetToDefaults"),message:a("config:whatsappNotifications.confirmReset"),confirmLabel:a("config:whatsappNotifications.resetToDefaults"),cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{V(),x(!1)},onClose:()=>x(!1)})]}):null}const ua=[{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:"🌙"}],ha=[{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:"🔴"}],ga=[{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:"👎"}],fa=[{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:"💜"}],xa=[{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"}],ba=[{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"}],ja={showTrees:"trees",showBushes:"bushes",showHouse:"house",showLamps:"lamps",showGrass:"grass",showClouds:"clouds"},va={none:"grass","pokemon-stadium":"pokemon"},Na={"emote-yes":"yes","emote-no":"no"},wa={"":"auto","#4a90d9":"dayBlue","#0a1a2a":"night","#ff6b35":"sunset","#1a0a2e":"purple","#2d5a27":"matrix","#8b0000":"blood","#000000":"void"};function Q({checked:s,onChange:o}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,onChange:a=>o(a.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function he({options:s,value:o,onChange:a,iconOnly:i=!1}){return e.jsx("div",{className:"chip-selector",children:s.map(m=>e.jsxs("button",{className:`chip ${o===m.value?"active":""}`,onClick:()=>a(m.value),title:m.label,children:[e.jsx("span",{className:"chip-icon",children:m.icon}),!i&&e.jsx("span",{className:"chip-label",children:m.label})]},m.value))})}function C({text:s,query:o}){if(!o.trim())return e.jsx(e.Fragment,{children:s});const a=s.toLowerCase(),i=o.toLowerCase(),m=a.indexOf(i);if(m===-1)return e.jsx(e.Fragment,{children:s});const f=s.slice(0,m),r=s.slice(m,m+o.length),n=s.slice(m+o.length);return e.jsxs(e.Fragment,{children:[f,e.jsx("mark",{className:"search-highlight",children:r}),n]})}const ya=[{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"]},{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:"whatsapp",title:"WhatsApp Integration",keywords:["whatsapp","message","sms","integration","notification","baileys"]},{id:"whatsappNotifications",title:"WhatsApp Notifications",keywords:["whatsapp","notification","notifications","messages","status","toggle","filter","event","subscribe","plan","error","spawned","stopped"]},{id:"data",title:"Data",keywords:["export","import","backup","restore","save","load","json"]},{id:"integrations",title:"Integrations",keywords:["integrations","plugins","gmail","slack","jira","calendar","docx","email","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:"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"]}],$e=[{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 ka({config:s,onChange:o,searchQuery:a="",onOpenIntegrationsModal:i,onOpenMonitoringModal:m,onOpenWorkflowEditor:f,onOpenTriggerManager:r}){var p;const{t:n}=ee(["config","common"]),h=Re(),I=bs(),[b,k]=l.useState(()=>js(be.DEFAULT_AGENT_CLASS)||"scout"),[d,g]=l.useState(h.settings.historyLimit),[u,y]=l.useState(()=>vs()),[x,c]=l.useState(!1),[F,z]=l.useState(""),[R,w]=l.useState(()=>H()),[E,V]=l.useState(!1),[B,W]=l.useState(!1),[N,T]=l.useState(""),[M,se]=l.useState(!1),[oe,j]=l.useState(!1),[O,K]=l.useState(!1),[v,D]=l.useState(""),[$,J]=l.useState(!1);l.useEffect(()=>{qs().then(D).catch(()=>{})},[]),l.useEffect(()=>{Vs().then(t=>{t!==h.settings.experimentalEchoPrompt&&A.updateSettings({experimentalEchoPrompt:t})}).catch(()=>{})},[]),l.useEffect(()=>{Hs().then(t=>{t!==h.settings.tmuxMode&&A.updateSettings({tmuxMode:t})}).catch(()=>{})},[]),l.useEffect(()=>Ns(t=>{y(t),c(!1)}),[]);const ae=ua.map(t=>({...t,label:n(`config:time.${t.value}`)})),X=ha.map(t=>({...t,label:n(`config:floor.${va[t.value]||t.value}`)})),G=ga.map(t=>({...t,label:n(`config:animation.${Na[t.value]||t.value}`)})),ge=fa.map(t=>({...t,label:n(`config:colorMode.${t.value}`)})),ve=xa.map(t=>({...t,label:n(`config:terrain.${ja[t.key]}`)})),Ae=ba.map(t=>({...t,label:n(`config:sky.${wa[t.value??""]}`)})),de=a.trim()?ya.filter(t=>{const P=a.toLowerCase();return t.title.toLowerCase().includes(P)||t.keywords.some(q=>q.toLowerCase().includes(P))}).map(t=>t.id):null,S=t=>de?de.includes(t):!0,Z=h.settings.customAgentNames||[],fe=Z.length>0?Z:ws,te=()=>{const t=N.trim();t&&!Z.includes(t)&&(A.updateSettings({customAgentNames:[...Z,t]}),T(""))},Ne=t=>{A.updateSettings({customAgentNames:Z.filter(P=>P!==t)})},me=()=>{A.updateSettings({customAgentNames:[]})},le=()=>{const t=F.trim();if(t){if(u.includes(t)){z("");return}y([...u,t]),c(!0),z("")}},Te=t=>{y(u.filter((P,q)=>q!==t)),c(!0)},we=(t,P)=>{const q=t+P;if(q<0||q>=u.length)return;const pe=u.slice();[pe[t],pe[q]]=[pe[q],pe[t]],y(pe),c(!0)},ue=()=>{ks(u),c(!1),De()},Ee=t=>{w(t),V(!0)},ye=()=>{Se(be.AUTH_TOKEN,R),V(!1),De()},Ie=t=>{D(t),J(!0)},ke=()=>{Ws(v).catch(()=>{}),J(!1)},ne=t=>{o({...s,terrain:{...s.terrain,...t}})},ie=t=>{o({...s,modelStyle:{...s.modelStyle,...t}})},xe=t=>{o({...s,animations:{...s.animations,...t}})},Pe=t=>{g(t),A.updateSettings({historyLimit:t})},Le=t=>{const P=s.terrain[t];typeof P=="boolean"&&ne({[t]:!P})},_=a.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-section",children:[de&&de.length===0&&e.jsx("div",{className:"config-no-results",children:n("config:noResults",{query:a})}),S("general")&&e.jsxs(U,{title:n("config:sections.general"),storageKey:"general",defaultOpen:!0,forceOpen:_&&S("general"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.history"),query:a})}),e.jsx("input",{type:"number",className:"config-input config-input-sm",value:d,onChange:t=>Pe(parseInt(t.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(C,{text:n("config:general.hideCosts"),query:a})}),e.jsx(Q,{checked:h.settings.hideCost,onChange:t=>A.updateSettings({hideCost:t})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.grid"),query:a})}),e.jsx(Q,{checked:s.gridVisible,onChange:t=>o({...s,gridVisible:t})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.showFPS"),query:a})}),e.jsx(Q,{checked:h.settings.showFPS,onChange:t=>A.updateSettings({showFPS:t})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.fpsLimit"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"120",step:"10",value:s.fpsLimit,onChange:t=>o({...s,fpsLimit:parseInt(t.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(C,{text:n("config:general.powerSaving"),query:a})," ",e.jsx(L,{name:"bolt",size:12})]}),e.jsx(Q,{checked:h.settings.powerSaving,onChange:t=>A.updateSettings({powerSaving:t})})]}),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(C,{text:n("config:general.tmuxMode"),query:a})}),e.jsx(Q,{checked:h.settings.tmuxMode,onChange:async t=>{A.updateSettings({tmuxMode:t});try{await Gs(t)}catch(P){console.error("Failed to sync tmux mode setting to server:",P)}}})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.vibrationIntensity"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"5",step:"1",value:h.settings.vibrationIntensity,onChange:t=>A.updateSettings({vibrationIntensity:parseInt(t.target.value)})}),e.jsx("span",{className:"config-value",children:h.settings.vibrationIntensity===0?n("config:vibrationValues.off"):h.settings.vibrationIntensity===1?n("config:vibrationValues.ultraLight"):h.settings.vibrationIntensity===2?n("config:vibrationValues.veryLight"):h.settings.vibrationIntensity===3?n("config:vibrationValues.light"):h.settings.vibrationIntensity===4?n("config:vibrationValues.medium"):n("config:vibrationValues.heavy")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.externalEditor"),query:a})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.externalEditorPlaceholder"),value:h.settings.externalEditorCommand||"",onChange:t=>A.updateSettings({externalEditorCommand:t.target.value})})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.tabTitle"),query:a})}),e.jsx("input",{type:"text",className:"config-input",placeholder:n("config:general.tabTitlePlaceholder"),value:h.settings.tabTitle||"",onChange:t=>A.updateSettings({tabTitle:t.target.value})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:general.language"),query:a})}),e.jsx(he,{options:$e,value:localStorage.getItem("tide-commander-language-mode")==="manual"?((p=$e.find(t=>t.value!=="auto"&&Oe.language.startsWith(t.value.split("-")[0])))==null?void 0:p.value)||"en":"auto",onChange:t=>{var P;if(t==="auto"){localStorage.setItem("tide-commander-language-mode","auto");const q=navigator.language,pe=((P=$e.find(Ke=>Ke.value!=="auto"&&q.startsWith(Ke.value.split("-")[0])))==null?void 0:P.value)||"en";Oe.changeLanguage(pe)}else localStorage.setItem("tide-commander-language-mode","manual"),Oe.changeLanguage(t)}})]})]}),S("agentNames")&&e.jsx(U,{title:n("config:sections.agentNames"),storageKey:"agentNames",defaultOpen:!1,forceOpen:_&&S("agentNames"),children:e.jsxs("div",{className:"agent-names-section",children:[e.jsx("span",{className:"config-hint",children:Z.length>0?n("config:agentNames.customConfigured",{count:Z.length}):n("config:agentNames.usingDefaults")}),e.jsxs("div",{className:"agent-names-input-row",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",placeholder:n("config:agentNames.addPlaceholder"),value:N,onChange:t=>T(t.target.value),onKeyDown:t=>{t.key==="Enter"&&te()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:te,disabled:!N.trim(),title:n("config:agentNames.addName"),children:"+"})]}),e.jsx("div",{className:"agent-names-list",children:fe.map((t,P)=>e.jsxs("div",{className:"agent-name-chip",children:[e.jsx("span",{className:"agent-name-text",children:t}),Z.length>0&&e.jsx("button",{className:"agent-name-remove",onClick:()=>Ne(t),title:n("common:buttons.remove"),children:"x"})]},`${t}-${P}`))}),Z.length>0&&e.jsx("button",{className:"config-btn config-btn-link",onClick:me,children:n("common:buttons.resetToDefaults")})]})}),S("defaultClass")&&e.jsx(U,{title:"Default Spawn Class",storageKey:"defaultClass",defaultOpen:!1,forceOpen:_&&S("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${b==="random"?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{k("random"),Se(be.DEFAULT_AGENT_CLASS,"random")},children:e.jsx("span",{className:"agent-name-text",children:"🎲 Random"})}),Object.entries(ys).map(([t,P])=>e.jsx("div",{className:`agent-name-chip${b===t?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{k(t),Se(be.DEFAULT_AGENT_CLASS,t)},children:e.jsxs("span",{className:"agent-name-text",children:[P.icon," ",t.charAt(0).toUpperCase()+t.slice(1)]})},t)),I.map(t=>e.jsx("div",{className:`agent-name-chip${b===t.id?" agent-name-chip--selected":""}`,style:{cursor:"pointer",userSelect:"none"},onClick:()=>{k(t.id),Se(be.DEFAULT_AGENT_CLASS,t.id)},children:e.jsxs("span",{className:"agent-name-text",children:[t.icon," ",t.name]})},t.id))]})]})}),S("appearance")&&e.jsx(U,{title:n("config:sections.appearance"),storageKey:"appearance",defaultOpen:!1,forceOpen:_&&S("appearance"),children:e.jsx(Qs,{})}),S("connection")&&e.jsxs(U,{title:n("config:sections.connection"),storageKey:"connection",defaultOpen:!1,forceOpen:_&&S("connection"),children:[e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:connection.backendUrl"),query:a})}),e.jsx("div",{className:"backend-urls-list",children:u.map((t,P)=>e.jsxs("div",{className:"backend-url-row",children:[e.jsx("span",{className:"backend-url-priority",title:n("config:connection.priorityLabel",{defaultValue:"Priority"}),children:P+1}),e.jsx("span",{className:"backend-url-text",title:t,children:t}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>we(P,-1),disabled:P===0,title:n("config:connection.moveUp",{defaultValue:"Move up"}),children:"↑"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>we(P,1),disabled:P===u.length-1,title:n("config:connection.moveDown",{defaultValue:"Move down"}),children:"↓"}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>Te(P),title:n("common:buttons.remove"),children:"x"})]},`${t}-${P}`))}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:F,onChange:t=>z(t.target.value),placeholder:n("config:connection.addUrlPlaceholder",{defaultValue:"http://host:port"}),onKeyDown:t=>{t.key==="Enter"&&le()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:le,disabled:!F.trim(),title:n("config:connection.addUrl",{defaultValue:"Add URL"}),children:"+"}),x&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:ue,title:n("config:connection.saveAndReconnect"),children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("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(C,{text:n("config:connection.authToken"),query:a})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:B?"text":"password",className:"config-input config-input-full",value:R,onChange:t=>Ee(t.target.value),placeholder:n("config:connection.tokenPlaceholder"),onKeyDown:t=>{t.key==="Enter"&&E&&ye()}}),e.jsx("button",{className:"config-btn config-btn-sm",onClick:()=>W(!B),title:n(B?"config:connection.hideToken":"config:connection.showToken"),children:e.jsx(L,{name:B?"eye-closed":"eye",size:14})}),E&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:ye,title:n("config:connection.saveAndReconnect"),children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("config:connection.tokenRequired")})]}),e.jsxs("div",{className:"config-row config-row-stacked",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:connection.codexBinaryPath"),query:a})}),e.jsxs("div",{className:"config-input-group",children:[e.jsx("input",{type:"text",className:"config-input config-input-full",value:v,onChange:t=>Ie(t.target.value),placeholder:n("config:connection.codexBinaryPathPlaceholder"),onKeyDown:t=>{t.key==="Enter"&&$&&ke()}}),$&&e.jsx("button",{className:"config-btn config-btn-sm",onClick:ke,children:n("common:buttons.apply")})]}),e.jsx("span",{className:"config-hint",children:n("config:connection.codexBinaryPathHint")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("common:buttons.reconnect"),query:a})}),e.jsx("button",{className:"config-btn",onClick:()=>De(),title:"Force reconnect to server",children:n("common:buttons.reconnect")})]})]}),S("scene")&&e.jsxs(U,{title:n("config:sections.scene"),storageKey:"scene",defaultOpen:!1,forceOpen:_&&S("scene"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:scene.characterSize"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"3.0",step:"0.1",value:s.characterScale,onChange:t=>o({...s,characterScale:parseFloat(t.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(C,{text:n("config:scene.scale2d",{defaultValue:"2D Scale"}),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale2d,onChange:t=>o({...s,scale2d:parseFloat(t.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(C,{text:n("config:scene.scale3d",{defaultValue:"3D Scale"}),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.3",max:"2.0",step:"0.1",value:s.scale3d,onChange:t=>o({...s,scale3d:parseFloat(t.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(C,{text:n("config:scene.show2DTaskLabels",{defaultValue:"Show 2D task labels"}),query:a})}),e.jsx(Q,{checked:s.show2DTaskLabels,onChange:t=>o({...s,show2DTaskLabels:t})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:scene.time"),query:a})}),e.jsx(he,{options:ae,value:s.timeMode,onChange:t=>o({...s,timeMode:t}),iconOnly:!0})]})]}),S("terrain")&&e.jsxs(U,{title:n("config:sections.terrain"),storageKey:"terrain",defaultOpen:!1,forceOpen:_&&S("terrain"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:terrainSettings.simpleMode",{defaultValue:"Simple Mode"}),query:a})}),e.jsx(Q,{checked:s.terrain.simpleMode??!1,onChange:t=>ne({simpleMode:t})})]}),e.jsx("div",{className:"terrain-icons",style:{opacity:s.terrain.simpleMode?.4:1,pointerEvents:s.terrain.simpleMode?"none":"auto"},children:ve.map(t=>e.jsx("button",{className:`terrain-icon-btn ${s.terrain[t.key]?"active":""}`,onClick:()=>Le(t.key),title:t.label,children:t.icon},t.key))}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:terrainSettings.fog"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.terrain.fogDensity,onChange:t=>ne({fogDensity:parseFloat(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.fogDensity===0?n("config:fogValues.off"):s.terrain.fogDensity<=1?n("config:fogValues.low"):n("config:fogValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:terrainSettings.brightness"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0.2",max:"2",step:"0.1",value:s.terrain.brightness,onChange:t=>ne({brightness:parseFloat(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.brightness<=.5?n("config:brightnessValues.dark"):s.terrain.brightness<=1.2?n("config:brightnessValues.normal"):n("config:brightnessValues.bright")})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:terrainSettings.floor"),query:a})}),e.jsx(he,{options:X,value:s.terrain.floorStyle,onChange:t=>ne({floorStyle:t}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:terrainSettings.sky"),query:a})}),e.jsx("div",{className:"sky-color-selector",children:Ae.map(t=>e.jsx("button",{className:`sky-color-btn ${s.terrain.skyColor===t.value?"active":""}`,onClick:()=>ne({skyColor:t.value}),title:t.label,style:{background:t.color}},t.value??"auto"))})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:terrainSettings.battlefieldSize"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"30",max:"200",step:"10",value:s.terrain.battlefieldSize,onChange:t=>ne({battlefieldSize:parseInt(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.terrain.battlefieldSize})]})]}),S("modelStyle")&&e.jsxs(U,{title:n("config:sections.modelStyle"),storageKey:"modelStyle",defaultOpen:!1,forceOpen:_&&S("modelStyle"),children:[e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:modelStyleSettings.saturation"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"2",step:"0.1",value:s.modelStyle.saturation,onChange:t=>ie({saturation:parseFloat(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.saturation<=.3?n("config:saturationValues.gray"):s.modelStyle.saturation<=1.2?n("config:saturationValues.normal"):n("config:saturationValues.vivid")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:modelStyleSettings.roughness"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.roughness,onChange:t=>ie({roughness:parseFloat(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.roughness<0?n("config:roughnessValues.auto"):s.modelStyle.roughness<=.3?n("config:roughnessValues.glossy"):s.modelStyle.roughness<=.7?n("config:roughnessValues.normal"):n("config:roughnessValues.matte")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:modelStyleSettings.metalness"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"1",step:"0.1",value:s.modelStyle.metalness,onChange:t=>ie({metalness:parseFloat(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.metalness<0?n("config:metalnessValues.auto"):s.modelStyle.metalness<=.3?n("config:metalnessValues.plastic"):s.modelStyle.metalness<=.7?n("config:metalnessValues.mixed"):n("config:metalnessValues.metal")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:modelStyleSettings.glow"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"0",max:"1",step:"0.05",value:s.modelStyle.emissiveBoost,onChange:t=>ie({emissiveBoost:parseFloat(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.emissiveBoost<=.1?n("config:glowValues.off"):s.modelStyle.emissiveBoost<=.4?n("config:glowValues.low"):s.modelStyle.emissiveBoost<=.7?n("config:glowValues.med"):n("config:glowValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:modelStyleSettings.reflections"),query:a})}),e.jsx("input",{type:"range",className:"config-slider",min:"-1",max:"2",step:"0.1",value:s.modelStyle.envMapIntensity,onChange:t=>ie({envMapIntensity:parseFloat(t.target.value)})}),e.jsx("span",{className:"config-value",children:s.modelStyle.envMapIntensity<0?n("config:reflectionValues.auto"):s.modelStyle.envMapIntensity<=.3?n("config:reflectionValues.low"):s.modelStyle.envMapIntensity<=1?n("config:reflectionValues.normal"):n("config:reflectionValues.high")})]}),e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:modelStyleSettings.wireframe"),query:a})}),e.jsx(Q,{checked:s.modelStyle.wireframe,onChange:t=>ie({wireframe:t})})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:modelStyleSettings.colorMode"),query:a})}),e.jsx(he,{options:ge,value:s.modelStyle.colorMode,onChange:t=>ie({colorMode:t}),iconOnly:!0})]})]}),S("animations")&&e.jsxs(U,{title:n("config:sections.animations"),storageKey:"animations",defaultOpen:!1,forceOpen:_&&S("animations"),children:[e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:animationSettings.idle"),query:a})}),e.jsx(he,{options:G,value:s.animations.idleAnimation,onChange:t=>xe({idleAnimation:t}),iconOnly:!0})]}),e.jsxs("div",{className:"config-group",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:animationSettings.working"),query:a})}),e.jsx(he,{options:G,value:s.animations.workingAnimation,onChange:t=>xe({workingAnimation:t}),iconOnly:!0})]})]}),S("secrets")&&e.jsx(U,{title:n("config:sections.secrets"),storageKey:"secrets",defaultOpen:!1,forceOpen:_&&S("secrets"),children:e.jsx(_s,{})}),S("systemPrompt")&&e.jsx(U,{title:n("config:sections.systemPrompt"),storageKey:"systemPrompt",defaultOpen:!1,forceOpen:_&&S("systemPrompt"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:systemPrompt.title"),query:a})}),e.jsx("button",{className:"config-button",onClick:()=>se(!0),children:n("config:systemPrompt.editPrompt")})]})}),S("whatsapp")&&e.jsx(U,{title:n("config:sections.whatsapp"),storageKey:"whatsapp",defaultOpen:!1,forceOpen:_&&S("whatsapp"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:whatsapp.title"),query:a})}),e.jsx("button",{className:"config-button",onClick:()=>j(!0),children:n("config:whatsapp.editConfig")})]})}),S("whatsappNotifications")&&e.jsx(U,{title:n("config:sections.whatsappNotifications"),storageKey:"whatsappNotifications",defaultOpen:!1,forceOpen:_&&S("whatsappNotifications"),children:e.jsxs("div",{className:"config-row",children:[e.jsx("span",{className:"config-label",children:e.jsx(C,{text:n("config:whatsappNotifications.title"),query:a})}),e.jsx("button",{className:"config-button",onClick:()=>K(!0),children:n("config:whatsappNotifications.editButton")})]})}),S("data")&&e.jsx(U,{title:n("config:sections.data"),storageKey:"data",defaultOpen:!1,forceOpen:_&&S("data"),children:e.jsx(Xs,{})}),S("integrations")&&e.jsx(U,{title:"Integrations",storageKey:"integrations",defaultOpen:!1,forceOpen:_&&S("integrations"),children:e.jsx(aa,{onOpenModal:t=>i==null?void 0:i(t)})}),S("workflows")&&e.jsxs(U,{title:"Workflows",storageKey:"workflows",defaultOpen:!1,forceOpen:_&&S("workflows"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(C,{text:"Create and manage automated workflow pipelines with visual state machine editor",query:a})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>f==null?void 0:f(),children:"Open Workflow Editor"})})]}),S("triggers")&&e.jsxs(U,{title:"Triggers",storageKey:"triggers",defaultOpen:!1,forceOpen:_&&S("triggers"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(C,{text:"Create and manage event-driven triggers that fire agents with templates",query:a})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>r==null?void 0:r(),children:"Open Trigger Manager"})})]}),S("monitoring")&&e.jsxs(U,{title:"Monitoring",storageKey:"monitoring",defaultOpen:!1,forceOpen:_&&S("monitoring"),children:[e.jsx("div",{className:"config-row",children:e.jsx("span",{className:"config-label",children:e.jsx(C,{text:"View event logs, trigger history, workflow traces, and system stats",query:a})})}),e.jsx("div",{className:"config-row",children:e.jsx("button",{className:"config-button",onClick:()=>m==null?void 0:m(),children:"Open Monitoring & Logs"})})]}),S("experimental")&&e.jsxs(U,{title:n("config:sections.experimental"),storageKey:"experimental",defaultOpen:!1,forceOpen:_&&S("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(C,{text:n("config:experimental.2dView"),query:a})," ",e.jsx(L,{name:"map",size:12})]}),e.jsx(Q,{checked:h.settings.experimental2DView,onChange:t=>A.updateSettings({experimental2DView:t})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Voice assistant for hands-free agent control",children:[e.jsx(C,{text:n("config:experimental.voiceAssistant"),query:a})," ",e.jsx(L,{name:"microphone",size:12})]}),e.jsx(Q,{checked:h.settings.experimentalVoiceAssistant,onChange:t=>A.updateSettings({experimentalVoiceAssistant:t})})]}),e.jsxs("div",{className:"config-row",children:[e.jsxs("span",{className:"config-label",title:"Text-to-speech for reading agent responses",children:[e.jsx(C,{text:n("config:experimental.tts"),query:a})," ",e.jsx(L,{name:"speaker-on",size:12})]}),e.jsx(Q,{checked:h.settings.experimentalTTS,onChange:t=>A.updateSettings({experimentalTTS:t})})]}),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(C,{text:n("config:experimental.echoPrompt"),query:a})}),e.jsx(Q,{checked:h.settings.experimentalEchoPrompt,onChange:async t=>{A.updateSettings({experimentalEchoPrompt:t});try{await Ms(t)}catch(P){console.error("Failed to sync echo prompt setting to server:",P)}}})]}),e.jsx("span",{className:"config-hint",children:n("config:experimental.hint")})]}),S("about")&&e.jsx(U,{title:n("config:sections.about"),storageKey:"about",defaultOpen:!1,forceOpen:_&&S("about"),children:e.jsx(ea,{})})]}),e.jsx(ta,{isOpen:M,onClose:()=>se(!1)}),e.jsx(la,{isOpen:oe,onClose:()=>j(!1)}),e.jsx(pa,{isOpen:O,onClose:()=>K(!1)})]})}function Ta({onConfigChange:s,onToolChange:o,config:a,isOpen:i,onClose:m,onOpenBuildingModal:f,onOpenAreaExplorer:r,onOpenIntegrationsModal:n,onOpenMonitoringModal:h,onOpenWorkflowEditor:I,onOpenTriggerManager:b}){const{t:k}=ee(["config","common"]),d=Re(),g=Array.from(d.areas.values()),u=Array.from(d.buildings.values()),[y,x]=l.useState(""),c=l.useRef(null);if(l.useEffect(()=>{const w=E=>{E.key==="Escape"&&i&&m()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[i,m]),l.useEffect(()=>{if(i&&c.current){if(typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches)return;const E=setTimeout(()=>{var V;(V=c.current)==null||V.focus()},50);return()=>clearTimeout(E)}},[i]),!i)return null;const F=w=>{const E=d.activeTool===w?null:w;o(E)},z=w=>{A.selectArea(d.selectedAreaId===w?null:w),o("select")},R=(w,E)=>{w.stopPropagation(),A.deleteArea(E)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"toolbox-backdrop",onClick:m}),e.jsxs("aside",{className:"toolbox",children:[e.jsxs("div",{className:"toolbox-header",children:[e.jsx("span",{children:k("config:title")}),e.jsx("button",{className:"toolbox-close-btn",onClick:m,title:k("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:c,type:"text",placeholder:k("config:searchPlaceholder"),value:y,onChange:w=>x(w.target.value),className:"toolbox-search-input"}),y&&e.jsx("button",{className:"toolbox-search-clear",onClick:()=>x(""),children:"×"})]}),e.jsxs("div",{className:"toolbox-content",children:[e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsxs(U,{title:k("config:areas.title",{count:g.length}),storageKey:"areas",children:[e.jsxs("div",{className:"tool-buttons",children:[e.jsx("button",{className:`tool-btn ${d.activeTool==="select"?"active":""}`,onClick:()=>F("select"),title:k("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 ${d.activeTool==="rectangle"?"active":""}`,onClick:()=>F("rectangle"),title:k("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 ${d.activeTool==="circle"?"active":""}`,onClick:()=>F("circle"),title:k("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:g.length===0?e.jsx("div",{className:"areas-empty",children:k("config:areas.drawToCreate")}):g.map(w=>e.jsx(Ps,{area:w,isSelected:d.selectedAreaId===w.id,onClick:()=>z(w.id),onDelete:E=>R(E,w.id)},w.id))})]})}),d.selectedAreaId&&e.jsx(zs,{area:d.areas.get(d.selectedAreaId),onClose:()=>A.selectArea(null),onOpenFolder:r}),e.jsx("div",{className:"toolbox-section toolbox-section-collapsible",children:e.jsx(U,{title:k("config:buildings.title",{count:u.length}),storageKey:"buildings",headerExtra:e.jsx("button",{className:"add-building-btn",onClick:w=>{w.stopPropagation(),f==null||f()},title:k("config:buildings.addBuilding"),children:"+"}),children:e.jsx("div",{className:"buildings-list",children:u.length===0?e.jsx("div",{className:"buildings-empty",children:k("config:buildings.clickToAdd")}):u.map(w=>e.jsx(Ls,{building:w,isSelected:d.selectedBuildingIds.has(w.id),onClick:()=>{A.selectBuilding(d.selectedBuildingIds.has(w.id)?null:w.id)},onEdit:()=>f==null?void 0:f(w.id)},w.id))})})}),d.selectedBuildingIds.size===1&&(()=>{const w=Array.from(d.selectedBuildingIds)[0],E=d.buildings.get(w);return E?e.jsx(Fs,{building:E,onClose:()=>A.selectBuilding(null),onOpenModal:()=>f==null?void 0:f(w)}):null})(),e.jsx(ka,{config:a,onChange:s,searchQuery:y,onOpenIntegrationsModal:n,onOpenMonitoringModal:h,onOpenWorkflowEditor:I,onOpenTriggerManager:b})]})]})]})}export{Ta as Toolbox};
@@ -1,5 +1,5 @@
1
- import{bk as He,r as t,s as I,l as ye,bl as Ee,aF as _e,j as e,I as z,u as fe,bm as ze,bn as Te,bo as Be,bp as Ue,m as We,bq as Ke,br as De,bs as Ve,a2 as Ge,a3 as qe,bt as Ye,aO as Je,E as Me,S as oe,aI as Xe,aE as Qe,W as Ze,G as Ie,ad as et,N as tt,bu as st,n as X,bv as nt}from"./main-BlnQCHb9.js";import{F as at}from"./index-CdSYWPJD.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Se={status:"all",activity:"all",sort:"activity"},lt={"1h":3600*1e3,"6h":360*60*1e3,"24h":1440*60*1e3},Ae=20,me=3,ot={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a"},ct=12e4;function rt(s){return s.trim().replace(/\r\n/g,`
2
- `)}function $e(s,a){return`${s}:${rt(a)}`}function it(s,a,l,f){if(s.uuid&&a.has(s.uuid))return!1;if(s.uuid)return!0;const p=s.isUserPrompt?"user":"assistant",d=$e(p,s.text),M=s.timestamp||0,A=l.get(d);return A!==void 0&&Math.abs(M-A)<=ct?!1:M>f}function dt({isOpen:s,agents:a}){const l=He(),[f,p]=t.useState(new Map),d=t.useRef(new Set);t.useRef(a);const M=t.useMemo(()=>Array.from(a.keys()).sort().join(","),[a]),A=t.useMemo(()=>Array.from(a.values()).map(j=>`${j.id}:${j.sessionId||""}`).sort().join(","),[a]);t.useEffect(()=>{s||(d.current.clear(),p(new Map))},[s]),t.useEffect(()=>{if(!s)return;const j=new Set(Array.from(a.keys()));for(const i of d.current)j.has(i)||d.current.delete(i);let h=null;l>0&&(h=I.preserveOutputs(),d.current.clear());const v=async(i,C,F=0)=>{if(d.current.add(i.id),F>0&&await new Promise(x=>setTimeout(x,F)),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!0,hasMore:!1,totalCount:0}),k}),!i.sessionId){C&&C.length>0&&I.mergeOutputsWithHistory(i.id,[],C),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),k});return}try{const k=await(await _e(ye(`/api/agents/${i.id}/history?limit=${Ee}&offset=0`))).json(),P=k.messages||[],K=P.length>0?Math.max(...P.map(w=>w.timestamp?new Date(w.timestamp).getTime():0)):0,Y=new Set(P.map(w=>w.uuid).filter(w=>!!w)),V=new Map;for(const w of P){if(w.type!=="user"&&w.type!=="assistant")continue;const c=$e(w.type,w.content),L=w.timestamp?new Date(w.timestamp).getTime():0,W=V.get(c)??0;L>W&&V.set(c,L)}const G=I.getOutputs(i.id),U=(C&&C.length>0?[...C,...G]:G).filter(w=>it(w,Y,V,K));I.clearOutputs(i.id);for(const w of U)I.addOutput(i.id,w);p(w=>{const c=new Map(w);return c.set(i.id,{agentId:i.id,messages:P,loading:!1,hasMore:k.hasMore||!1,totalCount:k.totalCount||0}),c})}catch(x){if(console.error(`Failed to load history for ${i.name}:`,x),C&&C.length>0){I.clearOutputs(i.id);for(const k of C)I.addOutput(i.id,k)}p(k=>{const P=new Map(k);return P.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),P})}},u=l>0?500:0,D=Array.from(a.values());for(const i of D)if(!d.current.has(i.id)){const C=h==null?void 0:h.get(i.id);v(i,C,u)}},[s,M,A,l]);const R=t.useRef(a),S=t.useRef(f);R.current=a,S.current=f;const b=t.useCallback(async j=>{const h=R.current.get(j),v=S.current.get(j);if(!(h!=null&&h.sessionId)||!v||!v.hasMore)return;const u=v.messages.length;try{const i=await(await fetch(ye(`/api/agents/${j}/history?limit=${Ee}&offset=${u}`))).json();i.messages&&i.messages.length>0&&p(C=>{const F=new Map(C),x=C.get(j);return x&&F.set(j,{...x,messages:[...i.messages,...x.messages],hasMore:i.hasMore||!1}),F})}catch(D){console.error(`Failed to load more history for agent ${j}:`,D)}},[]),E=t.useCallback(j=>{d.current.delete(j),p(h=>{const v=new Map(h),u=h.get(j);return u&&v.set(j,{...u,messages:[],hasMore:!1,totalCount:0,loading:!1}),v})},[]);return{histories:f,loadMoreHistory:b,clearAgentHistory:E}}function ut({command:s,onCommandChange:a,useTextarea:l,forceTextarea:f,onForceTextarea:p,onSend:d,canSend:M,attachedFiles:A,onAddFile:R,onRemoveFile:S,uploadFile:b,onAddPastedText:E,placeholder:j="Message...",className:h="",compact:v=!1,inputRef:u}){const D=t.useRef(null),i=t.useRef(null),C=t.useRef(l);t.useEffect(()=>{if(l&&!C.current&&i.current){const c=i.current;c.focus(),c.selectionStart=c.selectionEnd=c.value.length}C.current=l},[l]),t.useEffect(()=>{const c=i.current;if(!c||!l)return;c.style.height="auto";const L=v?120:180,W=Math.min(c.scrollHeight,L);c.style.height=`${W}px`},[s,l,v]);const F=t.useCallback(async c=>{const L=c.clipboardData.items;for(const _ of L)if(_.type.startsWith("image/")){c.preventDefault();const $=_.getAsFile();if($){const O=await b($);O&&R(O)}return}const W=c.clipboardData.files;if(W.length>0){c.preventDefault();for(const _ of W){const $=await b(_);$&&R($)}return}const B=c.clipboardData.getData("text"),te=(B.match(/\n/g)||[]).length+1;if(te>5){c.preventDefault();const $=`[Pasted text #${E(B)} +${te} lines]`,O=c.target,se=O.selectionStart||0,ae=O.selectionEnd||0,ne=s.slice(0,se)+$+s.slice(ae);a(ne),l||p(!0)}},[s,a,l,p,b,R,E]),x=t.useCallback(async c=>{const L=c.target.files;if(L){for(const W of L){const B=await b(W);B&&R(B)}D.current&&(D.current.value="")}},[b,R]),k=t.useCallback(c=>{if(c.key==="Enter"&&c.shiftKey){l||(c.preventDefault(),p(!0));return}c.key==="Enter"&&(c.preventDefault(),d())},[l,p,d]),P=t.useCallback(c=>{},[]),K=t.useCallback(c=>{c.button===1&&(c.preventDefault(),c.stopPropagation())},[]),Y=t.useCallback(c=>{i.current=c,u==null||u(c)},[u]),V=v?"agent-panel-input":"guake-input",G=v?"agent-panel-input-container":"guake-input-container",Q=v?"agent-panel-attach-btn":"guake-attach-btn",U=v?"agent-panel-send-btn":"",w=l?v?"agent-panel-input-expanded":"guake-input-expanded":"";return e.jsxs(e.Fragment,{children:[A.length>0&&e.jsx("div",{className:v?"agent-panel-attachments":"guake-attachments",children:A.map(c=>e.jsxs("div",{className:`${v?"agent-panel-attachment":"guake-attachment"} ${c.isImage?"is-image":""}`,children:[e.jsx("span",{className:v?"agent-panel-attachment-icon":"guake-attachment-icon",children:e.jsx(z,{name:c.isImage?"file":"paperclip",size:12})}),e.jsx("span",{className:v?"agent-panel-attachment-name":"guake-attachment-name",title:c.path,children:c.name}),!v&&e.jsxs("span",{className:"guake-attachment-size",children:["(",Math.round(c.size/1024),"KB)"]}),e.jsx("button",{className:v?"agent-panel-attachment-remove":"guake-attachment-remove",onClick:()=>S(c.id),title:"Remove",children:"×"})]},c.id))}),e.jsxs("div",{className:`${V} ${w} ${h}`,children:[e.jsx("input",{ref:D,type:"file",multiple:!0,onChange:x,style:{display:"none"},accept:"*"}),e.jsxs("div",{className:G,onAuxClick:K,children:[e.jsx("button",{className:Q,onClick:()=>{var c;return(c=D.current)==null?void 0:c.click()},title:"Attach file (or paste image)",children:e.jsx(z,{name:"paperclip",size:14})}),l?e.jsx("textarea",{ref:Y,placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:P}):e.jsx("input",{ref:u,type:"text",placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:P}),e.jsx("button",{className:U,onClick:d,disabled:!M,title:"Send",children:e.jsx(z,{name:"send",size:14})})]})]})]})}function mt(s){const a=Math.floor(s/1e3),l=Math.floor(a/60),f=a%60;return`${l}:${f.toString().padStart(2,"0")}`}const ft=t.memo(function({agentId:a,isWorking:l,timestamp:f}){const{t:p}=fe(["terminal"]),[d,M]=t.useState(0);return t.useEffect(()=>{if(!l||!f){M(0);return}M(Date.now()-f);const A=setInterval(()=>{M(Date.now()-f)},1e3);return()=>clearInterval(A)},[l,f]),l?e.jsxs("div",{className:"guake-stop-bar",children:[e.jsx("span",{className:"guake-elapsed-timer",children:mt(d)}),e.jsxs("button",{className:"guake-stop-btn",onClick:()=>I.stopAgent(a),title:p("terminal:input.stopOperation"),children:[e.jsx("span",{className:"stop-icon",children:e.jsx(z,{name:"stop",size:12,weight:"fill"})}),e.jsx("span",{className:"stop-label",children:p("terminal:input.stop")})]})]}):null});function pt({agent:s,history:a,outputs:l,isExpanded:f,isFocused:p,advancedView:d,onExpand:M,onFocus:A,inputRef:R,onLoadMore:S,onClearHistory:b}){const{t:E}=fe(["terminal","common"]),j=ze(s.id),h=t.useRef(null),[v,u]=t.useState(!1),D=t.useRef(0),i=t.useRef(!1),[C,F]=t.useState(!0),[x,k]=t.useState(!1),[P,K]=t.useState(null),[Y,V]=t.useState(null),[G,Q]=t.useState(null);Te(`commander-image-modal-${s.id}`,P!==null,()=>K(null));const{command:U,setCommand:w,forceTextarea:c,setForceTextarea:L,useTextarea:W,setPastedTexts:B,incrementPastedCount:te,resetPastedCount:_,attachedFiles:$,setAttachedFiles:O,removeAttachedFile:se,uploadFile:ae,expandPastedTexts:ne}=Be({selectedAgentId:s.id}),le=U.trim().length>0||$.length>0,n=Ue({outputs:l,viewMode:d?"advanced":"simple"}),o=t.useMemo(()=>{const N=We(s);return{usedPercent:N.usedPercent,freePercent:N.freePercent,hasData:!!s.contextStats,totalTokens:N.totalTokens,contextWindow:N.contextWindow}},[s.contextStats,s.contextUsed,s.contextLimit]),g=t.useCallback(()=>{!v&&(a!=null&&a.hasMore)&&S&&(u(!0),D.current=h.current?h.current.scrollHeight-h.current.scrollTop:0,S())},[v,a==null?void 0:a.hasMore,S]);t.useEffect(()=>{v&&a&&!a.loading&&u(!1)},[a,v]);const m=t.useCallback(()=>{i.current=!0,F(!1)},[]),T=t.useRef(f),Z=t.useRef(p);t.useEffect(()=>{(f&&!T.current||p&&!Z.current)&&(i.current=!1,F(!0),k(!0)),T.current=f,Z.current=p},[f,p]);const ee=t.useRef(a==null?void 0:a.loading);t.useEffect(()=>{ee.current&&!(a!=null&&a.loading)&&(i.current=!1,F(!0),k(!0)),ee.current=a==null?void 0:a.loading},[a==null?void 0:a.loading]),t.useEffect(()=>{if(!x)return;const N=h.current;if(!N)return;const y=performance.now();let H=0,ue=-1,ke;const Re=()=>{const{scrollTop:Fe,scrollHeight:Ne,clientHeight:Le}=N,Oe=Ne-Fe-Le<=2;if(Math.abs(Ne-ue)<=1&&Oe?H+=1:H=0,ue=Ne,H>=3){k(!1);return}if(performance.now()-y>5e3){k(!1);return}ke=requestAnimationFrame(Re)};return ke=requestAnimationFrame(Re),()=>cancelAnimationFrame(ke)},[x]),t.useEffect(()=>{i.current||F(!0)},[n.length]);const q=t.useCallback(()=>!1,[]),ie=t.useCallback(N=>{const y=te();return B(H=>new Map(H).set(y,N)),y},[te,B]),he=t.useCallback(N=>{O(y=>[...y,N])},[O]),xe=t.useCallback(()=>{if(!le)return;if(U.trim()==="/clear"&&$.length===0){I.clearContext(s.id),b(),w(""),L(!1),B(new Map),O([]),_();return}let N=ne(U.trim());if($.length>0){const y=$.map(H=>H.isImage?`[Image: ${H.path}]`:`[File: ${H.path}]`).join(`
3
- `);N=N?`${N}
1
+ import{bm as Oe,r as t,s as I,l as ye,bn as Ee,aH as _e,j as e,I as z,u as fe,bo as ze,bp as Te,bq as Be,br as Ue,m as Ke,bs as We,bt as De,bu as Ve,a4 as Ge,a5 as qe,bv as Ye,aQ as Je,G as Me,S as oe,aK as Qe,aG as Xe,Y as Ze,H as Ie,af as et,O as tt,bw as st,n as Q,bx as nt}from"./main-DFVcOIIz.js";import{F as at}from"./index-5oP0HT38.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const Ne={status:"all",activity:"all",sort:"activity"},lt={"1h":3600*1e3,"6h":360*60*1e3,"24h":1440*60*1e3},Ae=20,me=3,ot={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a"},ct=12e4;function rt(s){return s.trim().replace(/\r\n/g,`
2
+ `)}function $e(s,a){return`${s}:${rt(a)}`}function it(s,a,l,f){if(s.uuid&&a.has(s.uuid))return!1;if(s.uuid)return!0;const p=s.isUserPrompt?"user":"assistant",d=$e(p,s.text),M=s.timestamp||0,A=l.get(d);return A!==void 0&&Math.abs(M-A)<=ct?!1:M>f}function dt({isOpen:s,agents:a}){const l=Oe(),[f,p]=t.useState(new Map),d=t.useRef(new Set);t.useRef(a);const M=t.useMemo(()=>Array.from(a.keys()).sort().join(","),[a]),A=t.useMemo(()=>Array.from(a.values()).map(j=>`${j.id}:${j.sessionId||""}`).sort().join(","),[a]);t.useEffect(()=>{s||(d.current.clear(),p(new Map))},[s]),t.useEffect(()=>{if(!s)return;const j=new Set(Array.from(a.keys()));for(const i of d.current)j.has(i)||d.current.delete(i);let h=null;l>0&&(h=I.preserveOutputs(),d.current.clear());const v=async(i,C,F=0)=>{if(d.current.add(i.id),F>0&&await new Promise(x=>setTimeout(x,F)),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!0,hasMore:!1,totalCount:0}),k}),!i.sessionId){C&&C.length>0&&I.mergeOutputsWithHistory(i.id,[],C),p(x=>{const k=new Map(x);return k.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),k});return}try{const k=await(await _e(ye(`/api/agents/${i.id}/history?limit=${Ee}&offset=0`))).json(),P=k.messages||[],W=P.length>0?Math.max(...P.map(w=>w.timestamp?new Date(w.timestamp).getTime():0)):0,Y=new Set(P.map(w=>w.uuid).filter(w=>!!w)),V=new Map;for(const w of P){if(w.type!=="user"&&w.type!=="assistant")continue;const c=$e(w.type,w.content),L=w.timestamp?new Date(w.timestamp).getTime():0,K=V.get(c)??0;L>K&&V.set(c,L)}const G=I.getOutputs(i.id),U=(C&&C.length>0?[...C,...G]:G).filter(w=>it(w,Y,V,W));I.clearOutputs(i.id);for(const w of U)I.addOutput(i.id,w);p(w=>{const c=new Map(w);return c.set(i.id,{agentId:i.id,messages:P,loading:!1,hasMore:k.hasMore||!1,totalCount:k.totalCount||0}),c})}catch(x){if(console.error(`Failed to load history for ${i.name}:`,x),C&&C.length>0){I.clearOutputs(i.id);for(const k of C)I.addOutput(i.id,k)}p(k=>{const P=new Map(k);return P.set(i.id,{agentId:i.id,messages:[],loading:!1,hasMore:!1,totalCount:0}),P})}},u=l>0?500:0,D=Array.from(a.values());for(const i of D)if(!d.current.has(i.id)){const C=h==null?void 0:h.get(i.id);v(i,C,u)}},[s,M,A,l]);const R=t.useRef(a),N=t.useRef(f);R.current=a,N.current=f;const b=t.useCallback(async j=>{const h=R.current.get(j),v=N.current.get(j);if(!(h!=null&&h.sessionId)||!v||!v.hasMore)return;const u=v.messages.length;try{const i=await(await fetch(ye(`/api/agents/${j}/history?limit=${Ee}&offset=${u}`))).json();i.messages&&i.messages.length>0&&p(C=>{const F=new Map(C),x=C.get(j);return x&&F.set(j,{...x,messages:[...i.messages,...x.messages],hasMore:i.hasMore||!1}),F})}catch(D){console.error(`Failed to load more history for agent ${j}:`,D)}},[]),E=t.useCallback(j=>{d.current.delete(j),p(h=>{const v=new Map(h),u=h.get(j);return u&&v.set(j,{...u,messages:[],hasMore:!1,totalCount:0,loading:!1}),v})},[]);return{histories:f,loadMoreHistory:b,clearAgentHistory:E}}function ut({command:s,onCommandChange:a,useTextarea:l,forceTextarea:f,onForceTextarea:p,onSend:d,canSend:M,attachedFiles:A,onAddFile:R,onRemoveFile:N,uploadFile:b,onAddPastedText:E,placeholder:j="Message...",className:h="",compact:v=!1,inputRef:u}){const D=t.useRef(null),i=t.useRef(null),C=t.useRef(l);t.useEffect(()=>{if(l&&!C.current&&i.current){const c=i.current;c.focus(),c.selectionStart=c.selectionEnd=c.value.length}C.current=l},[l]),t.useEffect(()=>{const c=i.current;if(!c||!l)return;c.style.height="auto";const L=v?120:180,K=Math.min(c.scrollHeight,L);c.style.height=`${K}px`},[s,l,v]);const F=t.useCallback(async c=>{const L=c.clipboardData.items;for(const _ of L)if(_.type.startsWith("image/")){c.preventDefault();const $=_.getAsFile();if($){const H=await b($);H&&R(H)}return}const K=c.clipboardData.files;if(K.length>0){c.preventDefault();for(const _ of K){const $=await b(_);$&&R($)}return}const B=c.clipboardData.getData("text"),te=(B.match(/\n/g)||[]).length+1;if(te>5){c.preventDefault();const $=`[Pasted text #${E(B)} +${te} lines]`,H=c.target,se=H.selectionStart||0,ae=H.selectionEnd||0,ne=s.slice(0,se)+$+s.slice(ae);a(ne),l||p(!0)}},[s,a,l,p,b,R,E]),x=t.useCallback(async c=>{const L=c.target.files;if(L){for(const K of L){const B=await b(K);B&&R(B)}D.current&&(D.current.value="")}},[b,R]),k=t.useCallback(c=>{if(c.key==="Enter"&&c.shiftKey){l||(c.preventDefault(),p(!0));return}c.key==="Enter"&&(c.preventDefault(),d())},[l,p,d]),P=t.useCallback(c=>{},[]),W=t.useCallback(c=>{c.button===1&&(c.preventDefault(),c.stopPropagation())},[]),Y=t.useCallback(c=>{i.current=c,u==null||u(c)},[u]),V=v?"agent-panel-input":"guake-input",G=v?"agent-panel-input-container":"guake-input-container",X=v?"agent-panel-attach-btn":"guake-attach-btn",U=v?"agent-panel-send-btn":"",w=l?v?"agent-panel-input-expanded":"guake-input-expanded":"";return e.jsxs(e.Fragment,{children:[A.length>0&&e.jsx("div",{className:v?"agent-panel-attachments":"guake-attachments",children:A.map(c=>e.jsxs("div",{className:`${v?"agent-panel-attachment":"guake-attachment"} ${c.isImage?"is-image":""}`,children:[e.jsx("span",{className:v?"agent-panel-attachment-icon":"guake-attachment-icon",children:e.jsx(z,{name:c.isImage?"file":"paperclip",size:12})}),e.jsx("span",{className:v?"agent-panel-attachment-name":"guake-attachment-name",title:c.path,children:c.name}),!v&&e.jsxs("span",{className:"guake-attachment-size",children:["(",Math.round(c.size/1024),"KB)"]}),e.jsx("button",{className:v?"agent-panel-attachment-remove":"guake-attachment-remove",onClick:()=>N(c.id),title:"Remove",children:"×"})]},c.id))}),e.jsxs("div",{className:`${V} ${w} ${h}`,children:[e.jsx("input",{ref:D,type:"file",multiple:!0,onChange:x,style:{display:"none"},accept:"*"}),e.jsxs("div",{className:G,onAuxClick:W,children:[e.jsx("button",{className:X,onClick:()=>{var c;return(c=D.current)==null?void 0:c.click()},title:"Attach file (or paste image)",children:e.jsx(z,{name:"paperclip",size:14})}),l?e.jsx("textarea",{ref:Y,placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:P}):e.jsx("input",{ref:u,type:"text",placeholder:j,value:s,onChange:c=>a(c.target.value),onKeyDown:k,onPaste:F,onMouseDown:P}),e.jsx("button",{className:U,onClick:d,disabled:!M,title:"Send",children:e.jsx(z,{name:"send",size:14})})]})]})]})}function mt(s){const a=Math.floor(s/1e3),l=Math.floor(a/60),f=a%60;return`${l}:${f.toString().padStart(2,"0")}`}const ft=t.memo(function({agentId:a,isWorking:l,timestamp:f}){const{t:p}=fe(["terminal"]),[d,M]=t.useState(0);return t.useEffect(()=>{if(!l||!f){M(0);return}M(Date.now()-f);const A=setInterval(()=>{M(Date.now()-f)},1e3);return()=>clearInterval(A)},[l,f]),l?e.jsxs("div",{className:"guake-stop-bar",children:[e.jsx("span",{className:"guake-elapsed-timer",children:mt(d)}),e.jsxs("button",{className:"guake-stop-btn",onClick:()=>I.stopAgent(a),title:p("terminal:input.stopOperation"),children:[e.jsx("span",{className:"stop-icon",children:e.jsx(z,{name:"stop",size:12,weight:"fill"})}),e.jsx("span",{className:"stop-label",children:p("terminal:input.stop")})]})]}):null});function pt({agent:s,history:a,outputs:l,isExpanded:f,isFocused:p,advancedView:d,onExpand:M,onFocus:A,inputRef:R,onLoadMore:N,onClearHistory:b}){const{t:E}=fe(["terminal","common"]),j=ze(s.id),h=t.useRef(null),[v,u]=t.useState(!1),D=t.useRef(0),i=t.useRef(!1),[C,F]=t.useState(!0),[x,k]=t.useState(!1),[P,W]=t.useState(null),[Y,V]=t.useState(null),[G,X]=t.useState(null);Te(`commander-image-modal-${s.id}`,P!==null,()=>W(null));const{command:U,setCommand:w,forceTextarea:c,setForceTextarea:L,useTextarea:K,setPastedTexts:B,incrementPastedCount:te,resetPastedCount:_,attachedFiles:$,setAttachedFiles:H,removeAttachedFile:se,uploadFile:ae,expandPastedTexts:ne}=Be({selectedAgentId:s.id}),le=U.trim().length>0||$.length>0,n=Ue({outputs:l,viewMode:d?"advanced":"simple"}),o=t.useMemo(()=>{const S=Ke(s);return{usedPercent:S.usedPercent,freePercent:S.freePercent,hasData:!!s.contextStats,totalTokens:S.totalTokens,contextWindow:S.contextWindow}},[s.contextStats,s.contextUsed,s.contextLimit]),g=t.useCallback(()=>{!v&&(a!=null&&a.hasMore)&&N&&(u(!0),D.current=h.current?h.current.scrollHeight-h.current.scrollTop:0,N())},[v,a==null?void 0:a.hasMore,N]);t.useEffect(()=>{v&&a&&!a.loading&&u(!1)},[a,v]);const m=t.useCallback(()=>{i.current=!0,F(!1)},[]),T=t.useRef(f),Z=t.useRef(p);t.useEffect(()=>{(f&&!T.current||p&&!Z.current)&&(i.current=!1,F(!0),k(!0)),T.current=f,Z.current=p},[f,p]);const ee=t.useRef(a==null?void 0:a.loading);t.useEffect(()=>{ee.current&&!(a!=null&&a.loading)&&(i.current=!1,F(!0),k(!0)),ee.current=a==null?void 0:a.loading},[a==null?void 0:a.loading]),t.useEffect(()=>{if(!x)return;const S=h.current;if(!S)return;const y=performance.now();let O=0,ue=-1,ke;const Re=()=>{const{scrollTop:Fe,scrollHeight:Se,clientHeight:Le}=S,He=Se-Fe-Le<=2;if(Math.abs(Se-ue)<=1&&He?O+=1:O=0,ue=Se,O>=3){k(!1);return}if(performance.now()-y>5e3){k(!1);return}ke=requestAnimationFrame(Re)};return ke=requestAnimationFrame(Re),()=>cancelAnimationFrame(ke)},[x]),t.useEffect(()=>{i.current||F(!0)},[n.length]);const q=t.useCallback(()=>!1,[]),ie=t.useCallback(S=>{const y=te();return B(O=>new Map(O).set(y,S)),y},[te,B]),he=t.useCallback(S=>{H(y=>[...y,S])},[H]),xe=t.useCallback(()=>{if(!le)return;if(U.trim()==="/clear"&&$.length===0){I.clearContext(s.id),b(),w(""),L(!1),B(new Map),H([]),_();return}let S=ne(U.trim());if($.length>0){const y=$.map(O=>O.isImage?`[Image: ${O.path}]`:`[File: ${O.path}]`).join(`
3
+ `);S=S?`${S}
4
4
 
5
- ${y}`:y}I.sendCommand(s.id,N),w(""),L(!1),B(new Map),O([]),_()},[s.id,U,le,$,ne,b,_,w,L,B,O]),ge=t.useCallback((N,y)=>{K({url:N,name:y})},[]),ve=t.useCallback((N,y)=>{const H=Ke(N,s.cwd),ue=H.line?{...y||{},targetLine:H.line}:y;I.setFileViewerPath(H.path,ue,s.cwd)},[s.cwd]),je=t.useCallback((N,y)=>{V({command:N,output:y,isLive:y==="Running..."})},[]),we=t.useCallback(N=>{Q(N)},[]),Ce=t.useCallback(()=>{k(!1),i.current=!0,F(!1)},[]),be=t.useCallback(()=>K(null),[]),r=t.useCallback(()=>V(null),[]),J=t.useCallback(()=>Q(null),[]),de=t.useCallback(N=>{N.stopPropagation(),M()},[M]),ce=ot[s.status]||"#888888",re=(a==null?void 0:a.messages)||[];return e.jsxs("div",{className:`agent-panel ${s.status==="working"?"working":""} ${f?"expanded":""} ${p?"focused":""}`,onClick:p?void 0:A,children:[e.jsxs("div",{className:"agent-panel-header",onClick:p?A:void 0,children:[e.jsxs("div",{className:"agent-panel-info",children:[e.jsx("span",{className:"agent-panel-status",style:{background:ce},title:s.status}),e.jsxs("span",{className:"agent-panel-name",children:[(s.isBoss||s.class==="boss")&&e.jsx("span",{className:"agent-panel-boss-crown",children:e.jsx(z,{name:"crown",size:14})}),s.name]}),e.jsx("span",{className:`agent-panel-status-label ${s.status}`,children:s.status}),e.jsx("span",{className:"agent-panel-class",children:s.class}),e.jsx("span",{className:`agent-panel-provider ${s.provider==="codex"?"codex":s.provider==="opencode"?"opencode":"claude"}`,children:s.provider||"claude"}),e.jsxs("span",{className:"agent-panel-id",title:`ID: ${s.id}`,children:["[",s.id.substring(0,4),"]"]}),s.taskLabel?e.jsxs("div",{className:"agent-panel-task agent-panel-task-label",title:s.taskLabel,children:[e.jsx(z,{name:"task",size:12})," ",s.taskLabel]}):s.currentTask?e.jsxs("div",{className:"agent-panel-task",title:s.currentTask,children:[s.currentTask.substring(0,40),"..."]}):null]}),e.jsxs("div",{className:"agent-panel-context",title:`Context: ${Math.round(o.usedPercent)}% used (${De(o.totalTokens)} / ${De(o.contextWindow)})`,children:[e.jsx("div",{className:"agent-panel-context-bar",style:{background:o.freePercent<20?"#ff4a4a":o.freePercent<50?"#ff9e4a":"#4aff9e",width:`${o.freePercent}%`}}),e.jsxs("span",{className:"agent-panel-context-text",children:[Math.round(o.freePercent),"%"]})]}),e.jsx("div",{className:"agent-panel-actions",children:e.jsx("button",{className:"agent-panel-expand",onClick:de,title:E(f?"commander.collapsePanel":"commander.expandPanel"),children:f?e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("polyline",{points:"4 14 10 14 10 20"}),e.jsx("polyline",{points:"20 10 14 10 14 4"}),e.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("polyline",{points:"9 21 3 21 3 15"}),e.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})})]}),e.jsx("div",{className:"agent-panel-content",ref:h,children:a!=null&&a.loading?e.jsx("div",{className:"agent-panel-loading",children:E("common:status.loading")}):e.jsx(e.Fragment,{children:!re.length&&!n.length?e.jsxs("div",{className:"agent-panel-empty",children:[E("commander.noMessages"),!s.sessionId&&e.jsx("div",{style:{fontSize:"10px",color:"#666"},children:E("commander.noSessionId")})]}):e.jsx(Ve,{historyMessages:re,liveOutputs:n,agentId:s.id,viewMode:d?"advanced":"simple",selectedMessageIndex:null,isMessageSelected:q,onImageClick:ge,onFileClick:ve,onBashClick:je,onViewMarkdown:we,scrollContainerRef:h,onScrollTopReached:g,isLoadingMore:v,hasMore:a==null?void 0:a.hasMore,shouldAutoScroll:C,onUserScroll:m,pinToBottom:x,onPinCancel:Ce,isLoadingHistory:a==null?void 0:a.loading})})}),e.jsxs("div",{className:`guake-input-wrapper ${s.status==="working"?"has-stop-btn is-working":""}`,children:[e.jsx(ft,{agentId:s.id,isWorking:s.status==="working",timestamp:j==null?void 0:j.timestamp}),e.jsx(ut,{command:U,onCommandChange:w,useTextarea:W,forceTextarea:c,onForceTextarea:L,onSend:xe,canSend:le,attachedFiles:$,onAddFile:he,onRemoveFile:se,uploadFile:ae,onAddPastedText:ie,placeholder:E("commander.command",{name:s.name}),compact:!1,inputRef:R})]}),P&&e.jsx(Ge,{url:P.url,name:P.name,onClose:be}),Y&&e.jsx(qe,{state:Y,onClose:r}),e.jsx(Ye,{agent:s,content:G,onClose:J})]})}function ht({currentArea:s,onClose:a}){const{t:l}=fe(["terminal","common"]),[f,p]=t.useState(()=>{const u=new Set(Array.from(I.getState().agents.values()).map(D=>D.name));return Je.find(D=>!u.has(D))||`Agent-${Date.now().toString(36)}`}),[d,M]=t.useState(()=>Me(oe.LAST_CWD)),[A,R]=t.useState("scout"),[S,b]=t.useState("claude"),[E,j]=t.useState(!1),h=()=>{if(!f.trim()||!d.trim())return;j(!0),Ie(oe.LAST_CWD,d);let u;s&&(u={x:s.center.x,z:s.center.z}),I.spawnAgent(f.trim(),A,d.trim(),u,void 0,void 0,void 0,void 0,S),setTimeout(()=>{a()},500)},v=u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),h()),u.key==="Escape"&&a()};return e.jsx("div",{className:"commander-spawn-overlay",onClick:a,children:e.jsxs("div",{className:"commander-spawn-form",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"commander-spawn-header",children:[e.jsx("h3",{children:l("spawn.addNewAgent")}),s&&e.jsxs("span",{className:"commander-spawn-area",children:[e.jsx("span",{className:"commander-spawn-area-dot",style:{background:s.color}}),s.name]})]}),e.jsxs("div",{className:"commander-spawn-body",children:[e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.name")}),e.jsx("input",{type:"text",value:f,onChange:u=>p(u.target.value),onKeyDown:v,autoFocus:!0})]}),e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.workingDirectory")}),e.jsx(Xe,{value:d,onChange:M,onSubmit:h,placeholder:l("spawn.workingDirPlaceholder"),directoriesOnly:!0})]}),e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.class")}),e.jsx("div",{className:"commander-spawn-classes",children:Qe.map(u=>e.jsxs("button",{className:`commander-spawn-class ${A===u.id?"selected":""}`,onClick:()=>R(u.id),children:[e.jsx(Ze,{classId:u.id,size:18,className:"commander-spawn-class-icon"}),e.jsx("span",{children:u.name})]},u.id))})]}),e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.runtime")}),e.jsxs("div",{className:"commander-spawn-classes",children:[e.jsxs("button",{className:`commander-spawn-class ${S==="claude"?"selected":""}`,onClick:()=>b("claude"),children:[e.jsx("span",{className:"commander-spawn-class-icon",children:e.jsx(z,{name:"brain",size:14})}),e.jsx("span",{children:"Claude"})]}),e.jsxs("button",{className:`commander-spawn-class ${S==="codex"?"selected":""}`,onClick:()=>b("codex"),children:[e.jsx("span",{className:"commander-spawn-class-icon",children:e.jsx(z,{name:"gear",size:14})}),e.jsx("span",{children:"Codex"})]}),e.jsxs("button",{className:`commander-spawn-class ${S==="opencode"?"selected":""}`,onClick:()=>b("opencode"),children:[e.jsx("span",{className:"commander-spawn-class-icon",children:e.jsx(z,{name:"status-pending",size:12,weight:"fill",color:"#4ade80"})}),e.jsx("span",{children:"OpenCode"})]})]})]})]}),e.jsxs("div",{className:"commander-spawn-footer",children:[e.jsx("button",{className:"commander-spawn-cancel",onClick:a,children:l("common:buttons.cancel")}),e.jsx("button",{className:"commander-spawn-submit",onClick:h,disabled:!f.trim()||!d.trim()||E,children:l(E?"common:buttons.deploying":"common:buttons.deploy")})]})]})})}const Pe=t.memo(function({agent:a,history:l,isExpanded:f,isFocused:p,advancedView:d,index:M,onExpand:A,onCollapse:R,onFocus:S,onInputRef:b,onLoadMore:E,onClearHistory:j}){const h=nt(a.id),v=t.useCallback(()=>{f?R():A(a.id)},[a.id,f,A,R]),u=t.useCallback(()=>{S(p?-1:M)},[M,p,S]),D=t.useCallback(F=>{b(a.id,F)},[a.id,b]),i=t.useCallback(()=>{E(a.id)},[a.id,E]),C=t.useCallback(()=>{j(a.id)},[a.id,j]);return e.jsx(pt,{agent:a,history:l,outputs:h,isExpanded:f,isFocused:p,advancedView:d,onExpand:v,onFocus:u,inputRef:D,onLoadMore:i,onClearHistory:C})});function Ct({isOpen:s,onClose:a}){const{t:l}=fe(["terminal","common"]),f=et(),p=tt(),[d,M]=t.useState(()=>Me(oe.COMMANDER_TAB,"all")),[A,R]=t.useState(0),[S,b]=t.useState(null),E=t.useRef(null),[j,h]=t.useState(0),[v,u]=t.useState(!1),[D,i]=t.useState(null),[C,F]=t.useState(!1),[x,k]=t.useState(()=>{try{const n=Me(oe.COMMANDER_FILTERS,"");if(n)return{...Se,...JSON.parse(n)}}catch{}return Se}),P=t.useRef(new Map),K=t.useRef([]),Y=t.useRef(0),V=t.useRef([]),G=t.useRef(d),{histories:Q,loadMoreHistory:U,clearAgentHistory:w}=dt({isOpen:s,agents:f});t.useEffect(()=>{s||(b(null),h(0),u(!1))},[s]);const c=t.useMemo(()=>{const n=Array.from(p.values()).sort((g,m)=>g.name.localeCompare(m.name)),o=[{id:"all",name:l("common:labels.all")}];for(const g of n)o.push({id:g.id,name:g.name,color:g.color});return o.push({id:"unassigned",name:l("commander.unassigned")}),o},[p]),L=t.useMemo(()=>d==="all"||d==="unassigned"?null:p.get(d)||null,[d,p]),W=t.useMemo(()=>{const n=new Map;n.set("all",f.size);let o=0;for(const g of f.values()){const m=I.getAreaForAgent(g.id);m?n.set(m.id,(n.get(m.id)||0)+1):o++}return n.set("unassigned",o),n},[f]),B=x.status!=="all"||x.activity!=="all"||x.sort!=="activity",te=(x.status!=="all"?1:0)+(x.activity!=="all"?1:0)+(x.sort!=="activity"?1:0),_=t.useMemo(()=>{const n=m=>m.isBoss===!0||m.class==="boss",o=Date.now();let g=Array.from(f.values());if(d==="unassigned"?g=g.filter(m=>!I.getAreaForAgent(m.id)):d!=="all"&&(g=g.filter(m=>{const T=I.getAreaForAgent(m.id);return(T==null?void 0:T.id)===d})),x.status!=="all"&&(g=g.filter(m=>{switch(x.status){case"working":return m.status==="working";case"idle":return m.status==="idle";case"error":return m.status==="error"||m.status==="waiting"||m.status==="waiting_permission";case"offline":return m.status==="offline"||m.status==="orphaned";default:return!0}})),x.activity!=="all"){const m=lt[x.activity];g=g.filter(T=>o-(T.lastActivity||0)<m)}return g.sort((m,T)=>{var Z,ee;if(n(m)&&!n(T))return-1;if(!n(m)&&n(T))return 1;switch(x.sort){case"activity":return(T.lastActivity||0)-(m.lastActivity||0);case"name":return m.name.localeCompare(T.name);case"created":return(m.createdAt||0)-(T.createdAt||0);case"context":{const q=((Z=m.contextStats)==null?void 0:Z.usedPercent)??(m.contextUsed||0)/(m.contextLimit||2e5)*100;return(((ee=T.contextStats)==null?void 0:ee.usedPercent)??(T.contextUsed||0)/(T.contextLimit||2e5)*100)-q}default:return(T.lastActivity||0)-(m.lastActivity||0)}}),g},[f,d,x]),$=Math.ceil(_.length/Ae),O=t.useMemo(()=>_.slice(A*Ae,(A+1)*Ae),[_,A]);K.current=O,E.current=S,Y.current=j,V.current=c,G.current=d,Te("commander-expanded",S!==null,()=>b(null));const se=st();t.useEffect(()=>{s&&se&&(b(se),I.clearCommanderExpandRequest())},[s,se]);const ae=t.useCallback(()=>b(null),[]),ne=t.useCallback(n=>b(n),[]),le=t.useCallback(n=>h(n),[]),pe=t.useCallback((n,o)=>{o?P.current.set(n,o):P.current.delete(n)},[]);return t.useEffect(()=>{R(0),Ie(oe.COMMANDER_TAB,d)},[d]),t.useEffect(()=>{Ie(oe.COMMANDER_FILTERS,JSON.stringify(x)),R(0)},[x]),t.useEffect(()=>{var o;if(!s||window.matchMedia("(pointer: coarse)").matches)return;const n=S||((o=K.current[j])==null?void 0:o.id);if(n){const g=P.current.get(n);g&&document.activeElement!==g&&setTimeout(()=>g.focus(),50)}},[s,j,S]),t.useEffect(()=>{if(!s)return;const n=o=>{const g=I.getShortcuts(),m=o.target,T=m.tagName==="INPUT"||m.tagName==="TEXTAREA",Z=K.current,ee=Z.length-1,q=E.current,ie=g.find(r=>r.id==="commander-close");if(X(o,ie)){const{fileViewerPath:r,contextModalAgentId:J}=I.getState();if(r||J)return;o.preventDefault(),o.stopImmediatePropagation(),q?b(null):a();return}const he=g.find(r=>r.id==="commander-vim-left");if(X(o,he)&&!q){o.preventDefault(),h(r=>r>0?r-1:r);return}const xe=g.find(r=>r.id==="commander-vim-right");if(X(o,xe)&&!q){o.preventDefault(),h(r=>r<ee?r+1:r);return}const ge=g.find(r=>r.id==="commander-vim-up");if(X(o,ge)&&!q){o.preventDefault(),h(r=>r>=me?r-me:r);return}const ve=g.find(r=>r.id==="commander-vim-down");if(X(o,ve)&&!q){o.preventDefault(),h(r=>r+me<=ee?r+me:r);return}const je=g.find(r=>r.id==="commander-expand");if(X(o,je)){if(o.preventDefault(),q)b(null);else{const r=Z[Y.current];r&&b(r.id)}return}const we=g.find(r=>r.id==="commander-new-agent");if(X(o,we)){o.preventDefault(),u(!0);return}const Ce=g.find(r=>r.id==="commander-next-tab"),be=g.find(r=>r.id==="commander-prev-tab");if(!T){const r=V.current;if(X(o,Ce)){const J=I.getState().latestNotificationAgentId;if(J){if(o.preventDefault(),o.stopPropagation(),!I.getState().agents.get(J)){I.setLatestNotificationAgentId(null);return}const y=I.getAreaForAgent(J);y&&r.some(H=>H.id===y.id)?M(y.id):M("unassigned"),b(J),h(0),R(0),I.setLatestNotificationAgentId(null);return}o.preventDefault(),o.stopPropagation();const ce=(r.findIndex(re=>re.id===G.current)+1)%r.length;M(r[ce].id),h(0);return}if(X(o,be)){o.preventDefault(),o.stopPropagation();const de=(r.findIndex(ce=>ce.id===G.current)-1+r.length)%r.length;M(r[de].id),h(0);return}}};return document.addEventListener("keydown",n,!0),()=>document.removeEventListener("keydown",n,!0)},[s,a]),s?e.jsx("div",{className:"commander-overlay",onClick:a,children:e.jsxs("div",{className:"commander-view",onClick:n=>n.stopPropagation(),children:[e.jsxs("div",{className:"commander-header",children:[e.jsxs("div",{className:"commander-title-section",children:[e.jsx("h2",{className:"commander-title",children:l("commander.title")}),e.jsx("span",{className:"commander-shortcuts",children:l("commander.shortcuts")})]}),e.jsxs("div",{className:"commander-controls",children:[e.jsx("button",{className:`commander-view-toggle ${C?"active":""}`,onClick:()=>F(!C),title:l(C?"commander.simple":"commander.advanced"),children:C?e.jsxs(e.Fragment,{children:[e.jsx(z,{name:"target",size:12})," ",l("commander.advanced")]}):e.jsxs(e.Fragment,{children:[e.jsx(z,{name:"status-pending",size:12})," ",l("commander.simple")]})}),e.jsx("button",{className:"commander-add-btn",onClick:()=>u(!0),title:l("commander.addAgent"),children:l("commander.addAgent")}),e.jsx("button",{className:"commander-close",onClick:a,children:l("commander.close")})]})]}),e.jsx("div",{className:"commander-tabs",children:c.map(n=>{const o=n.id!=="all"&&n.id!=="unassigned"?p.get(n.id):null,g=o&&o.directories&&o.directories.length>0;return e.jsxs("button",{className:`commander-tab ${d===n.id?"active":""}`,onClick:()=>{M(n.id),h(0)},style:n.color?{borderBottomColor:d===n.id?n.color:"transparent"}:void 0,children:[n.color&&e.jsx("span",{className:"commander-tab-dot",style:{background:n.color}}),e.jsx("span",{children:n.name}),e.jsx("span",{className:"commander-tab-count",children:W.get(n.id)||0}),g&&e.jsx("span",{className:"commander-tab-folder",onClick:m=>{m.stopPropagation(),i(n.id)},title:l("commander.openFileExplorer"),children:e.jsx(z,{name:"folder",size:12})})]},n.id)})}),e.jsxs("div",{className:"commander-filters",children:[e.jsxs("div",{className:"commander-filter-group",children:[e.jsx("span",{className:"commander-filter-label",children:l("commander.filters.status")}),["all","working","idle","error","offline"].map(n=>e.jsx("button",{className:`commander-filter-btn ${x.status===n?"active":""}`,onClick:()=>k(o=>({...o,status:n})),children:n==="all"?l("commander.filters.all"):n==="error"?l("commander.filters.needsAttn"):n.charAt(0).toUpperCase()+n.slice(1)},n))]}),e.jsxs("div",{className:"commander-filter-group",children:[e.jsx("span",{className:"commander-filter-label",children:l("commander.filters.active")}),["all","1h","6h","24h"].map(n=>e.jsx("button",{className:`commander-filter-btn ${x.activity===n?"active":""}`,onClick:()=>k(o=>({...o,activity:n})),children:n==="all"?l("commander.filters.any"):`< ${n}`},n))]}),e.jsxs("div",{className:"commander-filter-group",children:[e.jsx("span",{className:"commander-filter-label",children:l("commander.filters.sort")}),["activity","name","created","context"].map(n=>e.jsx("button",{className:`commander-filter-btn ${x.sort===n?"active":""}`,onClick:()=>k(o=>({...o,sort:n})),children:n==="activity"?l("commander.filters.recent"):n==="context"?l("commander.filters.context"):n.charAt(0).toUpperCase()+n.slice(1)},n))]}),B&&e.jsx("button",{className:"commander-filter-clear",onClick:()=>k(Se),title:l("commander.clearFilters"),children:l("commander.filters.clearFilters",{count:te})})]}),$>1&&e.jsxs("div",{className:"commander-pagination",children:[e.jsxs("button",{className:"commander-page-btn",onClick:()=>R(n=>Math.max(0,n-1)),disabled:A===0,children:[e.jsx(z,{name:"caret-left",size:12})," ",l("commander.prev")]}),e.jsx("span",{className:"commander-page-info",children:l("commander.page",{current:A+1,total:$,count:_.length})}),e.jsxs("button",{className:"commander-page-btn",onClick:()=>R(n=>Math.min($-1,n+1)),disabled:A===$-1,children:[l("commander.next")," ",e.jsx(z,{name:"caret-right",size:12})]})]}),e.jsx("div",{className:`commander-grid ${S?"has-expanded":""}`,"data-agent-count":S?1:O.length,children:O.length===0?e.jsx("div",{className:"commander-empty",children:l(d==="all"?"commander.noAgentsAll":d==="unassigned"?"commander.noAgentsUnassigned":"commander.noAgentsArea")}):S?(()=>{const n=f.get(S);return n?e.jsx(Pe,{agent:n,history:Q.get(n.id),isExpanded:!0,isFocused:!0,advancedView:C,index:0,onExpand:ne,onCollapse:ae,onFocus:le,onInputRef:pe,onLoadMore:U,onClearHistory:w},n.id):null})():O.map((n,o)=>e.jsx(Pe,{agent:n,history:Q.get(n.id),isExpanded:!1,isFocused:o===j,advancedView:C,index:o,onExpand:ne,onCollapse:ae,onFocus:le,onInputRef:pe,onLoadMore:U,onClearHistory:w},n.id))}),v&&e.jsx(ht,{currentArea:L,onClose:()=>u(!1)}),D&&e.jsx(at,{isOpen:!0,areaId:D,onClose:()=>i(null),onChangeArea:n=>i(n)})]})}):null}export{Ct as CommanderView};
5
+ ${y}`:y}I.sendCommand(s.id,S),w(""),L(!1),B(new Map),H([]),_()},[s.id,U,le,$,ne,b,_,w,L,B,H]),ge=t.useCallback((S,y)=>{W({url:S,name:y})},[]),ve=t.useCallback((S,y)=>{const O=We(S,s.cwd),ue=O.line?{...y||{},targetLine:O.line}:y;I.setFileViewerPath(O.path,ue,s.cwd)},[s.cwd]),je=t.useCallback((S,y)=>{V({command:S,output:y,isLive:y==="Running..."})},[]),we=t.useCallback(S=>{X(S)},[]),Ce=t.useCallback(()=>{k(!1),i.current=!0,F(!1)},[]),be=t.useCallback(()=>W(null),[]),r=t.useCallback(()=>V(null),[]),J=t.useCallback(()=>X(null),[]),de=t.useCallback(S=>{S.stopPropagation(),M()},[M]),ce=ot[s.status]||"#888888",re=(a==null?void 0:a.messages)||[];return e.jsxs("div",{className:`agent-panel ${s.status==="working"?"working":""} ${f?"expanded":""} ${p?"focused":""}`,onClick:p?void 0:A,children:[e.jsxs("div",{className:"agent-panel-header",onClick:p?A:void 0,children:[e.jsxs("div",{className:"agent-panel-info",children:[e.jsx("span",{className:"agent-panel-status",style:{background:ce},title:s.status}),e.jsxs("span",{className:"agent-panel-name",children:[(s.isBoss||s.class==="boss")&&e.jsx("span",{className:"agent-panel-boss-crown",children:e.jsx(z,{name:"crown",size:14})}),s.name]}),e.jsx("span",{className:`agent-panel-status-label ${s.status}`,children:s.status}),e.jsx("span",{className:"agent-panel-class",children:s.class}),e.jsx("span",{className:`agent-panel-provider ${s.provider==="codex"?"codex":s.provider==="opencode"?"opencode":"claude"}`,children:s.provider||"claude"}),e.jsxs("span",{className:"agent-panel-id",title:`ID: ${s.id}`,children:["[",s.id.substring(0,4),"]"]}),s.taskLabel?e.jsxs("div",{className:"agent-panel-task agent-panel-task-label",title:s.taskLabel,children:[e.jsx(z,{name:"task",size:12})," ",s.taskLabel]}):s.currentTask?e.jsxs("div",{className:"agent-panel-task",title:s.currentTask,children:[s.currentTask.substring(0,40),"..."]}):null]}),e.jsxs("div",{className:"agent-panel-context",title:`Context: ${Math.round(o.usedPercent)}% used (${De(o.totalTokens)} / ${De(o.contextWindow)})`,children:[e.jsx("div",{className:"agent-panel-context-bar",style:{background:o.freePercent<20?"#ff4a4a":o.freePercent<50?"#ff9e4a":"#4aff9e",width:`${o.freePercent}%`}}),e.jsxs("span",{className:"agent-panel-context-text",children:[Math.round(o.freePercent),"%"]})]}),e.jsx("div",{className:"agent-panel-actions",children:e.jsx("button",{className:"agent-panel-expand",onClick:de,title:E(f?"commander.collapsePanel":"commander.expandPanel"),children:f?e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("polyline",{points:"4 14 10 14 10 20"}),e.jsx("polyline",{points:"20 10 14 10 14 4"}),e.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("polyline",{points:"9 21 3 21 3 15"}),e.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})})]}),e.jsx("div",{className:"agent-panel-content",ref:h,children:a!=null&&a.loading?e.jsx("div",{className:"agent-panel-loading",children:E("common:status.loading")}):e.jsx(e.Fragment,{children:!re.length&&!n.length?e.jsxs("div",{className:"agent-panel-empty",children:[E("commander.noMessages"),!s.sessionId&&e.jsx("div",{style:{fontSize:"10px",color:"#666"},children:E("commander.noSessionId")})]}):e.jsx(Ve,{historyMessages:re,liveOutputs:n,agentId:s.id,viewMode:d?"advanced":"simple",selectedMessageIndex:null,isMessageSelected:q,onImageClick:ge,onFileClick:ve,onBashClick:je,onViewMarkdown:we,scrollContainerRef:h,onScrollTopReached:g,isLoadingMore:v,hasMore:a==null?void 0:a.hasMore,shouldAutoScroll:C,onUserScroll:m,pinToBottom:x,onPinCancel:Ce,isLoadingHistory:a==null?void 0:a.loading})})}),e.jsxs("div",{className:`guake-input-wrapper ${s.status==="working"?"has-stop-btn is-working":""}`,children:[e.jsx(ft,{agentId:s.id,isWorking:s.status==="working",timestamp:j==null?void 0:j.timestamp}),e.jsx(ut,{command:U,onCommandChange:w,useTextarea:K,forceTextarea:c,onForceTextarea:L,onSend:xe,canSend:le,attachedFiles:$,onAddFile:he,onRemoveFile:se,uploadFile:ae,onAddPastedText:ie,placeholder:E("commander.command",{name:s.name}),compact:!1,inputRef:R})]}),P&&e.jsx(Ge,{url:P.url,name:P.name,onClose:be}),Y&&e.jsx(qe,{state:Y,onClose:r}),e.jsx(Ye,{agent:s,content:G,onClose:J})]})}function ht({currentArea:s,onClose:a}){const{t:l}=fe(["terminal","common"]),[f,p]=t.useState(()=>{const u=new Set(Array.from(I.getState().agents.values()).map(D=>D.name));return Je.find(D=>!u.has(D))||`Agent-${Date.now().toString(36)}`}),[d,M]=t.useState(()=>Me(oe.LAST_CWD)),[A,R]=t.useState("scout"),[N,b]=t.useState("claude"),[E,j]=t.useState(!1),h=()=>{if(!f.trim()||!d.trim())return;j(!0),Ie(oe.LAST_CWD,d);let u;s&&(u={x:s.center.x,z:s.center.z}),I.spawnAgent(f.trim(),A,d.trim(),u,void 0,void 0,void 0,void 0,N),setTimeout(()=>{a()},500)},v=u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),h()),u.key==="Escape"&&a()};return e.jsx("div",{className:"commander-spawn-overlay",onClick:a,children:e.jsxs("div",{className:"commander-spawn-form",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"commander-spawn-header",children:[e.jsx("h3",{children:l("spawn.addNewAgent")}),s&&e.jsxs("span",{className:"commander-spawn-area",children:[e.jsx("span",{className:"commander-spawn-area-dot",style:{background:s.color}}),s.name]})]}),e.jsxs("div",{className:"commander-spawn-body",children:[e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.name")}),e.jsx("input",{type:"text",value:f,onChange:u=>p(u.target.value),onKeyDown:v,autoFocus:!0})]}),e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.workingDirectory")}),e.jsx(Qe,{value:d,onChange:M,onSubmit:h,placeholder:l("spawn.workingDirPlaceholder"),directoriesOnly:!0})]}),e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.class")}),e.jsx("div",{className:"commander-spawn-classes",children:Xe.map(u=>e.jsxs("button",{className:`commander-spawn-class ${A===u.id?"selected":""}`,onClick:()=>R(u.id),children:[e.jsx(Ze,{classId:u.id,size:18,className:"commander-spawn-class-icon"}),e.jsx("span",{children:u.name})]},u.id))})]}),e.jsxs("div",{className:"commander-spawn-field",children:[e.jsx("label",{children:l("common:labels.runtime")}),e.jsxs("div",{className:"commander-spawn-classes",children:[e.jsxs("button",{className:`commander-spawn-class ${N==="claude"?"selected":""}`,onClick:()=>b("claude"),children:[e.jsx("span",{className:"commander-spawn-class-icon",children:e.jsx(z,{name:"brain",size:14})}),e.jsx("span",{children:"Claude"})]}),e.jsxs("button",{className:`commander-spawn-class ${N==="codex"?"selected":""}`,onClick:()=>b("codex"),children:[e.jsx("span",{className:"commander-spawn-class-icon",children:e.jsx(z,{name:"gear",size:14})}),e.jsx("span",{children:"Codex"})]}),e.jsxs("button",{className:`commander-spawn-class ${N==="opencode"?"selected":""}`,onClick:()=>b("opencode"),children:[e.jsx("span",{className:"commander-spawn-class-icon",children:e.jsx(z,{name:"status-pending",size:12,weight:"fill",color:"#4ade80"})}),e.jsx("span",{children:"OpenCode"})]})]})]})]}),e.jsxs("div",{className:"commander-spawn-footer",children:[e.jsx("button",{className:"commander-spawn-cancel",onClick:a,children:l("common:buttons.cancel")}),e.jsx("button",{className:"commander-spawn-submit",onClick:h,disabled:!f.trim()||!d.trim()||E,children:l(E?"common:buttons.deploying":"common:buttons.deploy")})]})]})})}const Pe=t.memo(function({agent:a,history:l,isExpanded:f,isFocused:p,advancedView:d,index:M,onExpand:A,onCollapse:R,onFocus:N,onInputRef:b,onLoadMore:E,onClearHistory:j}){const h=nt(a.id),v=t.useCallback(()=>{f?R():A(a.id)},[a.id,f,A,R]),u=t.useCallback(()=>{N(p?-1:M)},[M,p,N]),D=t.useCallback(F=>{b(a.id,F)},[a.id,b]),i=t.useCallback(()=>{E(a.id)},[a.id,E]),C=t.useCallback(()=>{j(a.id)},[a.id,j]);return e.jsx(pt,{agent:a,history:l,outputs:h,isExpanded:f,isFocused:p,advancedView:d,onExpand:v,onFocus:u,inputRef:D,onLoadMore:i,onClearHistory:C})});function Ct({isOpen:s,onClose:a}){const{t:l}=fe(["terminal","common"]),f=et(),p=tt(),[d,M]=t.useState(()=>Me(oe.COMMANDER_TAB,"all")),[A,R]=t.useState(0),[N,b]=t.useState(null),E=t.useRef(null),[j,h]=t.useState(0),[v,u]=t.useState(!1),[D,i]=t.useState(null),[C,F]=t.useState(!1),[x,k]=t.useState(()=>{try{const n=Me(oe.COMMANDER_FILTERS,"");if(n)return{...Ne,...JSON.parse(n)}}catch{}return Ne}),P=t.useRef(new Map),W=t.useRef([]),Y=t.useRef(0),V=t.useRef([]),G=t.useRef(d),{histories:X,loadMoreHistory:U,clearAgentHistory:w}=dt({isOpen:s,agents:f});t.useEffect(()=>{s||(b(null),h(0),u(!1))},[s]);const c=t.useMemo(()=>{const n=Array.from(p.values()).sort((g,m)=>g.name.localeCompare(m.name)),o=[{id:"all",name:l("common:labels.all")}];for(const g of n)o.push({id:g.id,name:g.name,color:g.color});return o.push({id:"unassigned",name:l("commander.unassigned")}),o},[p]),L=t.useMemo(()=>d==="all"||d==="unassigned"?null:p.get(d)||null,[d,p]),K=t.useMemo(()=>{const n=new Map;n.set("all",f.size);let o=0;for(const g of f.values()){const m=I.getAreaForAgent(g.id);m?n.set(m.id,(n.get(m.id)||0)+1):o++}return n.set("unassigned",o),n},[f]),B=x.status!=="all"||x.activity!=="all"||x.sort!=="activity",te=(x.status!=="all"?1:0)+(x.activity!=="all"?1:0)+(x.sort!=="activity"?1:0),_=t.useMemo(()=>{const n=m=>m.isBoss===!0||m.class==="boss",o=Date.now();let g=Array.from(f.values());if(d==="unassigned"?g=g.filter(m=>!I.getAreaForAgent(m.id)):d!=="all"&&(g=g.filter(m=>{const T=I.getAreaForAgent(m.id);return(T==null?void 0:T.id)===d})),x.status!=="all"&&(g=g.filter(m=>{switch(x.status){case"working":return m.status==="working";case"idle":return m.status==="idle";case"error":return m.status==="error"||m.status==="waiting"||m.status==="waiting_permission";case"offline":return m.status==="offline"||m.status==="orphaned";default:return!0}})),x.activity!=="all"){const m=lt[x.activity];g=g.filter(T=>o-(T.lastActivity||0)<m)}return g.sort((m,T)=>{var Z,ee;if(n(m)&&!n(T))return-1;if(!n(m)&&n(T))return 1;switch(x.sort){case"activity":return(T.lastActivity||0)-(m.lastActivity||0);case"name":return m.name.localeCompare(T.name);case"created":return(m.createdAt||0)-(T.createdAt||0);case"context":{const q=((Z=m.contextStats)==null?void 0:Z.usedPercent)??(m.contextUsed||0)/(m.contextLimit||2e5)*100;return(((ee=T.contextStats)==null?void 0:ee.usedPercent)??(T.contextUsed||0)/(T.contextLimit||2e5)*100)-q}default:return(T.lastActivity||0)-(m.lastActivity||0)}}),g},[f,d,x]),$=Math.ceil(_.length/Ae),H=t.useMemo(()=>_.slice(A*Ae,(A+1)*Ae),[_,A]);W.current=H,E.current=N,Y.current=j,V.current=c,G.current=d,Te("commander-expanded",N!==null,()=>b(null));const se=st();t.useEffect(()=>{s&&se&&(b(se),I.clearCommanderExpandRequest())},[s,se]);const ae=t.useCallback(()=>b(null),[]),ne=t.useCallback(n=>b(n),[]),le=t.useCallback(n=>h(n),[]),pe=t.useCallback((n,o)=>{o?P.current.set(n,o):P.current.delete(n)},[]);return t.useEffect(()=>{R(0),Ie(oe.COMMANDER_TAB,d)},[d]),t.useEffect(()=>{Ie(oe.COMMANDER_FILTERS,JSON.stringify(x)),R(0)},[x]),t.useEffect(()=>{var o;if(!s||window.matchMedia("(pointer: coarse)").matches)return;const n=N||((o=W.current[j])==null?void 0:o.id);if(n){const g=P.current.get(n);g&&document.activeElement!==g&&setTimeout(()=>g.focus(),50)}},[s,j,N]),t.useEffect(()=>{if(!s)return;const n=o=>{const g=I.getShortcuts(),m=o.target,T=m.tagName==="INPUT"||m.tagName==="TEXTAREA",Z=W.current,ee=Z.length-1,q=E.current,ie=g.find(r=>r.id==="commander-close");if(Q(o,ie)){const{fileViewerPath:r,contextModalAgentId:J}=I.getState();if(r||J)return;o.preventDefault(),o.stopImmediatePropagation(),q?b(null):a();return}const he=g.find(r=>r.id==="commander-vim-left");if(Q(o,he)&&!q){o.preventDefault(),h(r=>r>0?r-1:r);return}const xe=g.find(r=>r.id==="commander-vim-right");if(Q(o,xe)&&!q){o.preventDefault(),h(r=>r<ee?r+1:r);return}const ge=g.find(r=>r.id==="commander-vim-up");if(Q(o,ge)&&!q){o.preventDefault(),h(r=>r>=me?r-me:r);return}const ve=g.find(r=>r.id==="commander-vim-down");if(Q(o,ve)&&!q){o.preventDefault(),h(r=>r+me<=ee?r+me:r);return}const je=g.find(r=>r.id==="commander-expand");if(Q(o,je)){if(o.preventDefault(),q)b(null);else{const r=Z[Y.current];r&&b(r.id)}return}const we=g.find(r=>r.id==="commander-new-agent");if(Q(o,we)){o.preventDefault(),u(!0);return}const Ce=g.find(r=>r.id==="commander-next-tab"),be=g.find(r=>r.id==="commander-prev-tab");if(!T){const r=V.current;if(Q(o,Ce)){const J=I.getState().latestNotificationAgentId;if(J){if(o.preventDefault(),o.stopPropagation(),!I.getState().agents.get(J)){I.setLatestNotificationAgentId(null);return}const y=I.getAreaForAgent(J);y&&r.some(O=>O.id===y.id)?M(y.id):M("unassigned"),b(J),h(0),R(0),I.setLatestNotificationAgentId(null);return}o.preventDefault(),o.stopPropagation();const ce=(r.findIndex(re=>re.id===G.current)+1)%r.length;M(r[ce].id),h(0);return}if(Q(o,be)){o.preventDefault(),o.stopPropagation();const de=(r.findIndex(ce=>ce.id===G.current)-1+r.length)%r.length;M(r[de].id),h(0);return}}};return document.addEventListener("keydown",n,!0),()=>document.removeEventListener("keydown",n,!0)},[s,a]),s?e.jsx("div",{className:"commander-overlay",onClick:a,children:e.jsxs("div",{className:"commander-view",onClick:n=>n.stopPropagation(),children:[e.jsxs("div",{className:"commander-header",children:[e.jsxs("div",{className:"commander-title-section",children:[e.jsx("h2",{className:"commander-title",children:l("commander.title")}),e.jsx("span",{className:"commander-shortcuts",children:l("commander.shortcuts")})]}),e.jsxs("div",{className:"commander-controls",children:[e.jsx("button",{className:`commander-view-toggle ${C?"active":""}`,onClick:()=>F(!C),title:l(C?"commander.simple":"commander.advanced"),children:C?e.jsxs(e.Fragment,{children:[e.jsx(z,{name:"target",size:12})," ",l("commander.advanced")]}):e.jsxs(e.Fragment,{children:[e.jsx(z,{name:"status-pending",size:12})," ",l("commander.simple")]})}),e.jsx("button",{className:"commander-add-btn",onClick:()=>u(!0),title:l("commander.addAgent"),children:l("commander.addAgent")}),e.jsx("button",{className:"commander-close",onClick:a,children:l("commander.close")})]})]}),e.jsx("div",{className:"commander-tabs",children:c.map(n=>{const o=n.id!=="all"&&n.id!=="unassigned"?p.get(n.id):null,g=o&&o.directories&&o.directories.length>0;return e.jsxs("button",{className:`commander-tab ${d===n.id?"active":""}`,onClick:()=>{M(n.id),h(0)},style:n.color?{borderBottomColor:d===n.id?n.color:"transparent"}:void 0,children:[n.color&&e.jsx("span",{className:"commander-tab-dot",style:{background:n.color}}),e.jsx("span",{children:n.name}),e.jsx("span",{className:"commander-tab-count",children:K.get(n.id)||0}),g&&e.jsx("span",{className:"commander-tab-folder",onClick:m=>{m.stopPropagation(),i(n.id)},title:l("commander.openFileExplorer"),children:e.jsx(z,{name:"folder",size:12})})]},n.id)})}),e.jsxs("div",{className:"commander-filters",children:[e.jsxs("div",{className:"commander-filter-group",children:[e.jsx("span",{className:"commander-filter-label",children:l("commander.filters.status")}),["all","working","idle","error","offline"].map(n=>e.jsx("button",{className:`commander-filter-btn ${x.status===n?"active":""}`,onClick:()=>k(o=>({...o,status:n})),children:n==="all"?l("commander.filters.all"):n==="error"?l("commander.filters.needsAttn"):n.charAt(0).toUpperCase()+n.slice(1)},n))]}),e.jsxs("div",{className:"commander-filter-group",children:[e.jsx("span",{className:"commander-filter-label",children:l("commander.filters.active")}),["all","1h","6h","24h"].map(n=>e.jsx("button",{className:`commander-filter-btn ${x.activity===n?"active":""}`,onClick:()=>k(o=>({...o,activity:n})),children:n==="all"?l("commander.filters.any"):`< ${n}`},n))]}),e.jsxs("div",{className:"commander-filter-group",children:[e.jsx("span",{className:"commander-filter-label",children:l("commander.filters.sort")}),["activity","name","created","context"].map(n=>e.jsx("button",{className:`commander-filter-btn ${x.sort===n?"active":""}`,onClick:()=>k(o=>({...o,sort:n})),children:n==="activity"?l("commander.filters.recent"):n==="context"?l("commander.filters.context"):n.charAt(0).toUpperCase()+n.slice(1)},n))]}),B&&e.jsx("button",{className:"commander-filter-clear",onClick:()=>k(Ne),title:l("commander.clearFilters"),children:l("commander.filters.clearFilters",{count:te})})]}),$>1&&e.jsxs("div",{className:"commander-pagination",children:[e.jsxs("button",{className:"commander-page-btn",onClick:()=>R(n=>Math.max(0,n-1)),disabled:A===0,children:[e.jsx(z,{name:"caret-left",size:12})," ",l("commander.prev")]}),e.jsx("span",{className:"commander-page-info",children:l("commander.page",{current:A+1,total:$,count:_.length})}),e.jsxs("button",{className:"commander-page-btn",onClick:()=>R(n=>Math.min($-1,n+1)),disabled:A===$-1,children:[l("commander.next")," ",e.jsx(z,{name:"caret-right",size:12})]})]}),e.jsx("div",{className:`commander-grid ${N?"has-expanded":""}`,"data-agent-count":N?1:H.length,children:H.length===0?e.jsx("div",{className:"commander-empty",children:l(d==="all"?"commander.noAgentsAll":d==="unassigned"?"commander.noAgentsUnassigned":"commander.noAgentsArea")}):N?(()=>{const n=f.get(N);return n?e.jsx(Pe,{agent:n,history:X.get(n.id),isExpanded:!0,isFocused:!0,advancedView:C,index:0,onExpand:ne,onCollapse:ae,onFocus:le,onInputRef:pe,onLoadMore:U,onClearHistory:w},n.id):null})():H.map((n,o)=>e.jsx(Pe,{agent:n,history:X.get(n.id),isExpanded:!1,isFocused:o===j,advancedView:C,index:o,onExpand:ne,onCollapse:ae,onFocus:le,onInputRef:pe,onLoadMore:U,onClearHistory:w},n.id))}),v&&e.jsx(ht,{currentArea:L,onClose:()=>u(!1)}),D&&e.jsx(at,{isOpen:!0,areaId:D,onClose:()=>i(null),onChangeArea:n=>i(n)})]})}):null}export{Ct as CommanderView};