tide-commander 1.110.2 → 1.110.3

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 (43) hide show
  1. package/dist/assets/{BossLogsModal-DBeMak5-.js → BossLogsModal-Dub95BCo.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-DDl6qgnq.js → BossSpawnModal-BXIZWAzn.js} +1 -1
  3. package/dist/assets/{ControlsModal-BBUukX-p.js → ControlsModal-MclobOaO.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-BWf3XDEI.js → DockerLogsModal-DRQ6YsEB.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-CIOdhnaW.js → EmbeddedEditor-B9iQHzhz.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-qG-_WeOb.js → GmailOAuthSetup-wEezv-Vt.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-BK3lzU4n.js → GoogleOAuthSetup-P_teBMn2.js} +1 -1
  8. package/dist/assets/{IframeModal-D_NEs_Ld.js → IframeModal-DEXm0UTA.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-yphWX1ZD.js → IntegrationsPanel-CgFuLL4S.js} +2 -2
  10. package/dist/assets/{LogViewerModal-B0h9NNRk.js → LogViewerModal-CSpbNMTp.js} +1 -1
  11. package/dist/assets/{MonitoringModal-Ciw7KnXH.js → MonitoringModal-Dv1lWqtZ.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-C1dYQaff.js → PM2LogsModal-qpjByXs_.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-DOwzfu-D.js → RestoreArchivedAreaModal-2O5SPxwQ.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-MHfv4Rzg.js → Scene2DCanvas-BJiXSOxB.js} +1 -1
  15. package/dist/assets/{SceneManager-cm1Kj0YD.js → SceneManager-D9NtdKQ1.js} +1 -1
  16. package/dist/assets/{SkillsPanel-DLwMkORc.js → SkillsPanel-B8_RPJzS.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-Dql_wPMX.js → SlackMultiInstanceSetup-VcCJhIhV.js} +1 -1
  18. package/dist/assets/{SpawnModal-DzPTSOKV.js → SpawnModal-gn1VV_xv.js} +1 -1
  19. package/dist/assets/StatisticsModal-DRvS2yB_.js +1 -0
  20. package/dist/assets/{SubordinateAssignmentModal-CoLzD3z2.js → SubordinateAssignmentModal-D9gpXqIB.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-BOi2zr7N.js → TriggerManagerPanel-bBguUZCE.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-DB1ygPDS.js → WorkflowEditorPanel-BGcpM6uO.js} +1 -1
  23. package/dist/assets/{index-BZsQOteM.js → index-2NGIIydL.js} +1 -1
  24. package/dist/assets/{index-DKASWGtq.js → index-BLw57j0y.js} +1 -1
  25. package/dist/assets/index-Bg0YBtj9.js +11 -0
  26. package/dist/assets/{index-DKdZI-Ar.js → index-Bgcnlnvz.js} +1 -1
  27. package/dist/assets/{index-6Wak7CPm.js → index-BrdAbMM1.js} +1 -1
  28. package/dist/assets/{index-BXJSMT4a.js → index-CTfxfQqV.js} +3 -3
  29. package/dist/assets/{index-ThbMNdRp.js → index-Cy72l2Qo.js} +1 -1
  30. package/dist/assets/{index-D4XW6MSF.js → index-GpT5NHsq.js} +2 -2
  31. package/dist/assets/{index-C6EHHgC0.js → index-VYch6p3A.js} +1 -1
  32. package/dist/assets/{main-BxA3Bhkv.js → main-Brpf2Evy.js} +94 -94
  33. package/dist/assets/{main-BLrGoeQ_.css → main-VciFPjA1.css} +1 -1
  34. package/dist/assets/{web-BskC98UQ.js → web-DUdLOxoB.js} +1 -1
  35. package/dist/assets/{web-CSRmX8Ge.js → web-DjzK5qYd.js} +1 -1
  36. package/dist/assets/{web-zdygXcYu.js → web-IMi3bHab.js} +1 -1
  37. package/dist/index.html +2 -2
  38. package/dist/src/packages/server/data/builtin-skills/send-message-to-agent.js +31 -1
  39. package/dist/src/packages/server/routes/agents.js +30 -0
  40. package/dist/src/packages/server/services/runtime-service.js +24 -0
  41. package/dist/src/packages/server/websocket/handlers/agent-handler.js +18 -12
  42. package/package.json +1 -1
  43. package/dist/assets/index-BP6ukiYG.js +0 -11
@@ -1,2 +1,2 @@
1
- import{r as a,z as rn,B as Tt,u as Wt,E as on,j as e,V as cn,G as dn,H as un,J as Pt,S as y,K as Lt,L as kt,M as Dt,N as ut,O as se,P as pn,s as x,U as Ht,W as Vt,X as mn,v as Rt,w as zt,I as u,Y as fn,m as hn,Z as gn,_ as Xt,$ as Gt,a0 as xn,a1 as bn,a2 as _n,a3 as wn,a4 as vn,a5 as Cn,a6 as jn,a7 as Nn,a8 as kn,a9 as yn,aa as An,ab as In,ac as Ot,C as En,ad as Sn,ae as Mn,af as Tn,ag as Pn,ah as Ln,ai as Dn,aj as Rn,ak as zn,al as On,am as $n,an as Bn,ao as Fn,ap as Wn,aq as Hn,ar as Vn,as as Xn}from"./main-BxA3Bhkv.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Gn(w){const c=a.useRef(w);c.current=w,a.useEffect(()=>{if(!rn())return;let v=null,A=!1;return Tt.addListener("backButton",()=>{c.current()==="exit"&&Tt.exitApp()}).then(S=>{A?S.remove():v=S}),()=>{A=!0,v&&(v.remove(),v=null)}},[])}const Un=a.memo(function({className:c=""}){const{t:v}=Wt(["common"]),[A,S]=on(),q=a.useRef(null),[O,De]=a.useState(null);a.useLayoutEffect(()=>{const g=q.current;if(!g)return;const Y=g.querySelector(".view-mode-toggle__btn--active");Y&&De({left:Y.offsetLeft,width:Y.offsetWidth})},[A]);const le=a.useCallback(g=>{if(g!==A){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:g}})),g==="3d"){requestAnimationFrame(()=>S(g));return}S(g)}},[A,S]);return e.jsxs("div",{className:`view-mode-toggle ${c}`,ref:q,children:[O&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:O.left,width:O.width}}),cn.map(g=>e.jsxs("button",{className:`view-mode-toggle__btn ${A===g?"view-mode-toggle__btn--active":""}`,onClick:()=>le(g),title:v(`common:viewMode.descriptions.${g}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[g==="2d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),g==="3d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}),g==="flat"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]}),g==="dashboard"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),e.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),e.jsx("span",{className:"view-mode-toggle__label",children:v(`common:viewMode.labels.${g}`)})]},g))]})}),pt=3,mt=280,$t=320,Nt=240,Bt=64,qn=["simple","chat","advanced"],Yn={simple:"Simple",chat:"Chat",advanced:"Advanced"},Kn={simple:"○",chat:"◐",advanced:"◉"},Zn={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Ft="flat-clear-context";function Jn(w){const c=w.split("/").filter(Boolean);return c.length===0?w:c.slice(-2).join("/")}function Qn(w){if(w.provider==="codex"){const q=w.codexModel||"gpt-5.3-codex",O=Hn[q];return{model:(O==null?void 0:O.label)||q}}if(w.provider==="opencode")return{model:w.opencodeModel||"opencode"};const c=w.model||"sonnet",v=Xn[c],A=w.effort,S=A?Vn[A]:void 0;return{model:(v==null?void 0:v.label)||c,effort:S==null?void 0:S.label}}function ea(w,c){if(c.type==="rectangle"&&c.width&&c.height){const v=c.width/2,A=c.height/2;return w.x>=c.center.x-v&&w.x<=c.center.x+v&&w.z>=c.center.z-A&&w.z<=c.center.z+A}if(c.type==="circle"&&c.radius){const v=w.x-c.center.x,A=w.z-c.center.z;return v*v+A*A<=c.radius*c.radius}return!1}const ta=Sn.memo(function({agentId:c,terminalViewMode:v,onTerminalViewModeChange:A,inspectorOpen:S,onToggleInspector:q,onImageClick:O,onFileClick:De,onBashClick:le,onViewMarkdown:g,onRequestClearSubordinates:Y,onOpenBuilding:ye,keyboard:We,canNavigateBack:He,canNavigateForward:Ve,onNavigateBack:pe,onNavigateForward:ie,agentInfoOpen:me,onToggleAgentInfo:Xe,onHeaderContextMenu:K,onBuildingContextMenu:fe}){var ce,Pe,ne,st;const h=Mn(c),$=Vt(),B=a.useRef(null),Ae=a.useRef(null);a.useEffect(()=>{const l=Ae.current;if(!l)return;const r=d=>{d.button===3?(d.preventDefault(),d.stopPropagation(),pe()):d.button===4&&(d.preventDefault(),d.stopPropagation(),ie())},o=d=>{(d.button===3||d.button===4)&&d.preventDefault()};return l.addEventListener("mouseup",r),l.addEventListener("mousedown",o),()=>{l.removeEventListener("mouseup",r),l.removeEventListener("mousedown",o)}},[pe,ie]),a.useEffect(()=>{const l=Ae.current;if(!l)return;let r=0,o=0,d=0;const de=250,Ce=600,Le=80,bt=1.5,_t=P=>{let M=P instanceof HTMLElement?P:null;for(;M&&M!==l;){const lt=window.getComputedStyle(M).overflowX;if((lt==="auto"||lt==="scroll")&&M.scrollWidth>M.clientWidth)return!0;M=M.parentElement}return!1},V=P=>{const M=Date.now();if(M<d){P.preventDefault();return}if(Math.abs(P.deltaX)<=Math.abs(P.deltaY)*bt){r=0;return}if(_t(P.target)){r=0;return}M-o>de&&(r=0),o=M,r+=P.deltaX,r<=-Le?(r=0,d=M+Ce,P.preventDefault(),pe()):r>=Le&&(r=0,d=M+Ce,P.preventDefault(),ie())};return l.addEventListener("wheel",V,{passive:!1}),()=>l.removeEventListener("wheel",V)},[pe,ie]);const Ie=Ht(),he=a.useMemo(()=>{if(!h)return null;const l=new Set,r=[];for(const o of Ie.values())o.archived||o.directories.length===0||o.assignedAgentIds.includes(c)&&(l.add(o.id),r.push(o));for(const o of Ie.values())o.archived||o.directories.length===0||l.has(o.id)||ea({x:h.position.x,z:h.position.z},o)&&(l.add(o.id),r.push(o));return r.length===0?null:r.flatMap(o=>o.directories.filter(d=>d&&d.trim().length>0).map(d=>({areaId:o.id,areaName:o.name,dir:d})))},[h,c,Ie]),{branches:Ge,fetchRemote:Ue,fetchingDirs:qe}=Tn(he),ge=a.useMemo(()=>{var o;const l=x.getAreaForAgent(c);if(!l)return[];const r=[];for(const d of $.values())d.type==="terminal"&&x.isPositionInArea(d.position,l)&&r.push({id:d.id,name:d.name,hasUrl:!!((o=d.terminalStatus)!=null&&o.url)});return r},[c,$]),Ye=a.useMemo(()=>{var o;const l=x.getAreaForAgent(c);if(!l)return[];const r=[];for(const d of $.values())d.type==="server"&&((o=d.pm2)!=null&&o.enabled)&&x.isPositionInArea(d.position,l)&&r.push({id:d.id,name:d.name});return r},[c,$]),xe=a.useMemo(()=>{const l=x.getAreaForAgent(c);if(!l)return[];const r=[];for(const o of $.values())o.type==="database"&&o.database&&x.isPositionInArea(o.position,l)&&r.push({id:o.id,name:o.name});return r},[c,$]),[,be]=a.useReducer(l=>l+1,0),F=((ce=B.current)==null?void 0:ce.search.searchMode)??!1,re=a.useCallback(()=>{var l;(l=B.current)==null||l.search.toggleSearch(),be()},[]),Ke=Pn(),Re=Ke.isPending(Ft),[W,X]=a.useState(null),R=W?$.get(W):null,{height:Ee,onResizeStart:G}=Ln(),[U,Z]=a.useState(()=>kt(y.GIT_PANEL_OPEN,!1)),[z,Ze]=a.useState(()=>kt(y.BUILDINGS_PANEL_OPEN,!1)),[_e,ze]=a.useState(!1),Se=a.useCallback(()=>{ze(l=>{const r=!l;return r&&Dn.setEnabled(!0),r})},[]),ft=a.useCallback(()=>ze(!1),[]),ht=a.useCallback(()=>{Z(l=>{const r=!l;return se(y.GIT_PANEL_OPEN,r),r})},[]),we=a.useCallback(()=>{Ze(l=>{const r=!l;return se(y.BUILDINGS_PANEL_OPEN,r),r})},[]),gt=a.useCallback(()=>{Z(!1),se(y.GIT_PANEL_OPEN,!1)},[]),Je=a.useCallback(()=>{Ze(!1),se(y.BUILDINGS_PANEL_OPEN,!1)},[]),xt=Rn();a.useEffect(()=>{if(!W)return;ge.some(r=>r.id===W)||X(null)},[W,ge]);const[J,oe]=a.useState(!1),Oe=a.useRef(null);if(a.useEffect(()=>{if(!J)return;const l=r=>{Oe.current&&!Oe.current.contains(r.target)&&oe(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[J]),!h)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const Q=h.contextStats,Qe=!!Q,et=Q?Q.totalTokens:h.contextUsed||0,tt=Q?Q.contextWindow:h.contextLimit||2e5,Me=Q?Q.usedPercent:Math.round(et/tt*100),f=Math.max(0,Math.min(100,Me)),ee=Math.round(f*10)/10,H=Math.round((100-f)*10)/10,ve=f>=80?"#ff4a4a":f>=60?"#ff9e4a":f>=40?"#ffd700":"#4aff9e",$e=(et/1e3).toFixed(1),nt=(tt/1e3).toFixed(1),te=h.cwd,at=te?Jn(te):null,Te=((Pe=h.subordinateIds)==null?void 0:Pe.length)||0,Be=Te>0;return e.jsxs("div",{ref:Ae,className:`flat-terminal-wrapper ${U||z||_e?"flat-terminal-wrapper--with-side-panel":""}`,children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${me?"flat-terminal-wrapper__header-main--active":""}`,onClick:Xe,onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),K({x:l.clientX,y:l.clientY})},title:me?"Hide agent info":"Show agent info","aria-pressed":me,children:[e.jsx(Xt,{agent:h,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:h.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:Gt(h.status)},children:h.status})]}),h.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:h.taskLabel,children:["📋 ",h.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:h.provider==="codex"?"/assets/codex.png":h.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:h.provider,className:"flat-terminal-wrapper__header-provider-icon",title:h.provider==="codex"?"Codex Agent":h.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:l,effort:r}=Qn(h);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:r?`Model: ${l} · Effort: ${r}`:`Model: ${l}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:l}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-sep","aria-hidden":"true",children:"·"}),e.jsx("span",{className:"flat-terminal-wrapper__header-model-effort",children:r})]})]})})()]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__header-meta",children:[e.jsx("div",{className:"flat-terminal-wrapper__view-mode",role:"group","aria-label":"Message view mode",children:qn.map(l=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${v===l?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>A(l),title:Zn[l],"aria-pressed":v===l,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:Kn[l]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:Yn[l]})]},l))}),e.jsxs("div",{className:"flat-terminal-wrapper__actions",role:"group","aria-label":"Terminal actions",children:[e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:pe,disabled:!He,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(u,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:ie,disabled:!Ve,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(u,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${F?"flat-terminal-wrapper__action-btn--active":""}`,onClick:re,title:F?"Close search":"Search messages","aria-pressed":F,children:e.jsx(u,{name:F?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${Re?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>Ke.handleClick(Ft,()=>{var l;x.clearContext(c),(l=B.current)==null||l.historyLoader.clearHistory()}),title:Re?"Click again to confirm clear context":"Clear context",children:e.jsx(u,{name:Re?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${U?"flat-terminal-wrapper__action-btn--active":""}`,onClick:ht,title:U?"Hide git panel":"Show git changes","aria-pressed":U,children:e.jsx(u,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${z?"flat-terminal-wrapper__action-btn--active":""}`,onClick:we,title:z?"Hide buildings panel":"Show area buildings","aria-pressed":z,children:e.jsx(u,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:Oe,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${J?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>oe(l=>!l),title:"More actions","aria-expanded":J,children:"⋮"}),J&&e.jsxs("div",{className:"flat-terminal-wrapper__more-menu",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-terminal-wrapper__more-item ${_e?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{Se(),oe(!1)},title:_e?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(u,{name:"bug",size:14}),e.jsx("span",{children:_e?"Hide Debug Panel":"Show Debug Panel"})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item",onClick:()=>{x.collapseContext(c),oe(!1)},disabled:h.status!=="idle",title:h.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(u,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),Be&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{Y(c,Te),oe(!1)},children:[e.jsx(u,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",Te," subordinate",Te===1?"":"s"]})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{x.killAgent(c),oe(!1)},children:[e.jsx(u,{name:"cross",size:14}),e.jsx("span",{children:"Remove agent"})]})]})]})]}),e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__inspector-toggle ${S?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:q,title:S?"Hide inspector panel":"Show inspector panel","aria-label":S?"Hide inspector panel":"Show inspector panel","aria-pressed":S,children:[e.jsx("span",{className:"flat-terminal-wrapper__inspector-icon","aria-hidden":"true",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"}),e.jsx("line",{x1:"10",y1:"2.5",x2:"10",y2:"13.5"})]})}),e.jsx("span",{className:"flat-terminal-wrapper__inspector-label",children:"Inspector"})]}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__close",onClick:()=>x.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(u,{name:"cross",size:14})})]})]}),e.jsx(zn,{ref:B,agentId:c,agent:h,viewMode:v,isOpen:!0,onImageClick:O,onFileClick:De,onBashClick:le,onViewMarkdown:g,keyboard:We,hasModalOpen:!1}),R&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:G,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${R.name}`,style:{height:Ee},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(u,{name:"terminal",size:12}),e.jsx("span",{children:R.name}),!((ne=R.terminalStatus)!=null&&ne.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>X(null),title:"Close embedded terminal","aria-label":"Close embedded terminal",children:e.jsx(u,{name:"cross",size:12})})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:(st=R.terminalStatus)!=null&&st.url?e.jsx(On,{terminalUrl:R.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."})})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[h.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(u,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),te&&at&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${te}`,"aria-label":`Open ${te} in file explorer`,role:"button",tabIndex:0,onClick:()=>x.openFileExplorer(te),onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),x.openFileExplorer(te))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(u,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:at})]}),he&&he.map(({areaId:l,areaName:r,dir:o})=>{const d=Ge.get(o),de=qe.has(o),Ce=o.split("/").filter(Boolean).pop()||o;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${r}: ${o}${d?` (${d.branch}${d.ahead?` ↑${d.ahead}`:""}${d.behind?` ↓${d.behind}`:""})`:""}`,onClick:()=>x.openFileExplorerForAreaFolder(l,o),children:[e.jsx(u,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:Ce}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(u,{name:"git-branch",size:10})," ",d.branch]}),d.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${d.ahead} ahead`,children:[e.jsx(u,{name:"arrow-up",size:9}),d.ahead]}),d.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${d.behind} behind`,children:[e.jsx(u,{name:"arrow-down",size:9}),d.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${de?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Le=>{Le.stopPropagation(),Ue(o)},children:e.jsx(u,{name:de?"hourglass":"download",size:12})})]})]},`${l}:${o}`)}),e.jsxs("span",{className:"flat-terminal-wrapper__context",onClick:()=>x.setContextModalAgentId(c),title:Qe?`Context usage: ${$e}k / ${nt}k tokens (${ee}% used). Click to view stats.`:"Click to fetch context stats",children:[e.jsx("span",{className:"flat-terminal-wrapper__context-icon",children:e.jsx(u,{name:"dashboard",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__context-label",children:"Ctx:"}),e.jsx("span",{className:"flat-terminal-wrapper__context-bar",children:e.jsx("span",{className:"flat-terminal-wrapper__context-bar-fill",style:{width:`${f}%`,backgroundColor:ve}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:ve},children:[$e,"k/",nt,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",H,"% free)"]}),!Qe&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(u,{name:"warn",size:12})})]}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),ge.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:ge.map(l=>{const r=W===l.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${r?"flat-terminal-wrapper__building-btn--active":""} ${l.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${r?"Hide":"Show"} terminal: ${l.name}${l.hasUrl?"":" (starting...)"}`,onClick:()=>{if(r){X(null);return}l.hasUrl||x.sendBuildingCommand(l.id,"start"),X(l.id)},onContextMenu:o=>{o.preventDefault(),o.stopPropagation(),fe(l.id,{x:o.clientX,y:o.clientY})},children:e.jsx(u,{name:"terminal",size:14})},l.id)})}),Ye.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:Ye.map(l=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${l.name}`,onClick:()=>ye(l.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),fe(l.id,{x:r.clientX,y:r.clientY})},children:e.jsx(u,{name:"scroll",size:14})},l.id))}),xe.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:xe.map(l=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${l.name}`,onClick:()=>ye(l.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),fe(l.id,{x:r.clientX,y:r.clientY})},children:e.jsx(u,{name:"hard-drives",size:14})},l.id))}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx($n,{})})]}),U&&e.jsx(Bn,{agentId:c,agents:xt,onClose:gt,branchInfoMap:Ge,fetchRemote:Ue,fetchingDirs:qe}),z&&e.jsx(Fn,{agentId:c,onClose:Je}),_e&&e.jsx(Wn,{agentId:c,onClose:ft})]})});function la({onAgentClick:w,onBuildingClick:c,onBuildingDoubleClick:v,onBuildingPopup:A,onAreaContextMenu:S,onOpenSpawnModal:q,onOpenBossSpawnModal:O,onOpenAreaModal:De}){const{t:le}=Wt(["common"]),g=dn(),Y=un(),[ye,We]=a.useState(null),[He,Ve]=a.useState(null),[pe,ie]=a.useState(null),[me,Xe]=a.useState(null),[K,fe]=a.useState(null),[h,$]=a.useState(null),[B,Ae]=a.useState(null),[Ie,he]=a.useState(!1),Ge=a.useCallback(()=>{he(t=>!t)},[]),Ue=a.useCallback(()=>{he(!1)},[]),[qe,ge]=a.useState(()=>{const t=Pt(y.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Ye=a.useCallback(t=>{ge(t),Lt(y.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=n=>{if(n.key!==y.VIEW_MODE)return;const s=n.newValue;(s==="simple"||s==="chat"||s==="advanced")&&ge(s)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[xe,be]=a.useState(()=>kt(y.FLAT_INSPECTOR_OPEN,!1)),[F,re]=a.useState(!1),Ke=a.useCallback(()=>re(t=>!t),[]),Re=a.useCallback(()=>re(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:F}}))},[F]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:xe}}))},[xe]),a.useEffect(()=>{const t=()=>re(_=>!_),n=()=>{be(_=>{const i=!_;return se(y.FLAT_INSPECTOR_OPEN,i),i})},s=()=>{re(!1),be(!1),se(y.FLAT_INSPECTOR_OPEN,!1)},p=()=>re(!1),m=()=>{be(!1),se(y.FLAT_INSPECTOR_OPEN,!1)};return window.addEventListener("tide-toggle-flat-agents-drawer",t),window.addEventListener("tide-toggle-flat-inspector",n),window.addEventListener("tide-close-flat-side-views",s),window.addEventListener("tide-close-flat-agents-drawer-only",p),window.addEventListener("tide-close-flat-inspector-only",m),()=>{window.removeEventListener("tide-toggle-flat-agents-drawer",t),window.removeEventListener("tide-toggle-flat-inspector",n),window.removeEventListener("tide-close-flat-side-views",s),window.removeEventListener("tide-close-flat-agents-drawer-only",p),window.removeEventListener("tide-close-flat-inspector-only",m)}},[]);const W=a.useRef(null),X=a.useRef(null),[R,Ee]=a.useState(()=>{const t=Dt(y.FLAT_MIDDLE_WIDTH,0);return t>=mt?t:null}),[G,U]=a.useState(()=>{const t=Dt(y.FLAT_INSPECTOR_WIDTH,0);return t>=Nt?t:null}),Z=a.useCallback(t=>{if(typeof window>"u")return t;const n=G!==null?pt+G:0,s=window.innerWidth-Bt-pt-$t-n;return Math.max(mt,Math.min(Math.max(s,mt),t))},[G]),z=a.useCallback(t=>{var m;if(typeof window>"u")return t;const n=(m=W.current)==null?void 0:m.querySelector(".flat-middle"),s=(n==null?void 0:n.getBoundingClientRect().width)??mt,p=window.innerWidth-Bt-s-pt-$t-pt;return Math.max(Nt,Math.min(Math.max(p,Nt),t))},[]);a.useEffect(()=>{if(R===null&&G===null)return;const t=()=>{Ee(n=>{if(n===null)return n;const s=Z(n);return s===n?n:s}),U(n=>{if(n===null)return n;const s=z(n);return s===n?n:s})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[R,G,Z,z]);const Ze=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=W.current)==null?void 0:s.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),X.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),_e=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=W.current)==null?void 0:s.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),X.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),ze=a.useCallback(t=>{const n=X.current;if(!n||t.pointerId!==n.pointerId)return;const s=t.clientX-n.startX;n.kind==="middle"?Ee(Z(n.startWidth+s)):U(z(n.startWidth-s))},[Z,z]),Se=a.useCallback(t=>{const n=X.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(X.current=null,document.body.classList.remove("flat-splitter-dragging"),!(Math.abs(t.clientX-n.startX)>2))return;const p=t.clientX-n.startX;if(n.kind==="middle"){const m=Z(n.startWidth+p);Ee(m),ut(y.FLAT_MIDDLE_WIDTH,m)}else{const m=z(n.startWidth-p);U(m),ut(y.FLAT_INSPECTOR_WIDTH,m)}},[Z,z]),ft=a.useCallback(()=>{Ee(null),ut(y.FLAT_MIDDLE_WIDTH,0)},[]),ht=a.useCallback(()=>{U(null),ut(y.FLAT_INSPECTOR_WIDTH,0)},[]),[we,gt]=a.useState(()=>Pt(y.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Je=a.useCallback(t=>{gt(t),Lt(y.FLAT_INSPECTOR_VIEW,t)},[]),xt=a.useCallback(()=>{be(t=>{const n=!t;return se(y.FLAT_INSPECTOR_OPEN,n),n})},[]),J=a.useCallback(()=>{be(!1),se(y.FLAT_INSPECTOR_OPEN,!1)},[]),oe=pn(),Oe=a.useCallback((t,n)=>{We({url:t,name:n})},[]),Q=a.useCallback((t,n)=>{Ve({command:t,output:n,isLive:!1})},[]),Qe=a.useCallback((t,n)=>{x.setFileViewerPath(t,n)},[]),et=a.useCallback(t=>{ie(t)},[]),tt=a.useCallback((t,n)=>{Xe({agentId:t,count:n})},[]),Me=a.useCallback(t=>{v?v(t):c(t)},[c,v]),f=a.useMemo(()=>Y.size>0?Array.from(Y)[0]:null,[Y]);a.useEffect(()=>{he(!1)},[f]);const ee=a.useRef([]),H=a.useRef(-1),ve=a.useRef(!1),$e=a.useRef(null),[nt,te]=a.useState(!1),[at,Te]=a.useState(!1),Be=a.useRef(!1),ce=a.useRef(null),Pe=a.useRef(!1),ne=a.useMemo(()=>new Set(g.map(t=>t.id)),[g]),st=a.useMemo(()=>{const t=new Map(g.map(s=>[s.id,s])),n=new Map;for(const s of g)if((s.isBoss||s.class==="boss")&&s.subordinateIds&&s.subordinateIds.length>0){const p=s.subordinateIds.map(m=>t.get(m)).filter(m=>m!==void 0);p.length>0&&n.set(s.id,p)}return n},[g]),l=a.useCallback(()=>{const t=ee.current,n=H.current;te(n>0),Te(n>=0&&n<t.length-1)},[]),r=a.useCallback(t=>{const n=ee.current;if(n.length===0)return;let s=H.current+t;for(;s>=0&&s<n.length;){const p=n[s];if(ne.has(p)){ve.current=!0,H.current=s,l(),x.selectAgent(p);return}s+=t}},[ne,l]),o=a.useCallback(()=>r(-1),[r]),d=a.useCallback(()=>r(1),[r]);Gn(a.useCallback(()=>{const t=ee.current,n=H.current;return t.length>0&&n>0?(r(-1),"handled"):"exit"},[r]));const de=a.useCallback((t,n)=>{if(typeof window>"u")return;const s=window.history.state,m={...typeof s=="object"&&s!==null?s:{},__flatAgentNav:{agentId:t}};n==="replace"?window.history.replaceState(m,"",window.location.href):window.history.pushState(m,"",window.location.href)},[]);a.useEffect(()=>{if(!f){Be.current=!1,ce.current=null;return}if(!Be.current){de(f,"replace"),Be.current=!0,ce.current=f;return}if(Pe.current){Pe.current=!1,ce.current=f;return}ce.current!==f&&(de(f,"push"),ce.current=f)},[f,de]),a.useEffect(()=>{const t=n=>{var _,i;const s=(i=(_=n.state)==null?void 0:_.__flatAgentNav)==null?void 0:i.agentId;if(!s||typeof s!="string"||!ne.has(s)||s===f)return;Pe.current=!0,ve.current=!0;const p=ee.current,m=p.lastIndexOf(s);m>=0?H.current=m:(p.push(s),H.current=p.length-1),l(),x.selectAgent(s)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ne,f,l]),a.useEffect(()=>{if(!f){ee.current=[],H.current=-1,l();return}if($e.current=f,ve.current){ve.current=!1,l();return}const t=ee.current,n=H.current;if(n>=0&&t[n]===f){l();return}const s=n<t.length-1?t.slice(0,n+1):t.slice();s.push(f),s.length>100&&s.shift(),ee.current=s,H.current=s.length-1,l()},[f,l]);const Ce=a.useCallback(t=>{w(t),re(!1)},[w]),Le=f??"",bt=a.useCallback(()=>{},[]),_t=a.useCallback(t=>{Ce(t)},[Ce]),V=xe,[P,M]=a.useState(V),[lt,yt]=a.useState(V);a.useEffect(()=>{if(V){M(!0);return}yt(!1);const t=setTimeout(()=>M(!1),240);return()=>clearTimeout(t)},[V]),a.useEffect(()=>{if(!P||!V)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>yt(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[P,V]);const At=a.useRef(null);a.useEffect(()=>{if(f)return;const t=n=>{if(n.key!==" "&&n.key!=="Backspace")return;const s=n.target;if(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.isContentEditable)return;const p=$e.current;!p||!ne.has(p)||(n.preventDefault(),x.selectAgent(p))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[f,ne]);const[Ut,It]=a.useState(new Set),qt=a.useCallback(t=>{It(n=>{const s=new Set(n);return s.has(t)?s.delete(t):s.add(t),s})},[]),[je,Yt]=a.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches);a.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 768px)"),n=s=>Yt(s.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[it,Kt]=a.useState(null),Zt=a.useCallback(t=>{Kt(n=>n===t?null:t)},[]),wt=Ht(),rt=Vt(),[Jt]=mn(),Ne=a.useMemo(()=>{const t=new Map,n=[];for(const b of g){const k=x.getAreaForAgent(b.id);if(!Rt((k==null?void 0:k.id)??null))continue;if(!k||k.archived){n.push(b);continue}const N=t.get(k.id);N?N.push(b):t.set(k.id,[b])}const s=new Map,p=[];for(const b of rt.values()){let k=!1;for(const N of wt.values())if(!N.archived&&zt(N.id)&&x.isPositionInArea(b.position,N)){const ae=s.get(N.id);ae?ae.push(b):s.set(N.id,[b]),k=!0;break}!k&&Rt(null)&&p.push(b)}const m=[];for(const[,b]of wt){if(b.archived||!zt(b.id))continue;const k=t.get(b.id),N=s.get(b.id)??[];(k&&k.length>0||N.length>0)&&m.push({area:b,agents:k??[],buildings:N})}(n.length>0||p.length>0)&&m.push({area:{id:"__unassigned__",name:"Unassigned",color:"#6272a4",center:{x:0,z:0},type:"circle",radius:0,directories:[],archived:!1,assignedAgentIds:[],zIndex:0},agents:n,buildings:p});const _=m.filter(b=>b.area.id!=="__unassigned__"),i=m.filter(b=>b.area.id==="__unassigned__");let I=1,j=1;const E=new Map;if(_.length>1){let b=1/0,k=-1/0,N=1/0,ae=-1/0;for(const L of _)b=Math.min(b,L.area.center.x),k=Math.max(k,L.area.center.x),N=Math.min(N,L.area.center.z),ae=Math.max(ae,L.area.center.z);const ot=k-b||1,ct=ae-N||1;if(_.length<=4){I=_.length,j=1;const L=[..._].sort((D,vt)=>D.area.center.x-vt.area.center.x);for(let D=0;D<L.length;D++)E.set(L[D].area.id,{row:1,col:D+1})}else{const L=[..._].sort((C,T)=>C.area.center.x-T.area.center.x),D=[];for(let C=1;C<L.length;C++)D.push(L[C].area.center.x-L[C-1].area.center.x);const vt=D.reduce((C,T)=>C+T,0)/D.length||1;let Et=1;for(const C of D)C>vt*1.3&&Et++;I=Math.max(2,Math.min(Et,_.length));const Ct=[..._].sort((C,T)=>C.area.center.z-T.area.center.z),dt=[];for(let C=1;C<Ct.length;C++)dt.push(Ct[C].area.center.z-Ct[C-1].area.center.z);const nn=dt.reduce((C,T)=>C+T,0)/dt.length||1;let St=1;for(const C of dt)C>nn*1.3&&St++;j=Math.max(2,Math.min(St,_.length)),I=Math.max(I,Math.ceil(_.length/j)),j=Math.max(j,Math.ceil(_.length/I));const an=ot/I,sn=ct/j,jt=new Set;for(const C of _){let T=Math.min(I-1,Math.max(0,Math.floor((C.area.center.x-b)/an))),ke=Math.min(j-1,Math.max(0,Math.floor((C.area.center.z-N)/sn))),Fe=`${ke},${T}`,Mt=0;const ln=j*I;for(;jt.has(Fe)&&Mt<ln;)T++,T>=I&&(T=0,ke=(ke+1)%j),Fe=`${ke},${T}`,Mt++;jt.has(Fe)&&(ke=j,T=0,Fe=`${ke},${T}`,j++),jt.add(Fe),E.set(C.area.id,{row:ke+1,col:T+1})}}}const ue=b=>{b.sort((k,N)=>{var ot,ct,L,D;const ae=(((ot=k.position)==null?void 0:ot.z)??0)-(((ct=N.position)==null?void 0:ct.z)??0);return ae!==0?ae:(((L=k.position)==null?void 0:L.x)??0)-(((D=N.position)==null?void 0:D.x)??0)})};for(const b of _)ue(b.agents);for(const b of i)ue(b.agents);return{groups:[..._,...i],gridCols:I,gridRows:j,positions:E}},[g,wt,rt,Jt]),Qt=a.useMemo(()=>{if(!K)return[];const t=g.find(n=>n.id===K.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(u,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-agent-edit",{detail:{agentId:t.id}}))}},{id:"open-chat",label:"Open Chat",icon:e.jsx(u,{name:"chat",size:14}),onClick:()=>w(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(u,{name:"trash",size:14}),danger:!0,onClick:()=>{Ae({agentId:t.id,name:t.name})}}]:[]},[K,g,w]),en=a.useMemo(()=>{var _;if(!h)return[];const t=rt.get(h.buildingId);if(!t)return[];const n=[],s=t.type==="server"||t.type==="docker"||t.type==="terminal",p=t.status==="running",m=t.type==="boss";if(n.push({id:"open",label:t.type==="database"?"Open Database":t.type==="folder"?"Open Folder":t.type==="boss"?"View Boss Logs":t.type==="terminal"?"Open Terminal":t.type==="server"&&((_=t.pm2)!=null&&_.enabled)?"View PM2 Logs":"Open",icon:e.jsx(u,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>Me(t.id)}),s&&(p||n.push({id:"start",label:"Start",icon:e.jsx(u,{name:"play",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"start")}),p&&(n.push({id:"restart",label:"Restart",icon:e.jsx(u,{name:"refresh",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(u,{name:"stop",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"stop")}))),m&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(n.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(u,{name:"launch",size:14}),onClick:()=>{for(const i of t.subordinateBuildingIds)x.sendBuildingCommand(i,"start")}}),n.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(u,{name:"pause",size:14}),onClick:()=>{for(const i of t.subordinateBuildingIds)x.sendBuildingCommand(i,"stop")}}),n.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(u,{name:"restart",size:14}),onClick:()=>{for(const i of t.subordinateBuildingIds)x.sendBuildingCommand(i,"restart")}})),s&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(u,{name:"health",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"healthCheck")}),n.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),n.push({id:"edit",label:"Edit Building",icon:e.jsx(u,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:building-edit",{detail:{buildingId:t.id}}))}}),n.push({id:"clone",label:"Clone Building",icon:e.jsx(u,{name:"copy",size:14}),onClick:()=>{x.createBuilding({name:`${t.name} (Copy)`,type:t.type,style:t.style,color:t.color,scale:t.scale,position:{x:t.position.x+2,z:t.position.z+2},cwd:t.cwd,folderPath:t.folderPath,commands:t.commands,pm2:t.pm2,docker:t.docker,database:t.database,terminal:t.terminal,urls:t.urls,subordinateBuildingIds:t.subordinateBuildingIds})}}),t.urls&&t.urls.length>0)for(const i of t.urls)n.push({id:`url-${i.label}`,label:i.label,icon:e.jsx(u,{name:"link",size:14}),onClick:()=>window.open(i.url,"_blank","noopener,noreferrer")});return n.push({id:"divider-danger",label:"",divider:!0,onClick:()=>{}}),n.push({id:"delete",label:"Delete Building",icon:e.jsx(u,{name:"trash",size:14}),danger:!0,onClick:()=>x.deleteBuilding(t.id)}),n},[h,rt,Me]),tn=a.useCallback(t=>{const n=new Set(Ne.groups.map(s=>s.area.id));n.delete(t),It(n),requestAnimationFrame(()=>{const s=At.current;if(!s)return;const p=s.querySelector(`[data-area-id="${t}"]`);if(!p)return;const m=s.getBoundingClientRect(),i=p.getBoundingClientRect().top-m.top+s.scrollTop-8;s.scrollTo({top:Math.max(0,i),behavior:"smooth"})})},[Ne]);return e.jsxs("div",{ref:W,className:`flat-view ${V?"flat-view--with-inspector":""} ${f?"flat-view--has-chat":""} ${F?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(R===null&&G===null)return;const t={};return R!==null&&(t["--flat-middle-width"]=`${R}px`),G!==null&&(t["--flat-inspector-width"]=`${G}px`),t})(),children:[F&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:Re,"aria-hidden":"true"}),e.jsxs("div",{className:"flat-middle",children:[e.jsx("div",{className:"flat-middle__header",children:e.jsxs("div",{className:"flat-middle__actions",children:[e.jsx("button",{className:"flat-cta-btn flat-cta-btn--agent",onClick:q,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:O,title:"Create new boss agent",children:"+ Boss"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--area",onClick:De,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(fn,{activeAgentId:Le,onClose:bt,onSelectAgent:_t,collapsedAreas:Ut,onToggleArea:qt,agentListRef:At})})]}),e.jsx("div",{className:"flat-splitter flat-splitter--middle",role:"separator","aria-orientation":"vertical","aria-label":"Resize agents panel",title:"Drag to resize · Double-click to reset",onPointerDown:Ze,onPointerMove:ze,onPointerUp:Se,onPointerCancel:Se,onDoubleClick:ft}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":F?"Close agents sidebar":"Open agents sidebar","aria-expanded":F,onClick:Ke,children:[e.jsx(u,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),f?e.jsx(ta,{agentId:f,terminalViewMode:qe,onTerminalViewModeChange:Ye,inspectorOpen:xe,onToggleInspector:xt,onImageClick:Oe,onFileClick:Qe,onBashClick:Q,onViewMarkdown:et,onRequestClearSubordinates:tt,onOpenBuilding:Me,keyboard:oe,canNavigateBack:nt,canNavigateForward:at,onNavigateBack:o,onNavigateForward:d,agentInfoOpen:Ie,onToggleAgentInfo:Ge,onHeaderContextMenu:t=>{f&&fe({agentId:f,position:t})},onBuildingContextMenu:(t,n)=>{$({buildingId:t,position:n})}}):e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-map",children:[e.jsxs("div",{className:"flat-map__header",children:[e.jsx("span",{className:"flat-map__title",children:"🗺️ Areas"}),e.jsx("span",{className:"flat-map__hint",children:"Click an area to focus it, or an agent to chat"}),e.jsx(Un,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Ne.gridCols}, 1fr)`},children:Ne.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=je&&it?((n=Ne.positions.get(it))==null?void 0:n.row)??null:null;return Ne.groups.map(s=>{const p=s.area.id,m=Ne.positions.get(p),_=je&&it!==p;return je&&t!=null&&(m==null?void 0:m.row)===t&&p!==it?null:e.jsxs("div",{className:`flat-map-area-card${_?" flat-map-area-card--collapsed":""}`,style:{"--area-color":s.area.color,gridRow:m==null?void 0:m.row,gridColumn:m==null?void 0:m.col},onContextMenu:i=>{S&&(i.preventDefault(),i.stopPropagation(),S(p,{x:i.clientX,y:i.clientY}))},children:[e.jsxs("button",{type:"button",className:"flat-map-area-card__header",onClick:()=>je?Zt(p):tn(p),title:je?_?`Expand ${s.area.name}`:`Collapse ${s.area.name}`:`Focus ${s.area.name} in left panel`,"aria-expanded":je?!_:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:s.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:s.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:s.agents.length}),je&&e.jsx(u,{name:_?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:s.agents.map(i=>{const I=i.isBoss||i.class==="boss",j=I?st.get(i.id):void 0,E=hn(i),ue=E.usedPercent>=80?"#ff4a4a":E.usedPercent>=60?"#ff9e4a":E.usedPercent>=40?"#ffd700":"#4aff9e",b=`Context: ${(E.totalTokens/1e3).toFixed(1)}k / ${(E.contextWindow/1e3).toFixed(1)}k (${E.usedPercent}% used, ${E.freePercent}% free)`,k=i.latestTodos&&i.latestTodos.length>0||j&&j.length>0;return e.jsx(gn,{todos:i.latestTodos,subordinates:j,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${i.status}`,onClick:()=>w(i.id),onContextMenu:N=>{N.preventDefault(),N.stopPropagation(),fe({agentId:i.id,position:{x:N.clientX,y:N.clientY}})},title:k?void 0:`${I?"Boss · ":""}Open chat with ${i.name}
1
+ import{r as a,z as rn,B as Tt,u as Wt,E as on,j as e,V as cn,G as dn,H as un,J as Pt,S as y,K as Lt,L as kt,M as Dt,N as ut,O as se,P as pn,s as x,U as Ht,W as Vt,X as mn,v as Rt,w as zt,I as u,Y as fn,m as hn,Z as gn,_ as Xt,$ as Gt,a0 as xn,a1 as bn,a2 as _n,a3 as wn,a4 as vn,a5 as Cn,a6 as jn,a7 as Nn,a8 as kn,a9 as yn,aa as An,ab as In,ac as Ot,C as En,ad as Sn,ae as Mn,af as Tn,ag as Pn,ah as Ln,ai as Dn,aj as Rn,ak as zn,al as On,am as $n,an as Bn,ao as Fn,ap as Wn,aq as Hn,ar as Vn,as as Xn}from"./main-Brpf2Evy.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Gn(w){const c=a.useRef(w);c.current=w,a.useEffect(()=>{if(!rn())return;let v=null,A=!1;return Tt.addListener("backButton",()=>{c.current()==="exit"&&Tt.exitApp()}).then(S=>{A?S.remove():v=S}),()=>{A=!0,v&&(v.remove(),v=null)}},[])}const Un=a.memo(function({className:c=""}){const{t:v}=Wt(["common"]),[A,S]=on(),q=a.useRef(null),[O,De]=a.useState(null);a.useLayoutEffect(()=>{const g=q.current;if(!g)return;const Y=g.querySelector(".view-mode-toggle__btn--active");Y&&De({left:Y.offsetLeft,width:Y.offsetWidth})},[A]);const le=a.useCallback(g=>{if(g!==A){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:g}})),g==="3d"){requestAnimationFrame(()=>S(g));return}S(g)}},[A,S]);return e.jsxs("div",{className:`view-mode-toggle ${c}`,ref:q,children:[O&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:O.left,width:O.width}}),cn.map(g=>e.jsxs("button",{className:`view-mode-toggle__btn ${A===g?"view-mode-toggle__btn--active":""}`,onClick:()=>le(g),title:v(`common:viewMode.descriptions.${g}`),children:[e.jsxs("span",{className:"view-mode-toggle__icon",children:[g==="2d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]}),g==="3d"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),e.jsx("path",{d:"M2 17l10 5 10-5"}),e.jsx("path",{d:"M2 12l10 5 10-5"})]}),g==="flat"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),e.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]}),g==="dashboard"&&e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"5",rx:"1"}),e.jsx("rect",{x:"14",y:"12",width:"7",height:"9",rx:"1"}),e.jsx("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1"})]})]}),e.jsx("span",{className:"view-mode-toggle__label",children:v(`common:viewMode.labels.${g}`)})]},g))]})}),pt=3,mt=280,$t=320,Nt=240,Bt=64,qn=["simple","chat","advanced"],Yn={simple:"Simple",chat:"Chat",advanced:"Advanced"},Kn={simple:"○",chat:"◐",advanced:"◉"},Zn={simple:"Simple view — clean messages only",chat:"Chat view — assistant replies (no tool calls)",advanced:"Advanced view — everything including tools"},Ft="flat-clear-context";function Jn(w){const c=w.split("/").filter(Boolean);return c.length===0?w:c.slice(-2).join("/")}function Qn(w){if(w.provider==="codex"){const q=w.codexModel||"gpt-5.3-codex",O=Hn[q];return{model:(O==null?void 0:O.label)||q}}if(w.provider==="opencode")return{model:w.opencodeModel||"opencode"};const c=w.model||"sonnet",v=Xn[c],A=w.effort,S=A?Vn[A]:void 0;return{model:(v==null?void 0:v.label)||c,effort:S==null?void 0:S.label}}function ea(w,c){if(c.type==="rectangle"&&c.width&&c.height){const v=c.width/2,A=c.height/2;return w.x>=c.center.x-v&&w.x<=c.center.x+v&&w.z>=c.center.z-A&&w.z<=c.center.z+A}if(c.type==="circle"&&c.radius){const v=w.x-c.center.x,A=w.z-c.center.z;return v*v+A*A<=c.radius*c.radius}return!1}const ta=Sn.memo(function({agentId:c,terminalViewMode:v,onTerminalViewModeChange:A,inspectorOpen:S,onToggleInspector:q,onImageClick:O,onFileClick:De,onBashClick:le,onViewMarkdown:g,onRequestClearSubordinates:Y,onOpenBuilding:ye,keyboard:We,canNavigateBack:He,canNavigateForward:Ve,onNavigateBack:pe,onNavigateForward:ie,agentInfoOpen:me,onToggleAgentInfo:Xe,onHeaderContextMenu:K,onBuildingContextMenu:fe}){var ce,Pe,ne,st;const h=Mn(c),$=Vt(),B=a.useRef(null),Ae=a.useRef(null);a.useEffect(()=>{const l=Ae.current;if(!l)return;const r=d=>{d.button===3?(d.preventDefault(),d.stopPropagation(),pe()):d.button===4&&(d.preventDefault(),d.stopPropagation(),ie())},o=d=>{(d.button===3||d.button===4)&&d.preventDefault()};return l.addEventListener("mouseup",r),l.addEventListener("mousedown",o),()=>{l.removeEventListener("mouseup",r),l.removeEventListener("mousedown",o)}},[pe,ie]),a.useEffect(()=>{const l=Ae.current;if(!l)return;let r=0,o=0,d=0;const de=250,Ce=600,Le=80,bt=1.5,_t=P=>{let M=P instanceof HTMLElement?P:null;for(;M&&M!==l;){const lt=window.getComputedStyle(M).overflowX;if((lt==="auto"||lt==="scroll")&&M.scrollWidth>M.clientWidth)return!0;M=M.parentElement}return!1},V=P=>{const M=Date.now();if(M<d){P.preventDefault();return}if(Math.abs(P.deltaX)<=Math.abs(P.deltaY)*bt){r=0;return}if(_t(P.target)){r=0;return}M-o>de&&(r=0),o=M,r+=P.deltaX,r<=-Le?(r=0,d=M+Ce,P.preventDefault(),pe()):r>=Le&&(r=0,d=M+Ce,P.preventDefault(),ie())};return l.addEventListener("wheel",V,{passive:!1}),()=>l.removeEventListener("wheel",V)},[pe,ie]);const Ie=Ht(),he=a.useMemo(()=>{if(!h)return null;const l=new Set,r=[];for(const o of Ie.values())o.archived||o.directories.length===0||o.assignedAgentIds.includes(c)&&(l.add(o.id),r.push(o));for(const o of Ie.values())o.archived||o.directories.length===0||l.has(o.id)||ea({x:h.position.x,z:h.position.z},o)&&(l.add(o.id),r.push(o));return r.length===0?null:r.flatMap(o=>o.directories.filter(d=>d&&d.trim().length>0).map(d=>({areaId:o.id,areaName:o.name,dir:d})))},[h,c,Ie]),{branches:Ge,fetchRemote:Ue,fetchingDirs:qe}=Tn(he),ge=a.useMemo(()=>{var o;const l=x.getAreaForAgent(c);if(!l)return[];const r=[];for(const d of $.values())d.type==="terminal"&&x.isPositionInArea(d.position,l)&&r.push({id:d.id,name:d.name,hasUrl:!!((o=d.terminalStatus)!=null&&o.url)});return r},[c,$]),Ye=a.useMemo(()=>{var o;const l=x.getAreaForAgent(c);if(!l)return[];const r=[];for(const d of $.values())d.type==="server"&&((o=d.pm2)!=null&&o.enabled)&&x.isPositionInArea(d.position,l)&&r.push({id:d.id,name:d.name});return r},[c,$]),xe=a.useMemo(()=>{const l=x.getAreaForAgent(c);if(!l)return[];const r=[];for(const o of $.values())o.type==="database"&&o.database&&x.isPositionInArea(o.position,l)&&r.push({id:o.id,name:o.name});return r},[c,$]),[,be]=a.useReducer(l=>l+1,0),F=((ce=B.current)==null?void 0:ce.search.searchMode)??!1,re=a.useCallback(()=>{var l;(l=B.current)==null||l.search.toggleSearch(),be()},[]),Ke=Pn(),Re=Ke.isPending(Ft),[W,X]=a.useState(null),R=W?$.get(W):null,{height:Ee,onResizeStart:G}=Ln(),[U,Z]=a.useState(()=>kt(y.GIT_PANEL_OPEN,!1)),[z,Ze]=a.useState(()=>kt(y.BUILDINGS_PANEL_OPEN,!1)),[_e,ze]=a.useState(!1),Se=a.useCallback(()=>{ze(l=>{const r=!l;return r&&Dn.setEnabled(!0),r})},[]),ft=a.useCallback(()=>ze(!1),[]),ht=a.useCallback(()=>{Z(l=>{const r=!l;return se(y.GIT_PANEL_OPEN,r),r})},[]),we=a.useCallback(()=>{Ze(l=>{const r=!l;return se(y.BUILDINGS_PANEL_OPEN,r),r})},[]),gt=a.useCallback(()=>{Z(!1),se(y.GIT_PANEL_OPEN,!1)},[]),Je=a.useCallback(()=>{Ze(!1),se(y.BUILDINGS_PANEL_OPEN,!1)},[]),xt=Rn();a.useEffect(()=>{if(!W)return;ge.some(r=>r.id===W)||X(null)},[W,ge]);const[J,oe]=a.useState(!1),Oe=a.useRef(null);if(a.useEffect(()=>{if(!J)return;const l=r=>{Oe.current&&!Oe.current.contains(r.target)&&oe(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[J]),!h)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const Q=h.contextStats,Qe=!!Q,et=Q?Q.totalTokens:h.contextUsed||0,tt=Q?Q.contextWindow:h.contextLimit||2e5,Me=Q?Q.usedPercent:Math.round(et/tt*100),f=Math.max(0,Math.min(100,Me)),ee=Math.round(f*10)/10,H=Math.round((100-f)*10)/10,ve=f>=80?"#ff4a4a":f>=60?"#ff9e4a":f>=40?"#ffd700":"#4aff9e",$e=(et/1e3).toFixed(1),nt=(tt/1e3).toFixed(1),te=h.cwd,at=te?Jn(te):null,Te=((Pe=h.subordinateIds)==null?void 0:Pe.length)||0,Be=Te>0;return e.jsxs("div",{ref:Ae,className:`flat-terminal-wrapper ${U||z||_e?"flat-terminal-wrapper--with-side-panel":""}`,children:[e.jsxs("div",{className:"flat-terminal-wrapper__header",children:[e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__header-main ${me?"flat-terminal-wrapper__header-main--active":""}`,onClick:Xe,onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),K({x:l.clientX,y:l.clientY})},title:me?"Hide agent info":"Show agent info","aria-pressed":me,children:[e.jsx(Xt,{agent:h,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:h.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:Gt(h.status)},children:h.status})]}),h.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:h.taskLabel,children:["📋 ",h.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:h.provider==="codex"?"/assets/codex.png":h.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:h.provider,className:"flat-terminal-wrapper__header-provider-icon",title:h.provider==="codex"?"Codex Agent":h.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:l,effort:r}=Qn(h);return e.jsxs("span",{className:"flat-terminal-wrapper__header-model-chip",title:r?`Model: ${l} · Effort: ${r}`:`Model: ${l}`,children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-name",children:l}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flat-terminal-wrapper__header-model-sep","aria-hidden":"true",children:"·"}),e.jsx("span",{className:"flat-terminal-wrapper__header-model-effort",children:r})]})]})})()]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__header-meta",children:[e.jsx("div",{className:"flat-terminal-wrapper__view-mode",role:"group","aria-label":"Message view mode",children:qn.map(l=>e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__view-mode-btn ${v===l?"flat-terminal-wrapper__view-mode-btn--active":""}`,onClick:()=>A(l),title:Zn[l],"aria-pressed":v===l,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:Kn[l]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:Yn[l]})]},l))}),e.jsxs("div",{className:"flat-terminal-wrapper__actions",role:"group","aria-label":"Terminal actions",children:[e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:pe,disabled:!He,title:"Back to previous agent","aria-label":"Back to previous agent",children:e.jsx(u,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__action-btn",onClick:ie,disabled:!Ve,title:"Forward to next agent","aria-label":"Forward to next agent",children:e.jsx(u,{name:"arrow-right",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${F?"flat-terminal-wrapper__action-btn--active":""}`,onClick:re,title:F?"Close search":"Search messages","aria-pressed":F,children:e.jsx(u,{name:F?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${Re?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>Ke.handleClick(Ft,()=>{var l;x.clearContext(c),(l=B.current)==null||l.historyLoader.clearHistory()}),title:Re?"Click again to confirm clear context":"Clear context",children:e.jsx(u,{name:Re?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${U?"flat-terminal-wrapper__action-btn--active":""}`,onClick:ht,title:U?"Hide git panel":"Show git changes","aria-pressed":U,children:e.jsx(u,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${z?"flat-terminal-wrapper__action-btn--active":""}`,onClick:we,title:z?"Hide buildings panel":"Show area buildings","aria-pressed":z,children:e.jsx(u,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:Oe,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${J?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>oe(l=>!l),title:"More actions","aria-expanded":J,children:"⋮"}),J&&e.jsxs("div",{className:"flat-terminal-wrapper__more-menu",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:`flat-terminal-wrapper__more-item ${_e?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{Se(),oe(!1)},title:_e?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(u,{name:"bug",size:14}),e.jsx("span",{children:_e?"Hide Debug Panel":"Show Debug Panel"})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item",onClick:()=>{x.collapseContext(c),oe(!1)},disabled:h.status!=="idle",title:h.status!=="idle"?"Agent must be idle to collapse context":"Collapse context",children:[e.jsx(u,{name:"package",size:14}),e.jsx("span",{children:"Collapse context"})]}),Be&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{Y(c,Te),oe(!1)},children:[e.jsx(u,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",Te," subordinate",Te===1?"":"s"]})]}),e.jsx("div",{className:"flat-terminal-wrapper__more-divider"}),e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{x.killAgent(c),oe(!1)},children:[e.jsx(u,{name:"cross",size:14}),e.jsx("span",{children:"Remove agent"})]})]})]})]}),e.jsxs("button",{type:"button",className:`flat-terminal-wrapper__inspector-toggle ${S?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:q,title:S?"Hide inspector panel":"Show inspector panel","aria-label":S?"Hide inspector panel":"Show inspector panel","aria-pressed":S,children:[e.jsx("span",{className:"flat-terminal-wrapper__inspector-icon","aria-hidden":"true",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"}),e.jsx("line",{x1:"10",y1:"2.5",x2:"10",y2:"13.5"})]})}),e.jsx("span",{className:"flat-terminal-wrapper__inspector-label",children:"Inspector"})]}),e.jsx("button",{type:"button",className:"flat-terminal-wrapper__close",onClick:()=>x.deselectAll(),title:"Close chat","aria-label":"Close chat",children:e.jsx(u,{name:"cross",size:14})})]})]}),e.jsx(zn,{ref:B,agentId:c,agent:h,viewMode:v,isOpen:!0,onImageClick:O,onFileClick:De,onBashClick:le,onViewMarkdown:g,keyboard:We,hasModalOpen:!1}),R&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"guake-bottom-terminal-resize",onMouseDown:G,role:"separator","aria-orientation":"horizontal","aria-label":"Resize embedded terminal"}),e.jsxs("div",{className:"flat-bottom-panel",role:"region","aria-label":`Embedded terminal: ${R.name}`,style:{height:Ee},children:[e.jsxs("div",{className:"flat-bottom-panel__header",children:[e.jsxs("span",{className:"flat-bottom-panel__title",children:[e.jsx(u,{name:"terminal",size:12}),e.jsx("span",{children:R.name}),!((ne=R.terminalStatus)!=null&&ne.url)&&e.jsx("span",{className:"flat-bottom-panel__muted",children:"(starting...)"})]}),e.jsx("button",{type:"button",className:"flat-bottom-panel__close",onClick:()=>X(null),title:"Close embedded terminal","aria-label":"Close embedded terminal",children:e.jsx(u,{name:"cross",size:12})})]}),e.jsx("div",{className:"flat-bottom-panel__body",children:(st=R.terminalStatus)!=null&&st.url?e.jsx(On,{terminalUrl:R.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."})})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[h.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(u,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),te&&at&&e.jsxs("span",{className:"flat-terminal-wrapper__cwd",title:`Open in file explorer: ${te}`,"aria-label":`Open ${te} in file explorer`,role:"button",tabIndex:0,onClick:()=>x.openFileExplorer(te),onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),x.openFileExplorer(te))},children:[e.jsx("span",{className:"flat-terminal-wrapper__cwd-icon",children:e.jsx(u,{name:"folder",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__cwd-text",children:at})]}),he&&he.map(({areaId:l,areaName:r,dir:o})=>{const d=Ge.get(o),de=qe.has(o),Ce=o.split("/").filter(Boolean).pop()||o;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${r}: ${o}${d?` (${d.branch}${d.ahead?` ↑${d.ahead}`:""}${d.behind?` ↓${d.behind}`:""})`:""}`,onClick:()=>x.openFileExplorerForAreaFolder(l,o),children:[e.jsx(u,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-terminal-wrapper__area-dir-name",children:Ce}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(u,{name:"git-branch",size:10})," ",d.branch]}),d.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${d.ahead} ahead`,children:[e.jsx(u,{name:"arrow-up",size:9}),d.ahead]}),d.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${d.behind} behind`,children:[e.jsx(u,{name:"arrow-down",size:9}),d.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${de?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Le=>{Le.stopPropagation(),Ue(o)},children:e.jsx(u,{name:de?"hourglass":"download",size:12})})]})]},`${l}:${o}`)}),e.jsxs("span",{className:"flat-terminal-wrapper__context",onClick:()=>x.setContextModalAgentId(c),title:Qe?`Context usage: ${$e}k / ${nt}k tokens (${ee}% used). Click to view stats.`:"Click to fetch context stats",children:[e.jsx("span",{className:"flat-terminal-wrapper__context-icon",children:e.jsx(u,{name:"dashboard",size:12})}),e.jsx("span",{className:"flat-terminal-wrapper__context-label",children:"Ctx:"}),e.jsx("span",{className:"flat-terminal-wrapper__context-bar",children:e.jsx("span",{className:"flat-terminal-wrapper__context-bar-fill",style:{width:`${f}%`,backgroundColor:ve}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:ve},children:[$e,"k/",nt,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",H,"% free)"]}),!Qe&&e.jsx("span",{className:"flat-terminal-wrapper__context-warning",title:"No context stats yet",children:e.jsx(u,{name:"warn",size:12})})]}),e.jsx("div",{className:"flat-terminal-wrapper__statusbar-spacer","aria-hidden":"true"}),ge.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area terminals",children:ge.map(l=>{const r=W===l.id;return e.jsx("button",{type:"button",className:`flat-terminal-wrapper__building-btn ${r?"flat-terminal-wrapper__building-btn--active":""} ${l.hasUrl?"":"flat-terminal-wrapper__building-btn--offline"}`,title:`${r?"Hide":"Show"} terminal: ${l.name}${l.hasUrl?"":" (starting...)"}`,onClick:()=>{if(r){X(null);return}l.hasUrl||x.sendBuildingCommand(l.id,"start"),X(l.id)},onContextMenu:o=>{o.preventDefault(),o.stopPropagation(),fe(l.id,{x:o.clientX,y:o.clientY})},children:e.jsx(u,{name:"terminal",size:14})},l.id)})}),Ye.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:Ye.map(l=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open logs: ${l.name}`,onClick:()=>ye(l.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),fe(l.id,{x:r.clientX,y:r.clientY})},children:e.jsx(u,{name:"scroll",size:14})},l.id))}),xe.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area databases",children:xe.map(l=>e.jsx("button",{type:"button",className:"flat-terminal-wrapper__building-btn",title:`Open database: ${l.name}`,onClick:()=>ye(l.id),onContextMenu:r=>{r.preventDefault(),r.stopPropagation(),fe(l.id,{x:r.clientX,y:r.clientY})},children:e.jsx(u,{name:"hard-drives",size:14})},l.id))}),e.jsx("div",{className:"flat-terminal-wrapper__theme",children:e.jsx($n,{})})]}),U&&e.jsx(Bn,{agentId:c,agents:xt,onClose:gt,branchInfoMap:Ge,fetchRemote:Ue,fetchingDirs:qe}),z&&e.jsx(Fn,{agentId:c,onClose:Je}),_e&&e.jsx(Wn,{agentId:c,onClose:ft})]})});function la({onAgentClick:w,onBuildingClick:c,onBuildingDoubleClick:v,onBuildingPopup:A,onAreaContextMenu:S,onOpenSpawnModal:q,onOpenBossSpawnModal:O,onOpenAreaModal:De}){const{t:le}=Wt(["common"]),g=dn(),Y=un(),[ye,We]=a.useState(null),[He,Ve]=a.useState(null),[pe,ie]=a.useState(null),[me,Xe]=a.useState(null),[K,fe]=a.useState(null),[h,$]=a.useState(null),[B,Ae]=a.useState(null),[Ie,he]=a.useState(!1),Ge=a.useCallback(()=>{he(t=>!t)},[]),Ue=a.useCallback(()=>{he(!1)},[]),[qe,ge]=a.useState(()=>{const t=Pt(y.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Ye=a.useCallback(t=>{ge(t),Lt(y.VIEW_MODE,t)},[]);a.useEffect(()=>{const t=n=>{if(n.key!==y.VIEW_MODE)return;const s=n.newValue;(s==="simple"||s==="chat"||s==="advanced")&&ge(s)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);const[xe,be]=a.useState(()=>kt(y.FLAT_INSPECTOR_OPEN,!1)),[F,re]=a.useState(!1),Ke=a.useCallback(()=>re(t=>!t),[]),Re=a.useCallback(()=>re(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:F}}))},[F]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:xe}}))},[xe]),a.useEffect(()=>{const t=()=>re(_=>!_),n=()=>{be(_=>{const i=!_;return se(y.FLAT_INSPECTOR_OPEN,i),i})},s=()=>{re(!1),be(!1),se(y.FLAT_INSPECTOR_OPEN,!1)},p=()=>re(!1),m=()=>{be(!1),se(y.FLAT_INSPECTOR_OPEN,!1)};return window.addEventListener("tide-toggle-flat-agents-drawer",t),window.addEventListener("tide-toggle-flat-inspector",n),window.addEventListener("tide-close-flat-side-views",s),window.addEventListener("tide-close-flat-agents-drawer-only",p),window.addEventListener("tide-close-flat-inspector-only",m),()=>{window.removeEventListener("tide-toggle-flat-agents-drawer",t),window.removeEventListener("tide-toggle-flat-inspector",n),window.removeEventListener("tide-close-flat-side-views",s),window.removeEventListener("tide-close-flat-agents-drawer-only",p),window.removeEventListener("tide-close-flat-inspector-only",m)}},[]);const W=a.useRef(null),X=a.useRef(null),[R,Ee]=a.useState(()=>{const t=Dt(y.FLAT_MIDDLE_WIDTH,0);return t>=mt?t:null}),[G,U]=a.useState(()=>{const t=Dt(y.FLAT_INSPECTOR_WIDTH,0);return t>=Nt?t:null}),Z=a.useCallback(t=>{if(typeof window>"u")return t;const n=G!==null?pt+G:0,s=window.innerWidth-Bt-pt-$t-n;return Math.max(mt,Math.min(Math.max(s,mt),t))},[G]),z=a.useCallback(t=>{var m;if(typeof window>"u")return t;const n=(m=W.current)==null?void 0:m.querySelector(".flat-middle"),s=(n==null?void 0:n.getBoundingClientRect().width)??mt,p=window.innerWidth-Bt-s-pt-$t-pt;return Math.max(Nt,Math.min(Math.max(p,Nt),t))},[]);a.useEffect(()=>{if(R===null&&G===null)return;const t=()=>{Ee(n=>{if(n===null)return n;const s=Z(n);return s===n?n:s}),U(n=>{if(n===null)return n;const s=z(n);return s===n?n:s})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[R,G,Z,z]);const Ze=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=W.current)==null?void 0:s.querySelector(".flat-middle");n&&(t.currentTarget.setPointerCapture(t.pointerId),X.current={kind:"middle",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),_e=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=W.current)==null?void 0:s.querySelector(".flat-inspector");n&&(t.currentTarget.setPointerCapture(t.pointerId),X.current={kind:"inspector",startX:t.clientX,startWidth:n.getBoundingClientRect().width,pointerId:t.pointerId},document.body.classList.add("flat-splitter-dragging"))},[]),ze=a.useCallback(t=>{const n=X.current;if(!n||t.pointerId!==n.pointerId)return;const s=t.clientX-n.startX;n.kind==="middle"?Ee(Z(n.startWidth+s)):U(z(n.startWidth-s))},[Z,z]),Se=a.useCallback(t=>{const n=X.current;if(!n||t.pointerId!==n.pointerId)return;try{t.currentTarget.releasePointerCapture(t.pointerId)}catch{}if(X.current=null,document.body.classList.remove("flat-splitter-dragging"),!(Math.abs(t.clientX-n.startX)>2))return;const p=t.clientX-n.startX;if(n.kind==="middle"){const m=Z(n.startWidth+p);Ee(m),ut(y.FLAT_MIDDLE_WIDTH,m)}else{const m=z(n.startWidth-p);U(m),ut(y.FLAT_INSPECTOR_WIDTH,m)}},[Z,z]),ft=a.useCallback(()=>{Ee(null),ut(y.FLAT_MIDDLE_WIDTH,0)},[]),ht=a.useCallback(()=>{U(null),ut(y.FLAT_INSPECTOR_WIDTH,0)},[]),[we,gt]=a.useState(()=>Pt(y.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),Je=a.useCallback(t=>{gt(t),Lt(y.FLAT_INSPECTOR_VIEW,t)},[]),xt=a.useCallback(()=>{be(t=>{const n=!t;return se(y.FLAT_INSPECTOR_OPEN,n),n})},[]),J=a.useCallback(()=>{be(!1),se(y.FLAT_INSPECTOR_OPEN,!1)},[]),oe=pn(),Oe=a.useCallback((t,n)=>{We({url:t,name:n})},[]),Q=a.useCallback((t,n)=>{Ve({command:t,output:n,isLive:!1})},[]),Qe=a.useCallback((t,n)=>{x.setFileViewerPath(t,n)},[]),et=a.useCallback(t=>{ie(t)},[]),tt=a.useCallback((t,n)=>{Xe({agentId:t,count:n})},[]),Me=a.useCallback(t=>{v?v(t):c(t)},[c,v]),f=a.useMemo(()=>Y.size>0?Array.from(Y)[0]:null,[Y]);a.useEffect(()=>{he(!1)},[f]);const ee=a.useRef([]),H=a.useRef(-1),ve=a.useRef(!1),$e=a.useRef(null),[nt,te]=a.useState(!1),[at,Te]=a.useState(!1),Be=a.useRef(!1),ce=a.useRef(null),Pe=a.useRef(!1),ne=a.useMemo(()=>new Set(g.map(t=>t.id)),[g]),st=a.useMemo(()=>{const t=new Map(g.map(s=>[s.id,s])),n=new Map;for(const s of g)if((s.isBoss||s.class==="boss")&&s.subordinateIds&&s.subordinateIds.length>0){const p=s.subordinateIds.map(m=>t.get(m)).filter(m=>m!==void 0);p.length>0&&n.set(s.id,p)}return n},[g]),l=a.useCallback(()=>{const t=ee.current,n=H.current;te(n>0),Te(n>=0&&n<t.length-1)},[]),r=a.useCallback(t=>{const n=ee.current;if(n.length===0)return;let s=H.current+t;for(;s>=0&&s<n.length;){const p=n[s];if(ne.has(p)){ve.current=!0,H.current=s,l(),x.selectAgent(p);return}s+=t}},[ne,l]),o=a.useCallback(()=>r(-1),[r]),d=a.useCallback(()=>r(1),[r]);Gn(a.useCallback(()=>{const t=ee.current,n=H.current;return t.length>0&&n>0?(r(-1),"handled"):"exit"},[r]));const de=a.useCallback((t,n)=>{if(typeof window>"u")return;const s=window.history.state,m={...typeof s=="object"&&s!==null?s:{},__flatAgentNav:{agentId:t}};n==="replace"?window.history.replaceState(m,"",window.location.href):window.history.pushState(m,"",window.location.href)},[]);a.useEffect(()=>{if(!f){Be.current=!1,ce.current=null;return}if(!Be.current){de(f,"replace"),Be.current=!0,ce.current=f;return}if(Pe.current){Pe.current=!1,ce.current=f;return}ce.current!==f&&(de(f,"push"),ce.current=f)},[f,de]),a.useEffect(()=>{const t=n=>{var _,i;const s=(i=(_=n.state)==null?void 0:_.__flatAgentNav)==null?void 0:i.agentId;if(!s||typeof s!="string"||!ne.has(s)||s===f)return;Pe.current=!0,ve.current=!0;const p=ee.current,m=p.lastIndexOf(s);m>=0?H.current=m:(p.push(s),H.current=p.length-1),l(),x.selectAgent(s)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ne,f,l]),a.useEffect(()=>{if(!f){ee.current=[],H.current=-1,l();return}if($e.current=f,ve.current){ve.current=!1,l();return}const t=ee.current,n=H.current;if(n>=0&&t[n]===f){l();return}const s=n<t.length-1?t.slice(0,n+1):t.slice();s.push(f),s.length>100&&s.shift(),ee.current=s,H.current=s.length-1,l()},[f,l]);const Ce=a.useCallback(t=>{w(t),re(!1)},[w]),Le=f??"",bt=a.useCallback(()=>{},[]),_t=a.useCallback(t=>{Ce(t)},[Ce]),V=xe,[P,M]=a.useState(V),[lt,yt]=a.useState(V);a.useEffect(()=>{if(V){M(!0);return}yt(!1);const t=setTimeout(()=>M(!1),240);return()=>clearTimeout(t)},[V]),a.useEffect(()=>{if(!P||!V)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>yt(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[P,V]);const At=a.useRef(null);a.useEffect(()=>{if(f)return;const t=n=>{if(n.key!==" "&&n.key!=="Backspace")return;const s=n.target;if(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.isContentEditable)return;const p=$e.current;!p||!ne.has(p)||(n.preventDefault(),x.selectAgent(p))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[f,ne]);const[Ut,It]=a.useState(new Set),qt=a.useCallback(t=>{It(n=>{const s=new Set(n);return s.has(t)?s.delete(t):s.add(t),s})},[]),[je,Yt]=a.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches);a.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 768px)"),n=s=>Yt(s.matches);return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[]);const[it,Kt]=a.useState(null),Zt=a.useCallback(t=>{Kt(n=>n===t?null:t)},[]),wt=Ht(),rt=Vt(),[Jt]=mn(),Ne=a.useMemo(()=>{const t=new Map,n=[];for(const b of g){const k=x.getAreaForAgent(b.id);if(!Rt((k==null?void 0:k.id)??null))continue;if(!k||k.archived){n.push(b);continue}const N=t.get(k.id);N?N.push(b):t.set(k.id,[b])}const s=new Map,p=[];for(const b of rt.values()){let k=!1;for(const N of wt.values())if(!N.archived&&zt(N.id)&&x.isPositionInArea(b.position,N)){const ae=s.get(N.id);ae?ae.push(b):s.set(N.id,[b]),k=!0;break}!k&&Rt(null)&&p.push(b)}const m=[];for(const[,b]of wt){if(b.archived||!zt(b.id))continue;const k=t.get(b.id),N=s.get(b.id)??[];(k&&k.length>0||N.length>0)&&m.push({area:b,agents:k??[],buildings:N})}(n.length>0||p.length>0)&&m.push({area:{id:"__unassigned__",name:"Unassigned",color:"#6272a4",center:{x:0,z:0},type:"circle",radius:0,directories:[],archived:!1,assignedAgentIds:[],zIndex:0},agents:n,buildings:p});const _=m.filter(b=>b.area.id!=="__unassigned__"),i=m.filter(b=>b.area.id==="__unassigned__");let I=1,j=1;const E=new Map;if(_.length>1){let b=1/0,k=-1/0,N=1/0,ae=-1/0;for(const L of _)b=Math.min(b,L.area.center.x),k=Math.max(k,L.area.center.x),N=Math.min(N,L.area.center.z),ae=Math.max(ae,L.area.center.z);const ot=k-b||1,ct=ae-N||1;if(_.length<=4){I=_.length,j=1;const L=[..._].sort((D,vt)=>D.area.center.x-vt.area.center.x);for(let D=0;D<L.length;D++)E.set(L[D].area.id,{row:1,col:D+1})}else{const L=[..._].sort((C,T)=>C.area.center.x-T.area.center.x),D=[];for(let C=1;C<L.length;C++)D.push(L[C].area.center.x-L[C-1].area.center.x);const vt=D.reduce((C,T)=>C+T,0)/D.length||1;let Et=1;for(const C of D)C>vt*1.3&&Et++;I=Math.max(2,Math.min(Et,_.length));const Ct=[..._].sort((C,T)=>C.area.center.z-T.area.center.z),dt=[];for(let C=1;C<Ct.length;C++)dt.push(Ct[C].area.center.z-Ct[C-1].area.center.z);const nn=dt.reduce((C,T)=>C+T,0)/dt.length||1;let St=1;for(const C of dt)C>nn*1.3&&St++;j=Math.max(2,Math.min(St,_.length)),I=Math.max(I,Math.ceil(_.length/j)),j=Math.max(j,Math.ceil(_.length/I));const an=ot/I,sn=ct/j,jt=new Set;for(const C of _){let T=Math.min(I-1,Math.max(0,Math.floor((C.area.center.x-b)/an))),ke=Math.min(j-1,Math.max(0,Math.floor((C.area.center.z-N)/sn))),Fe=`${ke},${T}`,Mt=0;const ln=j*I;for(;jt.has(Fe)&&Mt<ln;)T++,T>=I&&(T=0,ke=(ke+1)%j),Fe=`${ke},${T}`,Mt++;jt.has(Fe)&&(ke=j,T=0,Fe=`${ke},${T}`,j++),jt.add(Fe),E.set(C.area.id,{row:ke+1,col:T+1})}}}const ue=b=>{b.sort((k,N)=>{var ot,ct,L,D;const ae=(((ot=k.position)==null?void 0:ot.z)??0)-(((ct=N.position)==null?void 0:ct.z)??0);return ae!==0?ae:(((L=k.position)==null?void 0:L.x)??0)-(((D=N.position)==null?void 0:D.x)??0)})};for(const b of _)ue(b.agents);for(const b of i)ue(b.agents);return{groups:[..._,...i],gridCols:I,gridRows:j,positions:E}},[g,wt,rt,Jt]),Qt=a.useMemo(()=>{if(!K)return[];const t=g.find(n=>n.id===K.agentId);return t?[{id:"edit-agent",label:"Edit Agent",icon:e.jsx(u,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:open-agent-edit",{detail:{agentId:t.id}}))}},{id:"open-chat",label:"Open Chat",icon:e.jsx(u,{name:"chat",size:14}),onClick:()=>w(t.id)},{id:"delete-agent",label:"Delete Agent",icon:e.jsx(u,{name:"trash",size:14}),danger:!0,onClick:()=>{Ae({agentId:t.id,name:t.name})}}]:[]},[K,g,w]),en=a.useMemo(()=>{var _;if(!h)return[];const t=rt.get(h.buildingId);if(!t)return[];const n=[],s=t.type==="server"||t.type==="docker"||t.type==="terminal",p=t.status==="running",m=t.type==="boss";if(n.push({id:"open",label:t.type==="database"?"Open Database":t.type==="folder"?"Open Folder":t.type==="boss"?"View Boss Logs":t.type==="terminal"?"Open Terminal":t.type==="server"&&((_=t.pm2)!=null&&_.enabled)?"View PM2 Logs":"Open",icon:e.jsx(u,{name:t.type==="database"?"database":t.type==="folder"?"folder":t.type==="terminal"?"terminal":"eye",size:14}),onClick:()=>Me(t.id)}),s&&(p||n.push({id:"start",label:"Start",icon:e.jsx(u,{name:"play",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"start")}),p&&(n.push({id:"restart",label:"Restart",icon:e.jsx(u,{name:"refresh",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"restart")}),n.push({id:"stop",label:"Stop",icon:e.jsx(u,{name:"stop",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"stop")}))),m&&t.subordinateBuildingIds&&t.subordinateBuildingIds.length>0&&(n.push({id:"start-all",label:"Start All Subordinates",icon:e.jsx(u,{name:"launch",size:14}),onClick:()=>{for(const i of t.subordinateBuildingIds)x.sendBuildingCommand(i,"start")}}),n.push({id:"stop-all",label:"Stop All Subordinates",icon:e.jsx(u,{name:"pause",size:14}),onClick:()=>{for(const i of t.subordinateBuildingIds)x.sendBuildingCommand(i,"stop")}}),n.push({id:"restart-all",label:"Restart All Subordinates",icon:e.jsx(u,{name:"restart",size:14}),onClick:()=>{for(const i of t.subordinateBuildingIds)x.sendBuildingCommand(i,"restart")}})),s&&n.push({id:"health-check",label:"Health Check",icon:e.jsx(u,{name:"health",size:14}),onClick:()=>x.sendBuildingCommand(t.id,"healthCheck")}),n.push({id:"divider-edit",label:"",divider:!0,onClick:()=>{}}),n.push({id:"edit",label:"Edit Building",icon:e.jsx(u,{name:"edit",size:14}),onClick:()=>{window.dispatchEvent(new CustomEvent("tide:building-edit",{detail:{buildingId:t.id}}))}}),n.push({id:"clone",label:"Clone Building",icon:e.jsx(u,{name:"copy",size:14}),onClick:()=>{x.createBuilding({name:`${t.name} (Copy)`,type:t.type,style:t.style,color:t.color,scale:t.scale,position:{x:t.position.x+2,z:t.position.z+2},cwd:t.cwd,folderPath:t.folderPath,commands:t.commands,pm2:t.pm2,docker:t.docker,database:t.database,terminal:t.terminal,urls:t.urls,subordinateBuildingIds:t.subordinateBuildingIds})}}),t.urls&&t.urls.length>0)for(const i of t.urls)n.push({id:`url-${i.label}`,label:i.label,icon:e.jsx(u,{name:"link",size:14}),onClick:()=>window.open(i.url,"_blank","noopener,noreferrer")});return n.push({id:"divider-danger",label:"",divider:!0,onClick:()=>{}}),n.push({id:"delete",label:"Delete Building",icon:e.jsx(u,{name:"trash",size:14}),danger:!0,onClick:()=>x.deleteBuilding(t.id)}),n},[h,rt,Me]),tn=a.useCallback(t=>{const n=new Set(Ne.groups.map(s=>s.area.id));n.delete(t),It(n),requestAnimationFrame(()=>{const s=At.current;if(!s)return;const p=s.querySelector(`[data-area-id="${t}"]`);if(!p)return;const m=s.getBoundingClientRect(),i=p.getBoundingClientRect().top-m.top+s.scrollTop-8;s.scrollTo({top:Math.max(0,i),behavior:"smooth"})})},[Ne]);return e.jsxs("div",{ref:W,className:`flat-view ${V?"flat-view--with-inspector":""} ${f?"flat-view--has-chat":""} ${F?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(R===null&&G===null)return;const t={};return R!==null&&(t["--flat-middle-width"]=`${R}px`),G!==null&&(t["--flat-inspector-width"]=`${G}px`),t})(),children:[F&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:Re,"aria-hidden":"true"}),e.jsxs("div",{className:"flat-middle",children:[e.jsx("div",{className:"flat-middle__header",children:e.jsxs("div",{className:"flat-middle__actions",children:[e.jsx("button",{className:"flat-cta-btn flat-cta-btn--agent",onClick:q,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:O,title:"Create new boss agent",children:"+ Boss"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--area",onClick:De,title:"Create new area",children:"+ Area"})]})}),e.jsx("div",{className:"flat-middle__content",children:e.jsx(fn,{activeAgentId:Le,onClose:bt,onSelectAgent:_t,collapsedAreas:Ut,onToggleArea:qt,agentListRef:At})})]}),e.jsx("div",{className:"flat-splitter flat-splitter--middle",role:"separator","aria-orientation":"vertical","aria-label":"Resize agents panel",title:"Drag to resize · Double-click to reset",onPointerDown:Ze,onPointerMove:ze,onPointerUp:Se,onPointerCancel:Se,onDoubleClick:ft}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":F?"Close agents sidebar":"Open agents sidebar","aria-expanded":F,onClick:Ke,children:[e.jsx(u,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),f?e.jsx(ta,{agentId:f,terminalViewMode:qe,onTerminalViewModeChange:Ye,inspectorOpen:xe,onToggleInspector:xt,onImageClick:Oe,onFileClick:Qe,onBashClick:Q,onViewMarkdown:et,onRequestClearSubordinates:tt,onOpenBuilding:Me,keyboard:oe,canNavigateBack:nt,canNavigateForward:at,onNavigateBack:o,onNavigateForward:d,agentInfoOpen:Ie,onToggleAgentInfo:Ge,onHeaderContextMenu:t=>{f&&fe({agentId:f,position:t})},onBuildingContextMenu:(t,n)=>{$({buildingId:t,position:n})}}):e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-map",children:[e.jsxs("div",{className:"flat-map__header",children:[e.jsx("span",{className:"flat-map__title",children:"🗺️ Areas"}),e.jsx("span",{className:"flat-map__hint",children:"Click an area to focus it, or an agent to chat"}),e.jsx(Un,{className:"flat-map__view-mode"})]}),e.jsx("div",{className:"flat-map__grid",style:{gridTemplateColumns:`repeat(${Ne.gridCols}, 1fr)`},children:Ne.groups.length===0?e.jsx("div",{className:"flat-map__empty",children:e.jsx("span",{children:"No areas or agents yet"})}):(()=>{var n;const t=je&&it?((n=Ne.positions.get(it))==null?void 0:n.row)??null:null;return Ne.groups.map(s=>{const p=s.area.id,m=Ne.positions.get(p),_=je&&it!==p;return je&&t!=null&&(m==null?void 0:m.row)===t&&p!==it?null:e.jsxs("div",{className:`flat-map-area-card${_?" flat-map-area-card--collapsed":""}`,style:{"--area-color":s.area.color,gridRow:m==null?void 0:m.row,gridColumn:m==null?void 0:m.col},onContextMenu:i=>{S&&(i.preventDefault(),i.stopPropagation(),S(p,{x:i.clientX,y:i.clientY}))},children:[e.jsxs("button",{type:"button",className:"flat-map-area-card__header",onClick:()=>je?Zt(p):tn(p),title:je?_?`Expand ${s.area.name}`:`Collapse ${s.area.name}`:`Focus ${s.area.name} in left panel`,"aria-expanded":je?!_:void 0,children:[e.jsx("span",{className:"flat-map-area-card__color",style:{background:s.area.color}}),e.jsx("span",{className:"flat-map-area-card__name",children:s.area.name}),e.jsx("span",{className:"flat-map-area-card__count",children:s.agents.length}),je&&e.jsx(u,{name:_?"caret-down":"caret-up",size:11,className:"flat-map-area-card__caret"})]}),e.jsx("div",{className:"flat-map-area-card__agents",children:s.agents.map(i=>{const I=i.isBoss||i.class==="boss",j=I?st.get(i.id):void 0,E=hn(i),ue=E.usedPercent>=80?"#ff4a4a":E.usedPercent>=60?"#ff9e4a":E.usedPercent>=40?"#ffd700":"#4aff9e",b=`Context: ${(E.totalTokens/1e3).toFixed(1)}k / ${(E.contextWindow/1e3).toFixed(1)}k (${E.usedPercent}% used, ${E.freePercent}% free)`,k=i.latestTodos&&i.latestTodos.length>0||j&&j.length>0;return e.jsx(gn,{todos:i.latestTodos,subordinates:j,position:"top",children:e.jsxs("button",{type:"button",className:`flat-map-agent-chip ${i.status}`,onClick:()=>w(i.id),onContextMenu:N=>{N.preventDefault(),N.stopPropagation(),fe({agentId:i.id,position:{x:N.clientX,y:N.clientY}})},title:k?void 0:`${I?"Boss · ":""}Open chat with ${i.name}
2
2
  ${b}`,children:[e.jsx(Xt,{agent:i,size:16}),I&&e.jsx("span",{className:"flat-map-agent-chip__crown","aria-hidden":"true",children:e.jsx(u,{name:"crown",size:11,color:"#ffd700",weight:"fill"})}),e.jsx("span",{className:"flat-map-agent-chip__name",children:i.name}),e.jsx("img",{src:i.provider==="codex"?"/assets/codex.png":i.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:i.provider,className:"flat-map-agent-chip__provider-icon",title:i.provider==="codex"?"Codex Agent":i.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),e.jsx("span",{className:"flat-map-agent-chip__dot",style:{backgroundColor:Gt(i.status)}}),i.latestTodos&&i.latestTodos.length>0&&e.jsx(xn,{todos:i.latestTodos,maxDots:6}),I&&j&&j.length>0&&e.jsx(bn,{subordinates:j,maxDots:6}),e.jsx("span",{className:"flat-map-agent-chip__context-bar","aria-hidden":"true",children:e.jsx("span",{className:"flat-map-agent-chip__context-bar-fill",style:{width:`${E.usedPercent}%`,backgroundColor:ue}})})]})},i.id)})}),s.area.directories.length>0&&e.jsx("div",{className:"flat-map-area-card__folders",role:"group","aria-label":`${s.area.name} folders`,children:s.area.directories.map(i=>{const I=i.split("/").filter(Boolean).pop()||i;return e.jsxs("button",{type:"button",className:"flat-map-folder-chip",onClick:j=>{j.stopPropagation(),x.openFileExplorerForAreaFolder(p,i)},title:`Open in file explorer: ${i}`,children:[e.jsx(u,{name:"folder-open",size:12}),e.jsx("span",{className:"flat-map-folder-chip__name",children:I})]},i)})}),s.buildings.length>0&&e.jsx("div",{className:"flat-map-area-card__buildings",children:s.buildings.map(i=>{var j;const I=(j=_n[i.type])==null?void 0:j.color;return e.jsxs("button",{type:"button",className:`flat-map-building-chip flat-map-building-chip--${i.status}`,style:I?{"--building-type-color":I}:void 0,onClick:E=>{if(A){const ue=E.currentTarget.getBoundingClientRect();A(i.id,{x:ue.right,y:ue.top+ue.height/2})}else Me(i.id)},onContextMenu:E=>{E.preventDefault(),E.stopPropagation(),$({buildingId:i.id,position:{x:E.clientX,y:E.clientY}})},title:`${i.name} · ${i.type} · ${i.status}`,children:[e.jsx(u,{name:wn(i.type),size:12,color:I}),e.jsx("span",{className:"flat-map-building-chip__name",children:i.name}),e.jsx("span",{className:"flat-map-building-chip__dot",style:{backgroundColor:vn(i.status)}})]},i.id)})})]},p)})})()})]})})]}),V&&e.jsx("div",{className:"flat-splitter flat-splitter--inspector",role:"separator","aria-orientation":"vertical","aria-label":"Resize inspector panel",title:"Drag to resize · Double-click to reset",onPointerDown:_e,onPointerMove:ze,onPointerUp:Se,onPointerCancel:Se,onDoubleClick:ht}),P&&e.jsxs("aside",{className:`flat-inspector ${lt?"flat-inspector--open":"flat-inspector--closing"}`,"aria-label":"Inspector panel",children:[e.jsxs("div",{className:"flat-inspector__header",children:[e.jsxs("div",{className:"flat-inspector__tabs",role:"tablist","aria-label":"Inspector view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":we==="agent",className:`flat-inspector__tab ${we==="agent"?"flat-inspector__tab--active":""}`,onClick:()=>Je("agent"),children:"Agent"}),e.jsx("button",{type:"button",role:"tab","aria-selected":we==="tracking",className:`flat-inspector__tab ${we==="tracking"?"flat-inspector__tab--active":""}`,onClick:()=>Je("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:J,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:we==="tracking"?e.jsx(Cn,{activeAgentId:f??"",onSelectAgent:t=>{w(t),window.innerWidth<=768&&J()}}):(()=>{if(!f)return e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Select an agent to inspect"})});const t=g.find(n=>n.id===f);return t?e.jsx(jn,{agent:t,onFocusAgent:n=>{w(n),window.innerWidth<=768&&J()},onKillAgent:n=>x.killAgent(n)}):e.jsx("div",{className:"flat-inspector__empty",children:e.jsx("span",{children:"Agent not found"})})})()})]}),ye&&e.jsx(Nn,{url:ye.url,name:ye.name,onClose:()=>We(null)}),He&&e.jsx(kn,{state:He,onClose:()=>Ve(null)}),e.jsx(yn,{agent:f?g.find(t=>t.id===f)??null:null,content:pe,onClose:()=>ie(null)}),me&&e.jsx(An,{action:"clear-subordinates",selectedAgentId:me.agentId,subordinateCount:me.count,onClose:()=>Xe(null),onClearHistory:()=>{}}),e.jsx(In,{agent:f?g.find(t=>t.id===f)??null:null,isOpen:Ie&&!!f,onClose:Ue}),e.jsx(Ot,{isOpen:K!==null,position:(K==null?void 0:K.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:Qt,onClose:()=>fe(null)}),e.jsx(Ot,{isOpen:h!==null,position:(h==null?void 0:h.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:en,onClose:()=>$(null)}),e.jsx(En,{isOpen:B!==null,title:le("common:confirm.removeAgentTitle"),message:le("common:confirm.removeAgentMessage",{name:(B==null?void 0:B.name)??""}),confirmLabel:le("common:buttons.remove"),cancelLabel:le("common:buttons.cancel"),variant:"danger",onConfirm:()=>{B&&x.removeAgentFromServer(B.agentId)},onClose:()=>Ae(null)})]})}export{la as FlatView};
@@ -1,10 +1,10 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-CIOdhnaW.js","assets/main-BxA3Bhkv.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-BLrGoeQ_.css","assets/EmbeddedEditor-O_u2UVA4.css"])))=>i.map(i=>d[i]);
2
- import{r as t,aL as q,l as K,aZ as Vt,M as $s,S as Dt,N as Hs,s as mt,u as le,j as e,I as T,bA as Rt,f as zs,bB as Os,bC as Dn,bD as As,bE as Gs,bF as Rn,bG as Fn,bH as Kt,bI as In,bJ as Pn,bK as Ln,bL as Xt,bM as $n,bN as Us,bO as Tt,bP as Mt,ac as it,bQ as ft,bR as pt,bS as Es,bT as Hn,b5 as zn,bU as Jt,bV as On,bW as An,bX as Ss,C as Gn,n as Un}from"./main-BxA3Bhkv.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Bn(s){const[n,l]=t.useState(null),[c,r]=t.useState(!1),i=t.useCallback(async()=>{if(s){r(!0);try{const f=await q(K(`/api/files/git-status?path=${encodeURIComponent(s)}`)),o=await f.json();f.ok?l(o):l({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),l({isGitRepo:!1,files:[]})}finally{r(!1)}}},[s]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function _n(s){try{const n=await q(K(`/api/files/git-original?path=${encodeURIComponent(s)}`)),l=await n.json();return n.ok&&!l.isNew?{content:l.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const Vn=new Set([".txt",".md",".markdown",".json",".yaml",".yml",".xml",".html",".htm",".css",".scss",".sass",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".c",".cpp",".h",".hpp",".cs",".go",".rs",".swift",".kt",".scala",".clj",".ex",".exs",".erl",".hs",".ml",".fs",".sql",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".toml",".ini",".cfg",".conf",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".babelrc",".log",".csv",".tsv",".svg",""]),Kn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Wn=new Set([".pdf"]),qn=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".zip",".tar",".gz",".rar",".7z",".exe",".dmg",".app",".deb",".rpm",".apk",".aab",".ipa",".msi",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".webm",".ttf",".otf",".woff",".woff2",".eot",".sqlite",".db",".so",".dll",".dylib",".a",".o",".obj",".bin",".dat",".iso",".img",".jar",".war",".ear",".class"]);function Yn(s){const n=s.toLowerCase();return Kn.has(n)?"image":Wn.has(n)?"pdf":qn.has(n)?"binary":(Vn.has(n),"text")}function Jn(){const[s,n]=t.useState(null),[l,c]=t.useState(!1),[r,i]=t.useState(null),f=t.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),b=Yn(p),C=u.substring(u.lastIndexOf("/")+1);if(b==="image"){const N=await q(K(`/api/files/binary?path=${encodeURIComponent(u)}`));if(!N.ok){const w=await N.json().catch(()=>({error:"Failed to load image"}));i(w.error||"Failed to load image"),n(null);return}const d=await N.blob(),v=URL.createObjectURL(d);n({path:u,filename:C,extension:p,content:"",size:d.size,modified:new Date().toISOString(),fileType:"image",dataUrl:v});return}if(b==="pdf"){const N=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load PDF info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"pdf",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&token=${encodeURIComponent(Vt())}`)});return}if(b==="binary"){const N=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load file info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Vt())}`)});return}const F=await q(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await F.json();if(!F.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const N=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(N.ok){n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Vt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const b=p instanceof Error?p.message:"Failed to load file";i(b),n(null)}finally{c(!1)}},[]),o=t.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:s,loading:l,error:r,loadFile:f,clearFile:o,setFile:n}}const Wt="file-explorer-state",Xn=10080*60*1e3;function Qn(s,n){return n?`${Wt}-folder-${n}`:s?`${Wt}-area-${s}`:`${Wt}-default`}async function Zn(s){try{const n=await q(K(`/api/files/exists?path=${encodeURIComponent(s)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function ea({areaId:s,folderPath:n,isOpen:l}){const c=Qn(s,n),r=t.useRef(!1);t.useEffect(()=>{r.current=!1},[s,n]);const i=t.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const o=localStorage.getItem(c);if(!o)return null;const u=JSON.parse(o);if(Date.now()-u.timestamp>Xn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async b=>({tab:b,exists:await Zn(b.path)})))).filter(({exists:b})=>b).map(({tab:b})=>b);let p=u.activeTabPath;return p&&!j.some(b=>b.path===p)&&(p=j.length>0?j[0].path:null),{tabs:j,activeTabPath:p,viewMode:u.viewMode||"files",selectedFolderIndex:u.selectedFolderIndex||0,expandedPaths:new Set(u.expandedPaths||[])}}catch(o){return console.error("[FileExplorerStorage] Failed to load state:",o),null}},[c]),f=t.useCallback(o=>{if(l)try{const u={tabs:o.tabs,activeTabPath:o.activeTabPath,viewMode:o.viewMode,selectedFolderIndex:o.selectedFolderIndex,expandedPaths:Array.from(o.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,l]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function ta(){const[s,n]=t.useState(()=>{const g=$s(Dt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),l=t.useRef(!1),[c,r]=t.useState(!1),i=t.useRef(0),f=t.useRef(0),o=t.useRef(s);o.current=s;const u=t.useCallback(g=>{g.preventDefault(),l.current=!0,r(!0),i.current=g.clientX,f.current=s,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[s]);return t.useEffect(()=>{const g=p=>{if(!l.current)return;const b=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+b));n(C)},j=()=>{l.current&&(l.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Dt.TREE_PANEL_WIDTH,o.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:s,handleResizeStart:u,isResizing:c}}const sa=100,na=.65,aa=36;function ra(){const[s,n]=t.useState(()=>$s(Dt.MOBILE_TREE_PANEL_HEIGHT,0)),l=t.useRef(s);l.current=s;const c=t.useRef(0),r=t.useRef(0),i=()=>Math.floor((window.innerHeight-aa)*na),f=p=>Math.min(i(),Math.max(sa,p)),o=t.useCallback(p=>{n(p);const b=document.querySelector(".file-explorer-main");b&&b.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=t.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Dt.MOBILE_TREE_PANEL_HEIGHT,l.current),mt.setTerminalResizing(!1)},[]),g=t.useCallback(p=>{p.preventDefault();const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;c.current=p.clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const F=N=>{const d=N.clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",F),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",F),document.addEventListener("mouseup",x)},[o,u]),j=t.useCallback(p=>{if(p.touches.length!==1)return;const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;c.current=p.touches[0].clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const F=N=>{if(N.touches.length!==1)return;N.preventDefault();const d=N.touches[0].clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",F),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",F,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[o,u]);return{mobileTreeHeight:s,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(null),[f,o]=t.useState(null),u=t.useCallback(async N=>{c(!0),i(null);try{const d=await q(K(`/api/files/git-branches?path=${encodeURIComponent(N)}`)),v=await d.json();d.ok?n(v.branches||[]):(i(v.error||"Failed to load branches"),n([]))}catch(d){console.error("[GitBranches] Failed to load branches:",d),i("Failed to load branches"),n([])}finally{c(!1)}},[]),g=t.useCallback(async(N,d)=>{o("checkout"),i(null);try{const v=await q(K("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return v.ok||i(w.error||"Checkout failed"),w}catch(v){console.error("[GitBranches] Checkout failed:",v);const w={success:!1,error:"Checkout failed"};return i(w.error),w}finally{o(null)}},[]),j=t.useCallback(async(N,d,v)=>{o("create"),i(null);try{const w=await q(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,name:d,startPoint:v})}),R=await w.json();return w.ok||i(R.error||"Failed to create branch"),R}catch(w){console.error("[GitBranches] Create branch failed:",w);const R={success:!1,error:"Failed to create branch"};return i(R.error),R}finally{o(null)}},[]),p=t.useCallback(async N=>{o("pull"),i(null);try{const d=await q(K("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return!d.ok&&!v.conflicts&&i(v.error||"Pull failed"),v}catch(d){console.error("[GitBranches] Pull failed:",d);const v={success:!1,error:"Pull failed"};return i(v.error),v}finally{o(null)}},[]),b=t.useCallback(async N=>{o("push"),i(null);try{const d=await q(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Push failed"),v}catch(d){console.error("[GitBranches] Push failed:",d);const v={success:!1,error:"Push failed"};return i(v.error),v}finally{o(null)}},[]),C=t.useCallback(async(N,d)=>{o("merge"),i(null);try{const v=await q(K("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return!v.ok&&!w.conflicts&&i(w.error||"Merge failed"),w}catch(v){console.error("[GitBranches] Merge failed:",v);const w={success:!1,error:"Merge failed"};return i(w.error),w}finally{o(null)}},[]),F=t.useCallback(async N=>{o("merge-abort"),i(null);try{const d=await q(K("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge abort failed"),v}catch(d){console.error("[GitBranches] Merge abort failed:",d);const v={success:!1,error:"Merge abort failed"};return i(v.error),v}finally{o(null)}},[]),x=t.useCallback(async N=>{o("merge-continue"),i(null);try{const d=await q(K("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge continue failed"),v}catch(d){console.error("[GitBranches] Merge continue failed:",d);const v={success:!1,error:"Merge continue failed"};return i(v.error),v}finally{o(null)}},[]);return{branches:s,loading:l,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:b,mergeBranch:C,mergeAbort:F,mergeContinue:x}}const ia=50,la=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function oa(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(!1),[f,o]=t.useState(null),[u,g]=t.useState(!1),[j,p]=t.useState(0),[b,C]=t.useState({...Rs}),[F,x]=t.useState(null),[N,d]=t.useState([]),[v,w]=t.useState(!1),[R,z]=t.useState([]),[O,G]=t.useState(!1),H=t.useRef(null),ae=t.useRef(""),ee=t.useCallback((A,Z,L)=>{const S=L||b,W=new URLSearchParams;return W.set("path",A),W.set("limit",String(ia)),W.set("offset",String(Z)),S.branch&&W.set("branch",S.branch),S.author&&W.set("author",S.author),S.since&&W.set("since",S.since),S.until&&W.set("until",S.until),S.searchPath&&W.set("searchPath",S.searchPath),S.search&&W.set("search",S.search),W.toString()},[b]),M=t.useCallback(async A=>{ae.current=A,c(!0),o(null),x(null),d([]);try{const Z=ee(A,0),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok?(n(S.commits||[]),p(S.total||0),g(S.hasMore||!1)):(o(S.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),o("Failed to load git history"),n([])}finally{c(!1)}},[ee]),D=t.useCallback(async A=>{if(!(r||!u)){i(!0);try{const Z=ee(A,s.length),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok&&(n(W=>[...W,...S.commits||[]]),p(S.total||0),g(S.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,s.length,u,r]),I=t.useCallback(async A=>{if(x(A),!A){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:A.hash}),S=await q(K(`/api/files/git-commit-files?${L}`)),W=await S.json();S.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=t.useCallback((A,Z)=>{C(L=>({...L,[A]:Z}))},[]),_=t.useCallback(()=>{C({...Rs})},[]);t.useEffect(()=>{const A=ae.current;if(A)return H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{M(A)},la),()=>{H.current&&clearTimeout(H.current)}},[b]);const ge=t.useCallback(async A=>{G(!0);try{const Z=new URLSearchParams({path:A}),L=await q(K(`/api/files/git-authors?${Z}`)),S=await L.json();L.ok&&z(S.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:s,loading:l,loadingMore:r,error:f,hasMore:u,total:j,filters:b,setFilter:re,resetFilters:_,selectedCommit:F,selectCommit:I,commitFiles:N,commitFilesLoading:v,loadHistory:M,loadMore:D,authors:R,authorsLoading:O,loadAuthors:ge}}function ca(s){if(!s.current)return null;const n=[".file-viewer-code-with-lines",".file-viewer-markdown-wrapper",".file-viewer-code-wrapper",".file-viewer-diagram-wrapper",".file-viewer-image-wrapper",".file-viewer-pdf-wrapper"];for(const l of n){const c=s.current.querySelector(l);if(c&&Fs(c))return c}return Fs(s.current)?s.current:null}function Fs(s){const n=["auto","scroll"].includes(getComputedStyle(s).overflowY),l=s.scrollHeight>s.clientHeight||s.scrollWidth>s.clientWidth;return n&&l}function Bs(s){if(!s)return 19.5;const n=parseFloat(getComputedStyle(s).lineHeight);return isNaN(n)?19.5:n}function qt(s,n=!0){const l=n?s.scrollHeight:0;s.scrollTo({top:l,behavior:"smooth"})}function da(s){const{scrollTop:n,scrollHeight:l,clientHeight:c}=s;return l<=c?100:Math.round(n/(l-c)*100)}function ua(s,n){const l=Bs(s),c=s.scrollTop,r=Math.floor(c/l)+1,i=n.split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-B9iQHzhz.js","assets/main-Brpf2Evy.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-VciFPjA1.css","assets/EmbeddedEditor-O_u2UVA4.css"])))=>i.map(i=>d[i]);
2
+ import{r as t,aL as q,l as K,aZ as Vt,M as $s,S as Dt,N as Hs,s as mt,u as le,j as e,I as T,bA as Rt,f as zs,bB as Os,bC as Dn,bD as As,bE as Gs,bF as Rn,bG as Fn,bH as Kt,bI as In,bJ as Pn,bK as Ln,bL as Xt,bM as $n,bN as Us,bO as Tt,bP as Mt,ac as it,bQ as ft,bR as pt,bS as Es,bT as Hn,b5 as zn,bU as Jt,bV as On,bW as An,bX as Ss,C as Gn,n as Un}from"./main-Brpf2Evy.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Bn(s){const[n,l]=t.useState(null),[c,r]=t.useState(!1),i=t.useCallback(async()=>{if(s){r(!0);try{const f=await q(K(`/api/files/git-status?path=${encodeURIComponent(s)}`)),o=await f.json();f.ok?l(o):l({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),l({isGitRepo:!1,files:[]})}finally{r(!1)}}},[s]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function _n(s){try{const n=await q(K(`/api/files/git-original?path=${encodeURIComponent(s)}`)),l=await n.json();return n.ok&&!l.isNew?{content:l.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const Vn=new Set([".txt",".md",".markdown",".json",".yaml",".yml",".xml",".html",".htm",".css",".scss",".sass",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".c",".cpp",".h",".hpp",".cs",".go",".rs",".swift",".kt",".scala",".clj",".ex",".exs",".erl",".hs",".ml",".fs",".sql",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".toml",".ini",".cfg",".conf",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".babelrc",".log",".csv",".tsv",".svg",""]),Kn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Wn=new Set([".pdf"]),qn=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".zip",".tar",".gz",".rar",".7z",".exe",".dmg",".app",".deb",".rpm",".apk",".aab",".ipa",".msi",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".webm",".ttf",".otf",".woff",".woff2",".eot",".sqlite",".db",".so",".dll",".dylib",".a",".o",".obj",".bin",".dat",".iso",".img",".jar",".war",".ear",".class"]);function Yn(s){const n=s.toLowerCase();return Kn.has(n)?"image":Wn.has(n)?"pdf":qn.has(n)?"binary":(Vn.has(n),"text")}function Jn(){const[s,n]=t.useState(null),[l,c]=t.useState(!1),[r,i]=t.useState(null),f=t.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),b=Yn(p),C=u.substring(u.lastIndexOf("/")+1);if(b==="image"){const N=await q(K(`/api/files/binary?path=${encodeURIComponent(u)}`));if(!N.ok){const w=await N.json().catch(()=>({error:"Failed to load image"}));i(w.error||"Failed to load image"),n(null);return}const d=await N.blob(),v=URL.createObjectURL(d);n({path:u,filename:C,extension:p,content:"",size:d.size,modified:new Date().toISOString(),fileType:"image",dataUrl:v});return}if(b==="pdf"){const N=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load PDF info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"pdf",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&token=${encodeURIComponent(Vt())}`)});return}if(b==="binary"){const N=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load file info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Vt())}`)});return}const F=await q(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await F.json();if(!F.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const N=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(N.ok){n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Vt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const b=p instanceof Error?p.message:"Failed to load file";i(b),n(null)}finally{c(!1)}},[]),o=t.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:s,loading:l,error:r,loadFile:f,clearFile:o,setFile:n}}const Wt="file-explorer-state",Xn=10080*60*1e3;function Qn(s,n){return n?`${Wt}-folder-${n}`:s?`${Wt}-area-${s}`:`${Wt}-default`}async function Zn(s){try{const n=await q(K(`/api/files/exists?path=${encodeURIComponent(s)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function ea({areaId:s,folderPath:n,isOpen:l}){const c=Qn(s,n),r=t.useRef(!1);t.useEffect(()=>{r.current=!1},[s,n]);const i=t.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const o=localStorage.getItem(c);if(!o)return null;const u=JSON.parse(o);if(Date.now()-u.timestamp>Xn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async b=>({tab:b,exists:await Zn(b.path)})))).filter(({exists:b})=>b).map(({tab:b})=>b);let p=u.activeTabPath;return p&&!j.some(b=>b.path===p)&&(p=j.length>0?j[0].path:null),{tabs:j,activeTabPath:p,viewMode:u.viewMode||"files",selectedFolderIndex:u.selectedFolderIndex||0,expandedPaths:new Set(u.expandedPaths||[])}}catch(o){return console.error("[FileExplorerStorage] Failed to load state:",o),null}},[c]),f=t.useCallback(o=>{if(l)try{const u={tabs:o.tabs,activeTabPath:o.activeTabPath,viewMode:o.viewMode,selectedFolderIndex:o.selectedFolderIndex,expandedPaths:Array.from(o.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,l]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function ta(){const[s,n]=t.useState(()=>{const g=$s(Dt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),l=t.useRef(!1),[c,r]=t.useState(!1),i=t.useRef(0),f=t.useRef(0),o=t.useRef(s);o.current=s;const u=t.useCallback(g=>{g.preventDefault(),l.current=!0,r(!0),i.current=g.clientX,f.current=s,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[s]);return t.useEffect(()=>{const g=p=>{if(!l.current)return;const b=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+b));n(C)},j=()=>{l.current&&(l.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Dt.TREE_PANEL_WIDTH,o.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:s,handleResizeStart:u,isResizing:c}}const sa=100,na=.65,aa=36;function ra(){const[s,n]=t.useState(()=>$s(Dt.MOBILE_TREE_PANEL_HEIGHT,0)),l=t.useRef(s);l.current=s;const c=t.useRef(0),r=t.useRef(0),i=()=>Math.floor((window.innerHeight-aa)*na),f=p=>Math.min(i(),Math.max(sa,p)),o=t.useCallback(p=>{n(p);const b=document.querySelector(".file-explorer-main");b&&b.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=t.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Dt.MOBILE_TREE_PANEL_HEIGHT,l.current),mt.setTerminalResizing(!1)},[]),g=t.useCallback(p=>{p.preventDefault();const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;c.current=p.clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const F=N=>{const d=N.clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",F),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",F),document.addEventListener("mouseup",x)},[o,u]),j=t.useCallback(p=>{if(p.touches.length!==1)return;const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;c.current=p.touches[0].clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const F=N=>{if(N.touches.length!==1)return;N.preventDefault();const d=N.touches[0].clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",F),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",F,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[o,u]);return{mobileTreeHeight:s,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(null),[f,o]=t.useState(null),u=t.useCallback(async N=>{c(!0),i(null);try{const d=await q(K(`/api/files/git-branches?path=${encodeURIComponent(N)}`)),v=await d.json();d.ok?n(v.branches||[]):(i(v.error||"Failed to load branches"),n([]))}catch(d){console.error("[GitBranches] Failed to load branches:",d),i("Failed to load branches"),n([])}finally{c(!1)}},[]),g=t.useCallback(async(N,d)=>{o("checkout"),i(null);try{const v=await q(K("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return v.ok||i(w.error||"Checkout failed"),w}catch(v){console.error("[GitBranches] Checkout failed:",v);const w={success:!1,error:"Checkout failed"};return i(w.error),w}finally{o(null)}},[]),j=t.useCallback(async(N,d,v)=>{o("create"),i(null);try{const w=await q(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,name:d,startPoint:v})}),R=await w.json();return w.ok||i(R.error||"Failed to create branch"),R}catch(w){console.error("[GitBranches] Create branch failed:",w);const R={success:!1,error:"Failed to create branch"};return i(R.error),R}finally{o(null)}},[]),p=t.useCallback(async N=>{o("pull"),i(null);try{const d=await q(K("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return!d.ok&&!v.conflicts&&i(v.error||"Pull failed"),v}catch(d){console.error("[GitBranches] Pull failed:",d);const v={success:!1,error:"Pull failed"};return i(v.error),v}finally{o(null)}},[]),b=t.useCallback(async N=>{o("push"),i(null);try{const d=await q(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Push failed"),v}catch(d){console.error("[GitBranches] Push failed:",d);const v={success:!1,error:"Push failed"};return i(v.error),v}finally{o(null)}},[]),C=t.useCallback(async(N,d)=>{o("merge"),i(null);try{const v=await q(K("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return!v.ok&&!w.conflicts&&i(w.error||"Merge failed"),w}catch(v){console.error("[GitBranches] Merge failed:",v);const w={success:!1,error:"Merge failed"};return i(w.error),w}finally{o(null)}},[]),F=t.useCallback(async N=>{o("merge-abort"),i(null);try{const d=await q(K("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge abort failed"),v}catch(d){console.error("[GitBranches] Merge abort failed:",d);const v={success:!1,error:"Merge abort failed"};return i(v.error),v}finally{o(null)}},[]),x=t.useCallback(async N=>{o("merge-continue"),i(null);try{const d=await q(K("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge continue failed"),v}catch(d){console.error("[GitBranches] Merge continue failed:",d);const v={success:!1,error:"Merge continue failed"};return i(v.error),v}finally{o(null)}},[]);return{branches:s,loading:l,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:b,mergeBranch:C,mergeAbort:F,mergeContinue:x}}const ia=50,la=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function oa(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(!1),[f,o]=t.useState(null),[u,g]=t.useState(!1),[j,p]=t.useState(0),[b,C]=t.useState({...Rs}),[F,x]=t.useState(null),[N,d]=t.useState([]),[v,w]=t.useState(!1),[R,z]=t.useState([]),[O,G]=t.useState(!1),H=t.useRef(null),ae=t.useRef(""),ee=t.useCallback((A,Z,L)=>{const S=L||b,W=new URLSearchParams;return W.set("path",A),W.set("limit",String(ia)),W.set("offset",String(Z)),S.branch&&W.set("branch",S.branch),S.author&&W.set("author",S.author),S.since&&W.set("since",S.since),S.until&&W.set("until",S.until),S.searchPath&&W.set("searchPath",S.searchPath),S.search&&W.set("search",S.search),W.toString()},[b]),M=t.useCallback(async A=>{ae.current=A,c(!0),o(null),x(null),d([]);try{const Z=ee(A,0),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok?(n(S.commits||[]),p(S.total||0),g(S.hasMore||!1)):(o(S.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),o("Failed to load git history"),n([])}finally{c(!1)}},[ee]),D=t.useCallback(async A=>{if(!(r||!u)){i(!0);try{const Z=ee(A,s.length),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok&&(n(W=>[...W,...S.commits||[]]),p(S.total||0),g(S.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,s.length,u,r]),I=t.useCallback(async A=>{if(x(A),!A){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:A.hash}),S=await q(K(`/api/files/git-commit-files?${L}`)),W=await S.json();S.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=t.useCallback((A,Z)=>{C(L=>({...L,[A]:Z}))},[]),_=t.useCallback(()=>{C({...Rs})},[]);t.useEffect(()=>{const A=ae.current;if(A)return H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{M(A)},la),()=>{H.current&&clearTimeout(H.current)}},[b]);const ge=t.useCallback(async A=>{G(!0);try{const Z=new URLSearchParams({path:A}),L=await q(K(`/api/files/git-authors?${Z}`)),S=await L.json();L.ok&&z(S.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:s,loading:l,loadingMore:r,error:f,hasMore:u,total:j,filters:b,setFilter:re,resetFilters:_,selectedCommit:F,selectCommit:I,commitFiles:N,commitFilesLoading:v,loadHistory:M,loadMore:D,authors:R,authorsLoading:O,loadAuthors:ge}}function ca(s){if(!s.current)return null;const n=[".file-viewer-code-with-lines",".file-viewer-markdown-wrapper",".file-viewer-code-wrapper",".file-viewer-diagram-wrapper",".file-viewer-image-wrapper",".file-viewer-pdf-wrapper"];for(const l of n){const c=s.current.querySelector(l);if(c&&Fs(c))return c}return Fs(s.current)?s.current:null}function Fs(s){const n=["auto","scroll"].includes(getComputedStyle(s).overflowY),l=s.scrollHeight>s.clientHeight||s.scrollWidth>s.clientWidth;return n&&l}function Bs(s){if(!s)return 19.5;const n=parseFloat(getComputedStyle(s).lineHeight);return isNaN(n)?19.5:n}function qt(s,n=!0){const l=n?s.scrollHeight:0;s.scrollTo({top:l,behavior:"smooth"})}function da(s){const{scrollTop:n,scrollHeight:l,clientHeight:c}=s;return l<=c?100:Math.round(n/(l-c)*100)}function ua(s,n){const l=Bs(s),c=s.scrollTop,r=Math.floor(c/l)+1,i=n.split(`
3
3
  `).length;return Math.min(r,i)}function ha(s,n,l=!1){if(!n)return[];l||s.toLowerCase();const c=l?n:n.toLowerCase(),r=[];let i=0;const f=s.split(`
4
4
  `);let o=0;for(let u=0;u<f.length;u++){const g=f[u],j=l?g:g.toLowerCase();let p=0,b=j.indexOf(c);for(;b!==-1;){const C=o+b;r.push({index:i++,line:u+1,column:b,length:c.length,charIndex:C}),p=b+c.length,b=j.indexOf(c,p)}o+=g.length+1}return r}function lt(s){return/[\w]/.test(s)}function Ae(s){return/\s/.test(s)}function ma(s,n,l){let c=n-1,r=l;const i=s.length,f=s[c]||"";if(r<f.length){const g=lt(f[r]);if(!Ae(f[r]))for(;r<f.length&&!Ae(f[r])&&lt(f[r])===g;)r++}for(;c<i;){const g=s[c]||"";for(;r<g.length&&Ae(g[r]);)r++;if(r<g.length)return{line:c+1,col:r};c++,r=0}const o=i,u=Math.max(0,(s[i-1]||"").length-1);return{line:o,col:u}}function fa(s,n,l){let c=n-1,r=l+1;const i=s.length;for(;c<i;){const u=s[c]||"";for(;r<u.length&&Ae(u[r]);)r++;if(r<u.length)break;c++,r=0}if(c>=i)return{line:i,col:Math.max(0,(s[i-1]||"").length-1)};const f=s[c]||"",o=lt(f[r]);for(;r+1<f.length&&!Ae(f[r+1])&&lt(f[r+1])===o;)r++;return{line:c+1,col:r}}function pa(s,n,l){let c=n-1,r=l-1;for(;c>=0;){const o=s[c]||"";for(;r>=0&&Ae(o[r]);)r--;if(r>=0)break;c--,c>=0&&(r=(s[c]||"").length-1)}if(c<0)return{line:1,col:0};const i=s[c]||"",f=lt(i[r]);for(;r>0&&!Ae(i[r-1])&&lt(i[r-1])===f;)r--;return{line:c+1,col:r}}function ga(s,n,l,c){if(c==="none")return"";const{anchorLine:r,anchorCol:i,headLine:f,headCol:o}=l;if(c==="line"){const C=Math.min(r,f),F=Math.max(r,f);return n.slice(C-1,F).join(`
5
5
  `)}let u,g,j,p;if(r<f||r===f&&i<=o?(u=r,g=i,j=f,p=o):(u=f,g=o,j=r,p=i),u===j)return(n[u-1]||"").substring(g,p+1);const b=[];b.push((n[u-1]||"").substring(g));for(let C=u;C<j-1;C++)b.push(n[C]||"");return b.push((n[j-1]||"").substring(0,p+1)),b.join(`
6
6
  `)}function _s(s){const{containerRef:n,isEnabled:l=!0,content:c="",onClose:r,onSearchOpen:i}=s,f=t.useRef({percentage:0,line:1,column:1}),o=t.useRef(null),u=t.useRef(19.5),g=t.useMemo(()=>c.split(`
7
- `),[c]),j=g.length,[p,b]=t.useState(1),[C,F]=t.useState(0),[x,N]=t.useState(!1),[d,v]=t.useState("none"),[w,R]=t.useState(null),[z,O]=t.useState(!1),[G,H]=t.useState(""),[ae,ee]=t.useState(0),[M,D]=t.useState(!1),I=t.useMemo(()=>ha(c,G,!1),[c,G]),re=t.useCallback(()=>{const m=o.current;if(!m)return;const Y=da(m),ie=ua(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:Y,line:ie,column:V}},[c]),_=t.useCallback(()=>{O(!0),H(""),ee(0),i==null||i()},[i]),ge=t.useCallback(()=>{O(!1),H(""),ee(0)},[]),A=t.useCallback(()=>{D(m=>!m)},[]),Z=t.useCallback(m=>{const Y=o.current;if(!Y)return;const ie=Y.querySelector(".file-viewer-pre"),ue=ie&&parseFloat(getComputedStyle(ie).lineHeight)||u.current,V=ie&&parseFloat(getComputedStyle(ie).paddingTop)||0,Q=(ie?ie.offsetTop:0)+V+(m-1)*ue,te=ue*3;Y.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);t.useEffect(()=>{!z||I.length===0||ee(0)},[I,z]),t.useEffect(()=>{if(!z||I.length===0)return;const m=I[ae];m&&(b(m.line),F(m.column),Z(m.line))},[z,I,ae,Z]);const L=t.useCallback(()=>{I.length!==0&&ee(m=>(m+1)%I.length)},[I]),S=t.useCallback(()=>{I.length!==0&&ee(m=>(m-1+I.length)%I.length)},[I]),W=t.useCallback(m=>{const Y=o.current;if(!Y)return;const ie=Y.querySelector(".file-viewer-pre");if(!ie)return;const ue=parseFloat(getComputedStyle(ie).lineHeight),V=isNaN(ue)?u.current:ue,E=parseFloat(getComputedStyle(ie).paddingTop)||0,te=ie.offsetTop+E+(m-1)*V,Ne=te+V,xe=Y.scrollTop,U=xe+Y.clientHeight;te<xe?Y.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&Y.scrollTo({top:Ne-Y.clientHeight,behavior:"auto"})},[]),se=t.useCallback((m,Y)=>{b(m),F(Y),W(m),d!=="none"&&R(ie=>ie?{...ie,headLine:m,headCol:Y}:null)},[d,W]),be=t.useCallback(()=>{if(d==="none"||!w)return;const m=ga(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const Y=document.createElement("textarea");Y.value=m,Y.style.position="fixed",Y.style.left="-9999px",document.body.appendChild(Y),Y.select(),document.execCommand("copy"),document.body.removeChild(Y)}),v("none"),R(null)},[d,w,c,g]),de=t.useCallback(m=>{const Y=m.target;if((Y.tagName==="INPUT"||Y.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=o.current;if(!ue)return;let V=!1;const E=u.current,Q=Math.max(1,Math.floor(ue.clientHeight/E)),te=Math.max(1,Math.floor(Q/2)),Ne=(U,ne)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(ne,Math.max(0,pe))},xe=(U,ne)=>{const pe=Ne(U,ne);se(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),R(null)):(v("char"),R({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),R(null)):(v("line"),R({anchorLine:p,anchorCol:0,headLine:p,headCol:0})),V=!0;else if(m.key==="y"&&!m.ctrlKey&&d!=="none")m.preventDefault(),m.stopPropagation(),be(),V=!0;else if(m.key==="j"||m.key==="ArrowDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+1,j);xe(U,C),V=!0}else if(m.key==="k"||m.key==="ArrowUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-1,1);xe(U,C),V=!0}else if(m.key==="d"&&m.ctrlKey||m.key==="d"&&d==="none"&&!z){m.preventDefault(),m.stopPropagation();const U=Math.min(p+te,j);xe(U,C),V=!0}else if(m.key==="u"&&m.ctrlKey||m.key==="u"&&d==="none"&&!z){m.preventDefault(),m.stopPropagation();const U=Math.max(p-te,1);xe(U,C),V=!0}else if((m.ctrlKey||m.metaKey)&&m.key==="f")m.preventDefault(),m.stopPropagation(),_(),V=!0;else if(m.key==="f"&&!m.ctrlKey&&!m.metaKey&&d==="none"&&!z){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key===" "||m.key==="PageDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key==="b"&&!x&&d==="none"&&!z||m.key==="PageUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-Q,1);xe(U,C),V=!0}else if(m.key==="g"&&!m.shiftKey&&d==="none"&&!z)m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),se(j,0),qt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),se(p,Math.max(0,C-1)),V=!0;else if(m.key==="l"||m.key==="ArrowRight"){m.preventDefault(),m.stopPropagation();const U=(g[p-1]||"").length;se(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=ma(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="b"&&!z){m.preventDefault(),m.stopPropagation();const U=pa(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),se(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),se(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const ne=(g[p-1]||"").search(/\S/);se(p,ne>=0?ne:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!z?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!z?(m.preventDefault(),m.stopPropagation(),S(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),A(),V=!0):m.key==="q"&&d==="none"?(m.preventDefault(),m.stopPropagation(),r==null||r(),V=!0):m.key==="Escape"&&(d!=="none"?(m.preventDefault(),m.stopPropagation(),v("none"),R(null),V=!0):z?(m.preventDefault(),m.stopPropagation(),ge(),V=!0):x&&(m.preventDefault(),m.stopPropagation(),N(!1),V=!0));V&&(m.key!=="Escape"&&!x&&N(!0),requestAnimationFrame(re))},[r,re,j,g,p,C,W,z,ge,d,x,se,be,_,L,S,A]);return t.useEffect(()=>{if(!l)return;const m=ca(n);if(o.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const Y=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",Y,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",Y)}},[l,de,re]),{scrollPercentage:f.current.percentage,currentLine:f.current.line,currentColumn:f.current.column,totalLines:j,cursorLine:p,cursorCol:C,cursorModeActive:x,visualMode:d,selection:w,searchActive:z,searchQuery:G,searchMatches:I,currentMatchIndex:ae,startSearch:_,setSearchQuery:H,nextMatch:L,prevMatch:S,clearSearch:ge,helpActive:M,toggleHelp:A}}const Zt=({query:s,onQueryChange:n,matchCount:l,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:o}=le(["terminal"]),u=t.useRef(null);t.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=t.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=l===0&&s?o("terminal:fileExplorer.noMatches"):l>0?`${c+1}/${l}`:"";return e.jsxs("div",{className:"file-viewer-search-bar",children:[e.jsxs("div",{className:"file-viewer-search-input-wrapper",children:[e.jsx("span",{className:"file-viewer-search-prefix",children:"/"}),e.jsx("input",{ref:u,type:"text",className:"file-viewer-search-input",placeholder:o("terminal:fileExplorer.searchInFile"),value:s,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"file-viewer-search-counter",children:j}),e.jsxs("div",{className:"file-viewer-search-nav",children:[e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-prev",onClick:i,disabled:l===0,title:o("terminal:fileExplorer.previousMatch"),"aria-label":o("terminal:fileExplorer.previousMatch"),children:e.jsx(T,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:l===0,title:o("terminal:fileExplorer.nextMatch"),"aria-label":o("terminal:fileExplorer.nextMatch"),children:e.jsx(T,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:o("terminal:fileExplorer.closeSearch"),"aria-label":o("terminal:fileExplorer.closeSearch"),children:e.jsx(T,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const xa=[{keys:["j","↓"],description:"Move cursor down one line",category:"Navigation"},{keys:["k","↑"],description:"Move cursor up one line",category:"Navigation"},{keys:["h","←"],description:"Move cursor left",category:"Navigation"},{keys:["l","→"],description:"Move cursor right",category:"Navigation"},{keys:["0"],description:"Jump to start of line",category:"Navigation"},{keys:["$"],description:"Jump to end of line",category:"Navigation"},{keys:["^"],description:"First non-whitespace char",category:"Navigation"},{keys:["d","Ctrl+D"],description:"Half page down",category:"Navigation"},{keys:["u","Ctrl+U"],description:"Half page up",category:"Navigation"},{keys:["f","Space"],description:"Full page down",category:"Navigation"},{keys:["b","Page Up"],description:"Full page up",category:"Navigation"},{keys:["g","Home"],description:"Jump to top of file",category:"Navigation"},{keys:["G","End"],description:"Jump to bottom of file",category:"Navigation"},{keys:["w"],description:"Next word start",category:"Word Motion"},{keys:["e"],description:"Next word end",category:"Word Motion"},{keys:["b"],description:"Previous word start",category:"Word Motion"},{keys:["v"],description:"Character visual mode",category:"Visual Mode"},{keys:["V"],description:"Line visual mode",category:"Visual Mode"},{keys:["y"],description:"Yank (copy) selection",category:"Visual Mode"},{keys:["Escape"],description:"Exit visual mode",category:"Visual Mode"},{keys:["/"],description:"Open search bar",category:"Search"},{keys:["n"],description:"Next match",category:"Search"},{keys:["N"],description:"Previous match",category:"Search"},{keys:["?"],description:"Toggle this help overlay",category:"Help"},{keys:["Escape"],description:"Exit cursor mode (or visual/search)",category:"Help"},{keys:["Alt+E"],description:"Close file viewer",category:"Help"},{keys:["q"],description:"Close file viewer",category:"Help"}],es=({onClose:s})=>{const{t:n}=le(["terminal"]),l=t.useCallback(i=>{i.target===i.currentTarget&&s()},[s]),c=t.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),s())},[s]),r=xa.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:l,onKeyDown:c,tabIndex:0,role:"dialog","aria-label":n("terminal:fileExplorer.keybindingsHelp"),children:e.jsxs("div",{className:"keybindings-help-content",children:[e.jsx("button",{className:"keybindings-help-close",onClick:s,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(T,{name:"close",size:14})}),e.jsx("h2",{className:"keybindings-help-title",children:n("terminal:fileExplorer.keybindingsHelp")}),e.jsx("p",{className:"keybindings-help-subtitle",children:n("terminal:fileExplorer.keybindingsSubtitle")}),e.jsx("div",{className:"keybindings-help-categories",children:Object.entries(r).map(([i,f])=>e.jsxs("div",{className:"keybindings-help-category",children:[e.jsx("h3",{className:"keybindings-help-category-title",children:i}),e.jsx("div",{className:"keybindings-help-list",children:f.map((o,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:o.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:o.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Is=t.lazy(()=>Dn(()=>import("./EmbeddedEditor-CIOdhnaW.js"),__vite__mapDeps([0,1,2,3,4,5])).then(s=>({default:s.EmbeddedEditor}))),ya=[".md",".mdx",".markdown"],Ps="file-viewer-markdown-render",ba=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",ja="https://kroki.io/plantuml/svg";function va(s){return ya.includes(s.toLowerCase())}function wa(s){return ba.includes(s.toLowerCase())}function Ca(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Ps);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ps,String(r))}catch{}return r})},[]);return[s,l]}function Na(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[s,l]}function ka(s){const n=new TextEncoder().encode(s);let l="";for(const c of n)l+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(l)}`}function Ge({file:s,rightContent:n,onRevealInTree:l,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,o]=t.useState("idle"),[u,g]=t.useState("idle"),j=s.fileType==="text"?Rt(s.extension):s.extension.slice(1).toUpperCase(),{settings:p}=zs(),b=async()=>{o("loading");try{const x=await q(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,...p.externalEditorCommand&&{editorCommand:p.externalEditorCommand}})});if(!x.ok){const N=await x.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",N),o("error"),setTimeout(()=>o("idle"),2e3);return}o("success"),setTimeout(()=>o("idle"),2e3)}catch(x){console.error("Error opening file in editor:",x),o("error"),setTimeout(()=>o("idle"),2e3)}},C=async()=>{if(s.path)try{await Ln(s.path),g("success"),setTimeout(()=>g("idle"),2e3)}catch(x){console.error("Error opening file explorer:",x),g("error"),setTimeout(()=>g("idle"),2e3)}},F=i("terminal:fileExplorer.openInFileExplorer");return e.jsxs("div",{className:"file-viewer-header",children:[e.jsxs("div",{className:"file-viewer-header-left",children:[e.jsx("span",{className:"file-viewer-filename",children:s.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[Os(s.size)," • ",j,s.content&&` • ${s.content.split(`
7
+ `),[c]),j=g.length,[p,b]=t.useState(1),[C,F]=t.useState(0),[x,N]=t.useState(!1),[d,v]=t.useState("none"),[w,R]=t.useState(null),[z,O]=t.useState(!1),[G,H]=t.useState(""),[ae,ee]=t.useState(0),[M,D]=t.useState(!1),I=t.useMemo(()=>ha(c,G,!1),[c,G]),re=t.useCallback(()=>{const m=o.current;if(!m)return;const Y=da(m),ie=ua(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:Y,line:ie,column:V}},[c]),_=t.useCallback(()=>{O(!0),H(""),ee(0),i==null||i()},[i]),ge=t.useCallback(()=>{O(!1),H(""),ee(0)},[]),A=t.useCallback(()=>{D(m=>!m)},[]),Z=t.useCallback(m=>{const Y=o.current;if(!Y)return;const ie=Y.querySelector(".file-viewer-pre"),ue=ie&&parseFloat(getComputedStyle(ie).lineHeight)||u.current,V=ie&&parseFloat(getComputedStyle(ie).paddingTop)||0,Q=(ie?ie.offsetTop:0)+V+(m-1)*ue,te=ue*3;Y.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);t.useEffect(()=>{!z||I.length===0||ee(0)},[I,z]),t.useEffect(()=>{if(!z||I.length===0)return;const m=I[ae];m&&(b(m.line),F(m.column),Z(m.line))},[z,I,ae,Z]);const L=t.useCallback(()=>{I.length!==0&&ee(m=>(m+1)%I.length)},[I]),S=t.useCallback(()=>{I.length!==0&&ee(m=>(m-1+I.length)%I.length)},[I]),W=t.useCallback(m=>{const Y=o.current;if(!Y)return;const ie=Y.querySelector(".file-viewer-pre");if(!ie)return;const ue=parseFloat(getComputedStyle(ie).lineHeight),V=isNaN(ue)?u.current:ue,E=parseFloat(getComputedStyle(ie).paddingTop)||0,te=ie.offsetTop+E+(m-1)*V,Ne=te+V,xe=Y.scrollTop,U=xe+Y.clientHeight;te<xe?Y.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&Y.scrollTo({top:Ne-Y.clientHeight,behavior:"auto"})},[]),se=t.useCallback((m,Y)=>{b(m),F(Y),W(m),d!=="none"&&R(ie=>ie?{...ie,headLine:m,headCol:Y}:null)},[d,W]),be=t.useCallback(()=>{if(d==="none"||!w)return;const m=ga(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const Y=document.createElement("textarea");Y.value=m,Y.style.position="fixed",Y.style.left="-9999px",document.body.appendChild(Y),Y.select(),document.execCommand("copy"),document.body.removeChild(Y)}),v("none"),R(null)},[d,w,c,g]),de=t.useCallback(m=>{const Y=m.target;if((Y.tagName==="INPUT"||Y.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=o.current;if(!ue)return;let V=!1;const E=u.current,Q=Math.max(1,Math.floor(ue.clientHeight/E)),te=Math.max(1,Math.floor(Q/2)),Ne=(U,ne)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(ne,Math.max(0,pe))},xe=(U,ne)=>{const pe=Ne(U,ne);se(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),R(null)):(v("char"),R({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),R(null)):(v("line"),R({anchorLine:p,anchorCol:0,headLine:p,headCol:0})),V=!0;else if(m.key==="y"&&!m.ctrlKey&&d!=="none")m.preventDefault(),m.stopPropagation(),be(),V=!0;else if(m.key==="j"||m.key==="ArrowDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+1,j);xe(U,C),V=!0}else if(m.key==="k"||m.key==="ArrowUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-1,1);xe(U,C),V=!0}else if(m.key==="d"&&m.ctrlKey||m.key==="d"&&d==="none"&&!z){m.preventDefault(),m.stopPropagation();const U=Math.min(p+te,j);xe(U,C),V=!0}else if(m.key==="u"&&m.ctrlKey||m.key==="u"&&d==="none"&&!z){m.preventDefault(),m.stopPropagation();const U=Math.max(p-te,1);xe(U,C),V=!0}else if((m.ctrlKey||m.metaKey)&&m.key==="f")m.preventDefault(),m.stopPropagation(),_(),V=!0;else if(m.key==="f"&&!m.ctrlKey&&!m.metaKey&&d==="none"&&!z){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key===" "||m.key==="PageDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key==="b"&&!x&&d==="none"&&!z||m.key==="PageUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-Q,1);xe(U,C),V=!0}else if(m.key==="g"&&!m.shiftKey&&d==="none"&&!z)m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),se(j,0),qt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),se(p,Math.max(0,C-1)),V=!0;else if(m.key==="l"||m.key==="ArrowRight"){m.preventDefault(),m.stopPropagation();const U=(g[p-1]||"").length;se(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=ma(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="b"&&!z){m.preventDefault(),m.stopPropagation();const U=pa(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),se(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),se(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const ne=(g[p-1]||"").search(/\S/);se(p,ne>=0?ne:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!z?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!z?(m.preventDefault(),m.stopPropagation(),S(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),A(),V=!0):m.key==="q"&&d==="none"?(m.preventDefault(),m.stopPropagation(),r==null||r(),V=!0):m.key==="Escape"&&(d!=="none"?(m.preventDefault(),m.stopPropagation(),v("none"),R(null),V=!0):z?(m.preventDefault(),m.stopPropagation(),ge(),V=!0):x&&(m.preventDefault(),m.stopPropagation(),N(!1),V=!0));V&&(m.key!=="Escape"&&!x&&N(!0),requestAnimationFrame(re))},[r,re,j,g,p,C,W,z,ge,d,x,se,be,_,L,S,A]);return t.useEffect(()=>{if(!l)return;const m=ca(n);if(o.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const Y=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",Y,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",Y)}},[l,de,re]),{scrollPercentage:f.current.percentage,currentLine:f.current.line,currentColumn:f.current.column,totalLines:j,cursorLine:p,cursorCol:C,cursorModeActive:x,visualMode:d,selection:w,searchActive:z,searchQuery:G,searchMatches:I,currentMatchIndex:ae,startSearch:_,setSearchQuery:H,nextMatch:L,prevMatch:S,clearSearch:ge,helpActive:M,toggleHelp:A}}const Zt=({query:s,onQueryChange:n,matchCount:l,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:o}=le(["terminal"]),u=t.useRef(null);t.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=t.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=l===0&&s?o("terminal:fileExplorer.noMatches"):l>0?`${c+1}/${l}`:"";return e.jsxs("div",{className:"file-viewer-search-bar",children:[e.jsxs("div",{className:"file-viewer-search-input-wrapper",children:[e.jsx("span",{className:"file-viewer-search-prefix",children:"/"}),e.jsx("input",{ref:u,type:"text",className:"file-viewer-search-input",placeholder:o("terminal:fileExplorer.searchInFile"),value:s,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"file-viewer-search-counter",children:j}),e.jsxs("div",{className:"file-viewer-search-nav",children:[e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-prev",onClick:i,disabled:l===0,title:o("terminal:fileExplorer.previousMatch"),"aria-label":o("terminal:fileExplorer.previousMatch"),children:e.jsx(T,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:l===0,title:o("terminal:fileExplorer.nextMatch"),"aria-label":o("terminal:fileExplorer.nextMatch"),children:e.jsx(T,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:o("terminal:fileExplorer.closeSearch"),"aria-label":o("terminal:fileExplorer.closeSearch"),children:e.jsx(T,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const xa=[{keys:["j","↓"],description:"Move cursor down one line",category:"Navigation"},{keys:["k","↑"],description:"Move cursor up one line",category:"Navigation"},{keys:["h","←"],description:"Move cursor left",category:"Navigation"},{keys:["l","→"],description:"Move cursor right",category:"Navigation"},{keys:["0"],description:"Jump to start of line",category:"Navigation"},{keys:["$"],description:"Jump to end of line",category:"Navigation"},{keys:["^"],description:"First non-whitespace char",category:"Navigation"},{keys:["d","Ctrl+D"],description:"Half page down",category:"Navigation"},{keys:["u","Ctrl+U"],description:"Half page up",category:"Navigation"},{keys:["f","Space"],description:"Full page down",category:"Navigation"},{keys:["b","Page Up"],description:"Full page up",category:"Navigation"},{keys:["g","Home"],description:"Jump to top of file",category:"Navigation"},{keys:["G","End"],description:"Jump to bottom of file",category:"Navigation"},{keys:["w"],description:"Next word start",category:"Word Motion"},{keys:["e"],description:"Next word end",category:"Word Motion"},{keys:["b"],description:"Previous word start",category:"Word Motion"},{keys:["v"],description:"Character visual mode",category:"Visual Mode"},{keys:["V"],description:"Line visual mode",category:"Visual Mode"},{keys:["y"],description:"Yank (copy) selection",category:"Visual Mode"},{keys:["Escape"],description:"Exit visual mode",category:"Visual Mode"},{keys:["/"],description:"Open search bar",category:"Search"},{keys:["n"],description:"Next match",category:"Search"},{keys:["N"],description:"Previous match",category:"Search"},{keys:["?"],description:"Toggle this help overlay",category:"Help"},{keys:["Escape"],description:"Exit cursor mode (or visual/search)",category:"Help"},{keys:["Alt+E"],description:"Close file viewer",category:"Help"},{keys:["q"],description:"Close file viewer",category:"Help"}],es=({onClose:s})=>{const{t:n}=le(["terminal"]),l=t.useCallback(i=>{i.target===i.currentTarget&&s()},[s]),c=t.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),s())},[s]),r=xa.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:l,onKeyDown:c,tabIndex:0,role:"dialog","aria-label":n("terminal:fileExplorer.keybindingsHelp"),children:e.jsxs("div",{className:"keybindings-help-content",children:[e.jsx("button",{className:"keybindings-help-close",onClick:s,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(T,{name:"close",size:14})}),e.jsx("h2",{className:"keybindings-help-title",children:n("terminal:fileExplorer.keybindingsHelp")}),e.jsx("p",{className:"keybindings-help-subtitle",children:n("terminal:fileExplorer.keybindingsSubtitle")}),e.jsx("div",{className:"keybindings-help-categories",children:Object.entries(r).map(([i,f])=>e.jsxs("div",{className:"keybindings-help-category",children:[e.jsx("h3",{className:"keybindings-help-category-title",children:i}),e.jsx("div",{className:"keybindings-help-list",children:f.map((o,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:o.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:o.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Is=t.lazy(()=>Dn(()=>import("./EmbeddedEditor-B9iQHzhz.js"),__vite__mapDeps([0,1,2,3,4,5])).then(s=>({default:s.EmbeddedEditor}))),ya=[".md",".mdx",".markdown"],Ps="file-viewer-markdown-render",ba=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",ja="https://kroki.io/plantuml/svg";function va(s){return ya.includes(s.toLowerCase())}function wa(s){return ba.includes(s.toLowerCase())}function Ca(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Ps);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ps,String(r))}catch{}return r})},[]);return[s,l]}function Na(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[s,l]}function ka(s){const n=new TextEncoder().encode(s);let l="";for(const c of n)l+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(l)}`}function Ge({file:s,rightContent:n,onRevealInTree:l,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,o]=t.useState("idle"),[u,g]=t.useState("idle"),j=s.fileType==="text"?Rt(s.extension):s.extension.slice(1).toUpperCase(),{settings:p}=zs(),b=async()=>{o("loading");try{const x=await q(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,...p.externalEditorCommand&&{editorCommand:p.externalEditorCommand}})});if(!x.ok){const N=await x.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",N),o("error"),setTimeout(()=>o("idle"),2e3);return}o("success"),setTimeout(()=>o("idle"),2e3)}catch(x){console.error("Error opening file in editor:",x),o("error"),setTimeout(()=>o("idle"),2e3)}},C=async()=>{if(s.path)try{await Ln(s.path),g("success"),setTimeout(()=>g("idle"),2e3)}catch(x){console.error("Error opening file explorer:",x),g("error"),setTimeout(()=>g("idle"),2e3)}},F=i("terminal:fileExplorer.openInFileExplorer");return e.jsxs("div",{className:"file-viewer-header",children:[e.jsxs("div",{className:"file-viewer-header-left",children:[e.jsx("span",{className:"file-viewer-filename",children:s.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[Os(s.size)," • ",j,s.content&&` • ${s.content.split(`
8
8
  `).length} lines`]})]}),e.jsxs("div",{className:"file-viewer-header-right",children:[r&&s.fileType==="text"&&e.jsx("button",{className:`file-viewer-edit-btn${c?" active":""}`,onClick:r,title:i(c?"terminal:fileExplorer.exitEdit":"terminal:fileExplorer.editFile"),children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 012.474 0l1.086 1.086a1.75 1.75 0 010 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 01-.927-.928l.929-3.25a1.75 1.75 0 01.445-.758l8.61-8.61zm1.414 1.06a.25.25 0 00-.354 0L3.463 11.1a.25.25 0 00-.064.108l-.558 1.953 1.953-.558a.25.25 0 00.108-.064l8.61-8.61a.25.25 0 000-.354l-1.086-1.086z"})})}),e.jsx("button",{className:`file-viewer-reveal-explorer-btn ${u}`,onClick:C,disabled:!s.path,title:F,"aria-label":F,children:u==="success"?e.jsx(T,{name:"check",size:14}):u==="error"?e.jsx(T,{name:"cross",size:14}):e.jsx(T,{name:"folder-open",size:14})}),e.jsx("button",{className:`file-viewer-open-editor-btn ${f}`,onClick:b,disabled:f==="loading",title:i(f==="error"?"terminal:fileExplorer.failedToOpenEditor":f==="success"?"terminal:fileExplorer.openingInEditor":"terminal:fileExplorer.openInEditor"),children:f==="success"?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 11-1.06-1.06l7.25-7.25a.75.75 0 011.06 0z"})}):f==="error"?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"})}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M1.5 1h6v1.5h-5v11h11v-5H15v6.5H0V1h1.5zm8 0H15v5.5h-1.5V3.56L7.28 9.78l-1.06-1.06L12.44 2.5H9.5V1z"})})}),l&&e.jsx("button",{className:"file-viewer-locate-btn",onClick:()=>l(s.path),title:i("terminal:fileExplorer.locateInTree"),children:e.jsx(T,{name:"target",size:14})}),n]})]})}function Ea({file:s,onRevealInTree:n,renderMarkdown:l,onToggleRender:c,editMode:r,onToggleEdit:i}){const f=t.useRef(null),o=t.useRef(null),u=t.useRef(null),{t:g}=le(["terminal","common"]),[j,p]=t.useState("idle"),[b,C]=t.useState("idle"),[F,x]=t.useState("idle"),[N,d]=t.useState("idle"),v=_s({containerRef:u,isEnabled:!0,content:s.content});t.useEffect(()=>{if(!l&&f.current){const H=Rt(s.extension);As(H).then(()=>{f.current&&Gs(f.current)})}},[s,l]);const w=t.useCallback(async()=>{if(!o.current){p("error"),setTimeout(()=>p("idle"),2e3);return}try{const H=o.current.innerHTML,ae=Rn(H),ee=o.current.innerText;await Fn(ae,ee),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},[]),R=t.useCallback(async()=>{if(!o.current){C("error"),setTimeout(()=>C("idle"),2e3);return}try{const H=o.current.innerHTML;await Kt(H),C("copied"),setTimeout(()=>C("idle"),2e3)}catch{C("error"),setTimeout(()=>C("idle"),2e3)}},[]),z=t.useCallback(async()=>{try{await Kt(s.content),x("copied"),setTimeout(()=>x("idle"),2e3)}catch{x("error"),setTimeout(()=>x("idle"),2e3)}},[s.content]),O=t.useCallback(async()=>{try{await Kt(s.content),d("copied"),setTimeout(()=>d("idle"),2e3)}catch{d("error"),setTimeout(()=>d("idle"),2e3)}},[s.content]),G=e.jsxs("div",{className:"file-viewer-header-buttons",children:[l&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:w,title:g("terminal:fileExplorer.copyRichTextTitle"),children:g(j==="copied"?"terminal:fileExplorer.copied":j==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyRichText")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${b}`,onClick:R,title:g("terminal:fileExplorer.copyHtmlTitle"),children:g(b==="copied"?"terminal:fileExplorer.copied":b==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyHtml")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${F}`,onClick:z,title:g("terminal:fileExplorer.copyMarkdownTitle"),children:g(F==="copied"?"terminal:fileExplorer.copied":F==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyMarkdown")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${N}`,onClick:O,title:g("terminal:fileExplorer.copyOriginalTitle"),children:g(N==="copied"?"terminal:fileExplorer.copied":N==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyOriginal")})]}),e.jsx("button",{className:`file-viewer-render-toggle ${l?"active":""}`,onClick:c,title:g(l?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderMarkdown"),children:l?"</>":"Aa"})]});return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:G,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[l?e.jsx("div",{className:"file-viewer-markdown-wrapper",children:e.jsx("div",{className:"markdown-content",ref:o,children:e.jsx(In,{remarkPlugins:[Pn],children:s.content})})}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:f,className:"language-markdown",children:s.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${v.currentLine}/${v.totalLines}`,children:v.scrollPercentage===100?"END":v.scrollPercentage===0?"TOP":`${v.scrollPercentage}%`}),v.searchActive&&e.jsx(Zt,{query:v.searchQuery,onQueryChange:v.setSearchQuery,matchCount:v.searchMatches.length,currentIndex:v.currentMatchIndex,onNext:v.nextMatch,onPrev:v.prevMatch,onClose:v.clearSearch})]}),v.helpActive&&e.jsx(es,{onClose:v.toggleHelp})]})}function Sa({file:s,onRevealInTree:n,renderPlantUml:l,onToggleRender:c,editMode:r,onToggleEdit:i}){const{t:f}=le(["terminal"]),o=t.useRef(null),u=t.useRef(null),[g,j]=t.useState(null),[p,b]=t.useState(!1),[C,F]=t.useState(null),x=_s({containerRef:u,isEnabled:!0,content:s.content});t.useEffect(()=>{if(!l&&o.current){const d=Rt(s.extension);As(d).then(()=>{o.current&&Gs(o.current)})}},[s,l]),t.useEffect(()=>{if(!l)return;if(!s.content.trim()){j(null),F("Diagram is empty");return}const d=new AbortController;return b(!0),F(null),(async()=>{try{const w=await fetch(ja,{method:"POST",headers:{"Content-Type":"text/plain; charset=utf-8",Accept:"image/svg+xml"},body:s.content,signal:d.signal});if(!w.ok)throw new Error(`Render failed (${w.status})`);const R=await w.text();if(!R.includes("<svg"))throw new Error("Invalid SVG output");j(ka(R))}catch(w){if(d.signal.aborted)return;const R=w instanceof Error?w.message:"Failed to render diagram";F(R),j(null)}finally{d.signal.aborted||b(!1)}})(),()=>d.abort()},[s.path,s.content,l]);const N=e.jsx("div",{className:"file-viewer-header-buttons",children:e.jsx("button",{className:`file-viewer-render-toggle ${l?"active":""}`,onClick:c,title:f(l?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderDiagram"),children:l?"</>":f("terminal:fileExplorer.diagram")})});return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:N,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[l?e.jsxs("div",{className:"file-viewer-diagram-wrapper",children:[p&&e.jsx("div",{className:"file-viewer-placeholder",children:f("terminal:fileExplorer.renderingDiagram")}),!p&&g&&e.jsx("img",{src:g,alt:s.filename,className:"file-viewer-diagram-image"}),!p&&C&&e.jsxs("div",{className:"file-viewer-diagram-error",children:[e.jsxs("div",{children:[f("terminal:fileExplorer.couldNotRender"),": ",C]}),e.jsx("button",{className:"file-viewer-render-toggle",onClick:c,children:f("terminal:fileExplorer.showSource")})]})]}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:o,className:"language-plaintext",children:s.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${x.currentLine}/${x.totalLines}`,children:x.scrollPercentage===100?"END":x.scrollPercentage===0?"TOP":`${x.scrollPercentage}%`}),x.searchActive&&e.jsx(Zt,{query:x.searchQuery,onQueryChange:x.setSearchQuery,matchCount:x.searchMatches.length,currentIndex:x.currentMatchIndex,onNext:x.nextMatch,onPrev:x.prevMatch,onClose:x.clearSearch})]}),x.helpActive&&e.jsx(es,{onClose:x.toggleHelp})]})}function Ta({file:s,onRevealInTree:n}){const{t:l}=le(["common","terminal"]),c=()=>{if(s.dataUrl){const r=document.createElement("a");r.href=s.dataUrl,r.download=s.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:l("common:buttons.download"),children:l("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-image-wrapper",children:s.dataUrl?e.jsx("img",{src:s.dataUrl,alt:s.filename,className:"file-viewer-image"}):e.jsx("div",{className:"file-viewer-placeholder",children:l("terminal:fileExplorer.failedToLoadImage")})})]})}function Ma({file:s,onRevealInTree:n}){const{t:l}=le(["common","terminal"]),c=()=>{if(s.dataUrl){const r=document.createElement("a");r.href=s.dataUrl,r.download=s.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:l("common:buttons.download"),children:l("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-pdf-wrapper",children:s.dataUrl?e.jsx("iframe",{src:s.dataUrl,title:s.filename,className:"file-viewer-pdf"}):e.jsx("div",{className:"file-viewer-placeholder",children:l("terminal:fileExplorer.failedToLoadPdf")})})]})}function Da({file:s,onRevealInTree:n}){const{t:l}=le(["terminal","common"]),c=()=>{if(s.dataUrl){const i=document.createElement("a");i.href=s.dataUrl,i.download=s.filename,i.click()}},r=()=>{const i=s.extension.toLowerCase();return[".xlsx",".xls"].includes(i)?e.jsx(T,{name:"dashboard",size:48}):[".docx",".doc"].includes(i)?e.jsx(T,{name:"edit",size:48}):[".pptx",".ppt"].includes(i)?e.jsx(T,{name:"film",size:48}):[".zip",".tar",".gz",".rar",".7z"].includes(i)?e.jsx(T,{name:"file-zip",size:48}):[".mp3",".wav",".flac",".ogg"].includes(i)?e.jsx(T,{name:"music-note",size:48}):[".mp4",".avi",".mov",".mkv",".webm"].includes(i)?e.jsx(T,{name:"film",size:48}):[".exe",".dmg",".app",".msi"].includes(i)?e.jsx(T,{name:"gear",size:48}):[".apk",".aab",".ipa"].includes(i)?e.jsx(T,{name:"mobile",size:48}):[".jar",".war",".ear"].includes(i)?e.jsx(T,{name:"coffee",size:48}):[".iso",".img"].includes(i)?e.jsx(T,{name:"disc",size:48}):[".so",".dll",".dylib"].includes(i)?e.jsx(T,{name:"wrench",size:48}):e.jsx(T,{name:"folder",size:48})};return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n}),e.jsxs("div",{className:"file-viewer-binary",children:[e.jsx("div",{className:"file-viewer-binary-icon",children:r()}),e.jsx("div",{className:"file-viewer-binary-name",children:s.filename}),e.jsx("div",{className:"file-viewer-binary-size",children:Os(s.size)}),e.jsx("div",{className:"file-viewer-binary-message",children:l("terminal:fileExplorer.cannotPreview")}),e.jsx("button",{className:"file-viewer-download-btn large",onClick:c,children:l("terminal:fileExplorer.downloadFile")})]})]})}function Ra({file:s,loading:n,error:l,onRevealInTree:c,onFileEdited:r}){const{t:i}=le(["terminal","common"]),[f,o]=Ca(),[u,g]=Na(),[j,p]=t.useState(!1);t.useEffect(()=>{p(!1)},[s==null?void 0:s.path]);const b=t.useCallback(async w=>{if(!s)return;const R=await q(K("/api/files/write"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,content:w})});if(!R.ok){const z=await R.json().catch(()=>({error:"Save failed"}));throw new Error(z.error||"Save failed")}},[s]),C=t.useCallback(()=>{p(w=>(w&&s&&(r==null||r(s.path)),!w))},[s,r]),F=t.useCallback(()=>{s&&(r==null||r(s.path))},[s,r]);if(n)return e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")});if(l)return e.jsx("div",{className:"file-viewer-placeholder error",children:l});if(!s)return e.jsxs("div",{className:"file-viewer-placeholder",children:[e.jsx("div",{className:"placeholder-icon",children:e.jsx(T,{name:"folder-open",size:32})}),e.jsx("div",{className:"placeholder-text",children:i("terminal:fileExplorer.selectFileToView")})]});const x=s.fileType||"text",N=x==="text"&&va(s.extension),d=x==="text"&&wa(s.extension),v=N||d;return v&&j&&s.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ge,{file:s,onRevealInTree:c,editMode:!0,onToggleEdit:C}),e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:s.content,extension:s.extension,onSave:b,onCancel:C},s.path)})]}):x==="text"&&!v&&s.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ge,{file:s,onRevealInTree:c}),e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:s.content,extension:s.extension,onSave:b,onCancel:F},s.path)})]}):e.jsxs("div",{className:"file-viewer-content",children:[N&&e.jsx(Ea,{file:s,onRevealInTree:c,renderMarkdown:f,onToggleRender:o,editMode:j,onToggleEdit:C}),d&&!N&&e.jsx(Sa,{file:s,onRevealInTree:c,renderPlantUml:u,onToggleRender:g,editMode:j,onToggleEdit:C}),x==="image"&&e.jsx(Ta,{file:s,onRevealInTree:c}),x==="pdf"&&e.jsx(Ma,{file:s,onRevealInTree:c}),x==="binary"&&e.jsx(Da,{file:s,onRevealInTree:c})]})}const Vs=t.memo(Ra,(s,n)=>s.loading!==n.loading||s.error!==n.error?!1:s.file===null&&n.file===null?!0:s.file===null||n.file===null?!1:s.file.path===n.file.path&&s.file.content===n.file.content&&s.file.modified===n.file.modified);Vs.displayName="FileViewer";function Ks({text:s,query:n}){if(!n)return e.jsx(e.Fragment,{children:s});const l=$n(s,n);if(l)return e.jsxs(e.Fragment,{children:[s.slice(0,l.start),e.jsx("mark",{className:"search-highlight",children:s.slice(l.start,l.end)}),s.slice(l.end)]});const c=n.toLowerCase(),i=s.toLowerCase().indexOf(c);return i===-1?e.jsx(e.Fragment,{children:s}):e.jsxs(e.Fragment,{children:[s.slice(0,i),e.jsx("mark",{className:"search-highlight",children:s.slice(i,i+n.length)}),s.slice(i+n.length)]})}const Fa=t.memo(function({node:n,query:l,isSelected:c,onSelect:r,lineNumber:i}){const f=n.isDirectory?null:Xt(n),o=n.path.split("/");o[o.length-1];const u=o.slice(0,-1).join("/");return e.jsxs("div",{className:`search-result-item ${c?"selected":""}`,onClick:()=>r(n),children:[n.isDirectory?e.jsx("span",{className:"search-result-icon",children:e.jsx(T,{name:"folder",size:14})}):f?e.jsx("span",{className:"search-result-icon",style:{backgroundImage:`url('${f}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"search-result-icon",children:e.jsx(T,{name:"file-text",size:14})}),e.jsxs("div",{className:"search-result-info",children:[e.jsxs("span",{className:"search-result-name",children:[e.jsx(Ks,{text:n.name,query:l}),i&&e.jsxs("span",{className:"search-result-line-badge",children:[":",i]})]}),e.jsx("span",{className:"search-result-path",children:u})]})]})}),Ia=t.memo(function({match:n,query:l,isSelected:c,onSelect:r}){const{t:i}=le(["terminal"]),f={name:n.name,path:n.path,isDirectory:!1,extension:n.extension},o=Xt(f),u=n.path.split("/"),g=u[u.length-1],j=u.slice(0,-1).join("/");return e.jsxs("div",{className:`content-search-item ${c?"selected":""}`,children:[e.jsxs("div",{className:`content-search-header ${c?"selected":""}`,onClick:()=>r(n.path),children:[o?e.jsx("span",{className:"content-search-icon",style:{backgroundImage:`url('${o}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"content-search-icon",children:e.jsx(T,{name:"file-text",size:14})}),e.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:"2px"},children:[e.jsx("span",{className:"content-search-name",children:g}),e.jsx("span",{className:"search-result-path",style:{fontSize:"10px"},children:j})]}),e.jsx("span",{className:"content-search-count",children:n.matches.length})]}),e.jsxs("div",{className:"content-search-matches",children:[n.matches.slice(0,5).map((p,b)=>e.jsxs("div",{className:"content-search-match",onClick:()=>r(n.path,p.line),children:[e.jsx("span",{className:"content-search-line-num",children:p.line}),e.jsx("span",{className:"content-search-line-content",children:e.jsx(Ks,{text:p.content.trim(),query:l})})]},`${n.path}-${p.line}-${b}`)),n.matches.length>5&&e.jsxs("div",{className:"content-search-match",style:{opacity:.6,cursor:"default"},children:[e.jsx("span",{className:"content-search-line-num",children:"..."}),e.jsx("span",{className:"content-search-line-content",children:i("terminal:fileExplorer.moreMatches",{count:n.matches.length-5})})]})]})]})});function Pa({filenameResults:s,contentResults:n,onSelectFile:l,onSelectContent:c,selectedPath:r,query:i,lineNumber:f}){const{t:o}=le(["terminal"]),u=s.length>0,g=n.length>0;return!u&&!g?e.jsx("div",{className:"search-no-results",children:o("terminal:fileExplorer.noMatchesFound")}):e.jsxs("div",{className:"unified-search-results",children:[u&&e.jsxs("div",{className:"unified-search-section",children:[e.jsxs("div",{className:"unified-search-section-header",children:[e.jsx("span",{className:"unified-search-section-icon",children:e.jsx(T,{name:"file-text",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:o("terminal:fileExplorer.files")}),e.jsx("span",{className:"unified-search-section-count",children:s.length})]}),e.jsx("div",{className:"unified-search-section-content",children:s.map(j=>e.jsx(Fa,{node:j,query:i,isSelected:r===j.path,onSelect:l,lineNumber:f},j.path))})]}),g&&e.jsxs("div",{className:"unified-search-section",children:[e.jsxs("div",{className:"unified-search-section-header",children:[e.jsx("span",{className:"unified-search-section-icon",children:e.jsx(T,{name:"edit",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:o("terminal:fileExplorer.content")}),e.jsx("span",{className:"unified-search-section-count",children:o("terminal:fileExplorer.matchesInFiles",{matches:n.reduce((j,p)=>j+p.matches.length,0),files:n.length})})]}),e.jsx("div",{className:"unified-search-section-content",children:n.map(j=>e.jsx(Ia,{match:j,query:i,isSelected:r===j.path,onSelect:c},j.path))})]})]})}const Ws=t.memo(Pa,(s,n)=>!(s.query!==n.query||s.selectedPath!==n.selectedPath||s.filenameResults.length!==n.filenameResults.length||s.contentResults.length!==n.contentResults.length));Ws.displayName="UnifiedSearchResults";const La=t.memo(function({file:n,isSelected:l,onSelect:c,onStage:r,isStaging:i,showDirPath:f,isChecked:o,onToggleCheck:u,onContextMenu:g,onDiscard:j}){const{t:p}=le(["terminal"]),b=n.status,C=pt[b],F=b==="deleted",x=b==="untracked"&&r,N=n.name.includes(".")?"."+n.name.split(".").pop():"",d=f&&n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"";return e.jsxs("div",{className:`git-file-item ${l?"selected":""}`,onClick:()=>!F&&c(n.path,b),onContextMenu:v=>{v.preventDefault(),g==null||g(v,n,b)},style:{cursor:F?"not-allowed":"pointer"},title:n.path,children:[u&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:o||!1,onChange:v=>{v.stopPropagation(),u(n.path)},onClick:v=>v.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:ft(N),alt:"file"}),e.jsxs("span",{className:"git-file-name",children:[n.name,d&&e.jsx("span",{className:"git-file-dir",children:d})]}),e.jsx("span",{className:"git-file-status",style:{color:C.color},children:C.icon}),n.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:[e.jsx(T,{name:"subitem",size:10,style:{transform:"rotate(180deg)"}})," ",n.oldPath.split("/").pop()]}),x&&e.jsx("button",{className:`git-stage-btn ${i?"staging":""}`,onClick:v=>{v.stopPropagation(),i||r(n.path)},title:p("terminal:fileExplorer.stageFile"),disabled:i,children:i?"...":"+"}),j&&e.jsx("button",{className:"git-discard-btn",onClick:v=>{v.stopPropagation(),j(n,b)},title:b==="untracked"||b==="added"?"Delete file":"Discard changes",children:e.jsx(T,{name:"revert",size:12})})]})}),$a=16,Ha=22,za=t.memo(function s({node:n,depth:l,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:o,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:b,onDiscard:C}){const{t:F}=le(["terminal"]),x=l*$a;if(!n.isDirectory){const d=n.file.status,v=pt[d];return e.jsxs("div",{className:`git-file-item ${i===n.path?"selected":""}`,onClick:()=>d!=="deleted"&&f(n.file.path,d),onContextMenu:w=>{w.preventDefault(),p==null||p(w,n.file,d)},style:{paddingLeft:`${x+Ha}px`,cursor:d==="deleted"?"not-allowed":"pointer"},title:n.file.path,children:[j&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:(g==null?void 0:g.has(n.file.path))||!1,onChange:w=>{w.stopPropagation(),j(n.file.path)},onClick:w=>w.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:ft(n.file.name.includes(".")?"."+n.file.name.split(".").pop():""),alt:"file"}),e.jsx("span",{className:"git-file-name",children:n.file.name}),e.jsx("span",{className:"git-file-status",style:{color:v.color},children:v.icon}),n.file.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:[e.jsx(T,{name:"subitem",size:10,style:{transform:"rotate(180deg)"}})," ",n.file.oldPath.split("/").pop()]}),d==="untracked"&&o&&e.jsx("button",{className:`git-stage-btn ${u!=null&&u.has(n.path)?"staging":""}`,onClick:w=>{w.stopPropagation(),u!=null&&u.has(n.path)||o(n.file.path)},title:F("terminal:fileExplorer.stageFile"),disabled:u==null?void 0:u.has(n.path),children:u!=null&&u.has(n.path)?"...":"+"}),C&&e.jsx("button",{className:"git-discard-btn",onClick:w=>{w.stopPropagation(),C(n.file,d)},title:d==="untracked"||d==="added"?"Delete file":"Discard changes",children:e.jsx(T,{name:"revert",size:12})})]})}const N=c.has(n.path);return e.jsxs("div",{className:"tree-node-wrapper",children:[e.jsxs("div",{className:`tree-node directory ${N?"expanded":""}`,style:{paddingLeft:`${x}px`},onClick:()=>r(n.path),onContextMenu:d=>{d.preventDefault(),d.stopPropagation(),b==null||b(d,n)},children:[e.jsx("span",{className:`tree-arrow ${N?"expanded":""}`,children:e.jsx(T,{name:"caret-right",size:10})}),e.jsx("img",{className:"tree-folder-icon",src:N?"/assets/vscode-icons/default_folder_opened.svg":"/assets/vscode-icons/default_folder.svg",alt:"folder"}),e.jsx("span",{className:"tree-name",children:n.name}),e.jsx("span",{className:"git-tree-file-count",children:F("terminal:fileExplorer.fileCount",{count:n.fileCount})})]}),N&&e.jsx("div",{className:"tree-children",children:n.children.map(d=>e.jsx(s,{node:d,depth:l+1,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:o,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:b,onDiscard:C},d.path))})]})}),Yt=t.memo(function({groupLabel:n,groupIcon:l,groupColor:c,files:r,treeNodes:i,viewMode:f,selectedPath:o,expandedDirs:u,onToggleDir:g,onFileSelect:j,onStageFile:p,onStageAll:b,stagingPaths:C,checkedFiles:F,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscardFile:v,onDiscardAll:w}){const{t:R}=le(["terminal"]);if(r.length===0)return null;const z=r.some(H=>H.status==="untracked"),O=z&&b&&r.length>0,G=C?r.every(H=>C.has(H.path)):!1;return e.jsxs("div",{className:"git-status-group",children:[e.jsxs("div",{className:"git-status-group-header",style:{color:c},children:[e.jsx("span",{className:"git-status-badge",style:{background:c},children:l}),n," (",r.length,")",O&&e.jsx("button",{className:`git-stage-all-btn ${G?"staging":""}`,onClick:H=>{H.stopPropagation(),G||b()},title:R("terminal:fileExplorer.stageAllUntracked"),disabled:G,children:G?"...":R("terminal:fileExplorer.stageAll")}),w&&e.jsxs("button",{className:"git-discard-all-btn",onClick:H=>{H.stopPropagation(),w()},title:z?`Delete all ${r.length} files`:`Discard all ${r.length} changes`,children:[e.jsx(T,{name:"revert",size:12})," All"]})]}),f==="tree"?e.jsx("div",{className:"git-tree-content",children:i.map(H=>e.jsx(za,{node:H,depth:0,expandedDirs:u,onToggleDir:g,selectedPath:o,onSelect:j,onStage:p,stagingPaths:C,checkedFiles:F,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscard:v},H.path))}):e.jsx("div",{className:"git-flat-content",children:r.map(H=>e.jsx(La,{file:H,isSelected:o===H.path,onSelect:j,onStage:H.status==="untracked"?p:void 0,isStaging:C==null?void 0:C.has(H.path),showDirPath:!0,isChecked:F==null?void 0:F.has(H.path),onToggleCheck:x,onContextMenu:N,onDiscard:v},H.path))})]})});function Oa({gitStatus:s,loading:n,onFileSelect:l,selectedPath:c,onRefresh:r,onStageFiles:i,stagingPaths:f,currentFolder:o,onCommitComplete:u,mergeInProgress:g,mergingBranch:j,onMergeContinue:p,onMergeAbort:b,onConflictOpen:C,onRevealInTree:F}){const{t:x}=le(["terminal","common"]),[N,d]=t.useState("tree"),[v,w]=t.useState(new Set),[R,z]=t.useState(""),[O,G]=t.useState(""),[H,ae]=t.useState(!1),[ee,M]=t.useState(new Set),[D,I]=t.useState(!1),[re,_]=t.useState(null),ge=t.useRef(null),{showToast:A}=Us(),[Z,L]=t.useState(null),[S,W]=t.useState(null),[se,be]=t.useState(null),de=t.useCallback((k,P)=>{be({files:[k],label:k.name})},[]),m=t.useCallback(async()=>{if(!(!se||!o))try{const k=await q(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:se.files.map(B=>({path:B.path,status:B.status})),directory:o})}),P=await k.json();k.ok&&P.success?(A("success","Discarded",`Reverted ${se.files.length} file(s)`),r()):A("error","Discard Failed",P.error||"Could not discard changes")}catch{A("error","Discard Failed","Network error")}finally{be(null)}},[se,o,r,A]),Y=t.useCallback((k,P,B)=>{k.preventDefault(),k.stopPropagation(),L({isOpen:!0,position:{x:k.clientX,y:k.clientY},file:P,status:B})},[]),ie=t.useCallback(async(k,P)=>{if(o)try{const B=await q(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{path:k.path,status:P}],directory:o})}),ke=await B.json();B.ok&&ke.success?(A("success","Discarded",`Restored ${k.name}`),r()):A("error","Discard Failed",ke.error||"Could not discard changes")}catch{A("error","Discard Failed","Network error")}},[o,r,A]),ue=t.useCallback(async k=>{try{await navigator.clipboard.writeText(k),A("success","Copied","Full path copied")}catch{A("error","Copy Failed","Could not copy path")}},[A]),V=t.useCallback(async k=>{const P=o&&k.startsWith(o+"/")?k.slice(o.length+1):k;try{await navigator.clipboard.writeText(P),A("success","Copied","Relative path copied")}catch{A("error","Copy Failed","Could not copy path")}},[o,A]),E=t.useMemo(()=>{if(!Z)return[];const{file:k,status:P}=Z,B=[];return P==="conflict"&&C?B.push({id:"open-conflict",label:x("terminal:fileExplorer.gitContextMenu.openConflictResolver"),icon:e.jsx(T,{name:"warn",size:14}),onClick:()=>C(k.path)}):P!=="deleted"&&B.push({id:"open-file",label:x("terminal:fileExplorer.gitContextMenu.openFile"),icon:e.jsx(T,{name:"file-text",size:14}),onClick:()=>l(k.path,P)}),P!=="conflict"&&B.push({id:"stage-file",label:x("terminal:fileExplorer.gitContextMenu.stageFile"),icon:e.jsx(T,{name:"plus",size:14}),onClick:()=>{i([k.path])}}),B.push({id:"divider-1",label:"",divider:!0,onClick:()=>{}}),(P==="modified"||P==="deleted"||P==="renamed"||P==="conflict")&&B.push({id:"discard-changes",label:x("terminal:fileExplorer.gitContextMenu.discardChanges"),icon:e.jsx(T,{name:"revert",size:14}),danger:!0,onClick:()=>{ie(k,P)}}),(P==="untracked"||P==="added")&&B.push({id:"delete-file",label:x("terminal:fileExplorer.gitContextMenu.deleteFile"),icon:e.jsx(T,{name:"trash",size:14}),danger:!0,onClick:()=>{ie(k,P)}}),B.push({id:"divider-2",label:"",divider:!0,onClick:()=>{}}),B.push({id:"copy-full-path",label:x("terminal:fileExplorer.gitContextMenu.copyFullPath"),icon:e.jsx(T,{name:"pin",size:14}),onClick:()=>{ue(k.path)}}),B.push({id:"copy-relative-path",label:x("terminal:fileExplorer.gitContextMenu.copyRelativePath"),icon:e.jsx(T,{name:"clipboard",size:14}),onClick:()=>{V(k.path)}}),F&&P!=="deleted"&&B.push({id:"reveal-in-tree",label:x("terminal:fileExplorer.gitContextMenu.revealInTree"),icon:e.jsx(T,{name:"target",size:14}),onClick:()=>F(k.path)}),B},[Z,l,i,C,F,ie,ue,V,x]),Q=t.useCallback((k,P)=>{k.preventDefault(),k.stopPropagation(),W({isOpen:!0,position:{x:k.clientX,y:k.clientY},node:P})},[]),te=t.useCallback(k=>!k.isDirectory&&k.file?[k.file]:k.children.flatMap(P=>te(P)),[]),Ne=t.useCallback(async k=>{if(!o)return;const P=te(k);if(P.length!==0)try{const B=await q(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:P.map(Te=>({path:Te.path,status:Te.status})),directory:o})}),ke=await B.json();B.ok&&ke.success?(A("success","Discarded",`Reverted ${P.length} file(s) in ${k.name}`),r()):A("error","Discard Failed",ke.error||"Could not discard changes")}catch{A("error","Discard Failed","Network error")}},[o,te,r,A]),xe=t.useMemo(()=>{if(!S)return[];const{node:k}=S,P=te(k);return[{id:"discard-dir",label:`Discard Changes (${P.length} files)`,icon:e.jsx(T,{name:"revert",size:14}),danger:!0,onClick:()=>{Ne(k)}},{id:"stage-dir",label:`Stage All (${P.length} files)`,icon:e.jsx(T,{name:"plus",size:14}),onClick:()=>{i(P.map(B=>B.path))}}]},[S,te,Ne,i]),U=t.useCallback(k=>{w(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),{conflictFiles:ne,conflictTree:pe,changesFiles:me,changesTree:Ue,untrackedFiles:Se,untrackedTree:Ft,allDirPaths:He}=t.useMemo(()=>{if(!s||!s.isGitRepo||s.files.length===0)return{conflictFiles:[],conflictTree:[],changesFiles:[],changesTree:[],untrackedFiles:[],untrackedTree:[],allDirPaths:new Set};const k=new Set,P=s.files.filter(Re=>Re.status==="conflict"),B=Tt(P);Mt(B,k);const ke=s.files.filter(Re=>Re.status==="modified"||Re.status==="added"||Re.status==="deleted"||Re.status==="renamed"),Te=Tt(ke);Mt(Te,k);const ot=s.files.filter(Re=>Re.status==="untracked"),Ke=Tt(ot);return Mt(Ke,k),{conflictFiles:P,conflictTree:B,changesFiles:ke,changesTree:Te,untrackedFiles:ot,untrackedTree:Ke,allDirPaths:k}},[s]);t.useEffect(()=>{w(He)},[He]),t.useEffect(()=>{s!=null&&s.files&&M(new Set(s.files.map(k=>k.path)))},[s==null?void 0:s.files]);const It=t.useCallback(()=>{me.length!==0&&be({files:me,label:`${me.length} changed files`})},[me]),Be=t.useCallback(()=>{Se.length!==0&&be({files:Se,label:`${Se.length} unversioned files`})},[Se]),Pt=t.useCallback(()=>{ne.length!==0&&be({files:ne,label:`${ne.length} conflicted files`})},[ne]),_e=ne.length>0;t.useEffect(()=>{if(re){const k=re.type==="error"?8e3:4e3,P=setTimeout(()=>_(null),k);return()=>clearTimeout(P)}},[re]);const gt=t.useCallback(async()=>{const k=!H;if(ae(k),k&&o){G(R);try{const B=await(await q(K(`/api/files/git-log-message?path=${encodeURIComponent(o)}`))).json();B.message&&z(B.message)}catch{}}else z(O)},[H,o,R,O]),je=t.useCallback(k=>{M(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),Lt=t.useCallback(()=>{if(!(s!=null&&s.files))return;const k=s.files.map(B=>B.path),P=k.every(B=>ee.has(B));M(P?new Set:new Set(k))},[s==null?void 0:s.files,ee]),ve=t.useCallback(async k=>{if(!(!o||!R.trim()||ee.size===0||D)){I(!0),_(null);try{const P=await q(K("/api/files/git-commit"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:o,message:R.trim(),amend:H,paths:Array.from(ee)})}),B=await P.json();if(!P.ok||!B.success){_({type:"error",text:B.error||"Commit failed"}),I(!1);return}if(k)try{const ke=await q(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:o})}),Te=await ke.json();ke.ok&&Te.success?_({type:"success",text:x("terminal:fileExplorer.committedAndPushed")}):_({type:"error",text:x("terminal:fileExplorer.committedButPushFailed",{error:Te.error||"Unknown error"})})}catch{_({type:"error",text:x("terminal:fileExplorer.committedButPushFailed",{error:"Network error"})})}else _({type:"success",text:x("terminal:fileExplorer.committedSuccessfully")});z(""),G(""),ae(!1),r(),u==null||u()}catch(P){_({type:"error",text:P.message||"Commit failed"})}finally{I(!1)}}},[o,R,H,ee,D,r,u]);if(n)return e.jsx("div",{className:"git-changes-loading",children:x("terminal:fileExplorer.loadingGitStatus")});if(!s||!s.isGitRepo)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(T,{name:"package",size:32})}),e.jsx("div",{className:"git-empty-text",children:x("terminal:fileExplorer.notGitRepo")})]});if(s.files.length===0)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(T,{name:"sparkle",size:32})}),e.jsx("div",{className:"git-empty-text",children:x("terminal:fileExplorer.workingTreeClean")}),e.jsx("div",{className:"git-empty-branch",children:x("terminal:fileExplorer.onBranch",{branch:s.branch})})]});const xt=k=>{i([k])},Ve=()=>{const k=Se.map(P=>P.path);k.length>0&&i(k)},De=(k,P)=>{P==="conflict"&&C?C(k):l(k,P)};return e.jsxs("div",{className:"git-changes",children:[e.jsxs("div",{className:"git-changes-header",children:[e.jsxs("span",{className:"git-branch",children:[e.jsx("span",{className:"git-branch-icon",children:e.jsx(T,{name:"git-branch",size:12})}),s.branch]}),s.counts&&e.jsxs("div",{className:"git-changes-summary",children:[(s.counts.conflict??0)>0&&e.jsxs("span",{className:"git-count conflict",children:[s.counts.conflict,"C"]}),s.counts.modified>0&&e.jsxs("span",{className:"git-count modified",children:[s.counts.modified,"M"]}),s.counts.added>0&&e.jsxs("span",{className:"git-count added",children:[s.counts.added,"A"]}),s.counts.deleted>0&&e.jsxs("span",{className:"git-count deleted",children:[s.counts.deleted,"D"]}),s.counts.untracked>0&&e.jsxs("span",{className:"git-count untracked",children:[s.counts.untracked,"?"]})]}),e.jsxs("div",{className:"git-view-toggle",children:[e.jsx("button",{className:`git-view-toggle-btn ${N==="flat"?"active":""}`,onClick:()=>d("flat"),title:x("terminal:fileExplorer.flatList"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"2",y:"3",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"7",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"11",width:"12",height:"1.5",rx:"0.5"})]})}),e.jsx("button",{className:`git-view-toggle-btn ${N==="tree"?"active":""}`,onClick:()=>d("tree"),title:x("terminal:fileExplorer.directoryTree"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"1",y:"2",width:"6",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"5.5",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"9",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"7",y:"12.5",width:"7",height:"1.5",rx:"0.5"})]})})]}),e.jsx("button",{className:"git-refresh-btn",onClick:r,title:x("common:buttons.refresh"),children:e.jsx(T,{name:"refresh",size:12})})]}),g&&e.jsxs("div",{className:"git-merge-banner",children:[e.jsx("span",{className:"git-merge-banner-icon",children:"⚠"}),e.jsx("span",{className:"git-merge-banner-text",children:x("terminal:fileExplorer.mergeInProgress",{branch:j?` (${j})`:""})}),e.jsxs("div",{className:"git-merge-actions",children:[e.jsx("button",{className:"git-merge-continue-btn",onClick:p,disabled:_e,title:x(_e?"terminal:fileExplorer.resolveAllConflictsFirst":"terminal:fileExplorer.continueMerge"),children:x("terminal:fileExplorer.continue")}),e.jsx("button",{className:"git-merge-abort-btn",onClick:b,title:x("terminal:fileExplorer.abortMerge"),children:x("terminal:fileExplorer.abort")})]})]}),e.jsxs("div",{className:"git-changes-list",children:[e.jsx(Yt,{groupLabel:x("terminal:fileExplorer.gitGroups.conflicts"),groupIcon:"C",groupColor:"#ff5555",files:ne,treeNodes:pe,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:Y,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Pt}),e.jsx(Yt,{groupLabel:x("terminal:fileExplorer.gitGroups.changes"),groupIcon:"~",groupColor:"#c89a5a",files:me,treeNodes:Ue,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:Y,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:It}),e.jsx(Yt,{groupLabel:x("terminal:fileExplorer.gitGroups.unversioned"),groupIcon:"?",groupColor:"#6ab8c8",files:Se,treeNodes:Ft,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,onStageFile:xt,onStageAll:Ve,stagingPaths:f,checkedFiles:ee,onToggleCheck:je,onContextMenu:Y,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Be})]}),e.jsxs("div",{className:"git-commit-panel",children:[e.jsxs("div",{className:"git-commit-options",children:[e.jsxs("label",{className:"git-commit-amend-label",children:[e.jsx("input",{type:"checkbox",className:"git-commit-amend-checkbox",checked:H,onChange:gt}),x("terminal:fileExplorer.amend")]}),e.jsx("span",{className:"git-commit-file-count",children:x("terminal:fileExplorer.fileCount",{count:ee.size})}),e.jsx("button",{className:"git-commit-select-toggle",onClick:Lt,title:ee.size===s.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll"),children:ee.size===s.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll")})]}),e.jsx("textarea",{ref:ge,className:"git-commit-message",placeholder:x("terminal:fileExplorer.commitMessagePlaceholder"),value:R,onChange:k=>z(k.target.value),onKeyDown:k=>{(k.metaKey||k.ctrlKey)&&k.key==="Enter"&&(k.preventDefault(),ve(!1)),(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="Enter"&&(k.preventDefault(),ve(!0)),k.stopPropagation()},rows:3,disabled:D}),re&&e.jsx("div",{className:`git-commit-status ${re.type}`,children:re.text}),e.jsxs("div",{className:"git-commit-actions",children:[e.jsx("button",{className:"git-commit-btn",onClick:()=>ve(!1),disabled:!R.trim()||ee.size===0||D,title:x("terminal:fileExplorer.commitCtrlEnter"),children:x(D?"terminal:fileExplorer.committing":"terminal:fileExplorer.commitAction")}),e.jsx("button",{className:"git-commit-push-btn",onClick:()=>ve(!0),disabled:!R.trim()||ee.size===0||D,title:x("terminal:fileExplorer.commitAndPushCtrlShiftEnter"),children:D?"...":x("terminal:fileExplorer.commitAndPush")})]})]}),Z&&e.jsx(it,{isOpen:Z.isOpen,position:Z.position,worldPosition:{x:0,z:0},actions:E,onClose:()=>L(null)}),S&&e.jsx(it,{isOpen:S.isOpen,position:S.position,worldPosition:{x:0,z:0},actions:xe,onClose:()=>W(null)}),se&&e.jsx("div",{className:"git-discard-confirm-overlay",onClick:()=>be(null),children:e.jsxs("div",{className:"git-discard-confirm",onClick:k=>k.stopPropagation(),children:[e.jsx("p",{children:se.files.some(k=>k.status==="untracked"||k.status==="added")?e.jsxs(e.Fragment,{children:["Delete ",e.jsx("strong",{children:se.label}),"?"]}):e.jsxs(e.Fragment,{children:["Discard changes to ",e.jsx("strong",{children:se.label}),"?"]})}),e.jsx("p",{className:"git-discard-confirm-hint",children:"This cannot be undone."}),e.jsxs("div",{className:"git-discard-confirm-actions",children:[e.jsx("button",{className:"git-discard-confirm-cancel",onClick:()=>be(null),children:"Cancel"}),e.jsx("button",{className:"git-discard-confirm-btn",onClick:m,children:se.files.some(k=>k.status==="untracked"||k.status==="added")?"Delete":"Discard"})]})]})})]})}const qs=t.memo(Oa,(s,n)=>s.loading!==n.loading||s.selectedPath!==n.selectedPath||s.stagingPaths!==n.stagingPaths||s.currentFolder!==n.currentFolder||s.mergeInProgress!==n.mergeInProgress||s.mergingBranch!==n.mergingBranch?!1:s.gitStatus===null&&n.gitStatus===null?!0:!(s.gitStatus===null||n.gitStatus===null||s.gitStatus.isGitRepo!==n.gitStatus.isGitRepo||s.gitStatus.branch!==n.gitStatus.branch||s.gitStatus.files.length!==n.gitStatus.files.length||s.gitStatus.mergeInProgress!==n.gitStatus.mergeInProgress));qs.displayName="GitChanges";const Aa=t.memo(function({tab:n,isActive:l,onSelect:c,onClose:r,onContextMenu:i}){const{t:f}=le(["terminal"]),o={name:n.filename,path:n.path,isDirectory:!1,extension:n.extension},u=t.useCallback(()=>{c(n.path)},[c,n.path]),g=t.useCallback(b=>{b.button===1&&(b.preventDefault(),b.stopPropagation(),r(n.path))},[r,n.path]),j=t.useCallback(b=>{b.preventDefault(),b.stopPropagation(),r(n.path)},[r,n.path]),p=t.useCallback(b=>{b.preventDefault(),b.stopPropagation(),i(b,n)},[i,n]);return e.jsxs("div",{className:`file-tab ${l?"active":""}`,onClick:u,onMouseDown:g,onContextMenu:p,title:n.path,children:[e.jsx("img",{className:"file-tab-icon",src:Xt(o),alt:"file"}),e.jsx("span",{className:"file-tab-name",children:n.filename}),e.jsx("button",{className:"file-tab-close",onClick:j,title:f("terminal:fileExplorer.closeMiddleClick"),children:"×"})]})});function Ga(s){return typeof s.path=="string"&&s.path.startsWith("/")}function Ua({tabs:s,activeTabPath:n,onSelectTab:l,onCloseTab:c,onShowGitHistory:r}){const{t:i}=le(["terminal"]),[f,o]=t.useState(null),u=t.useCallback((p,b)=>{o({isOpen:!0,position:{x:p.clientX,y:p.clientY},tab:b})},[]),g=t.useCallback(()=>o(null),[]),j=t.useMemo(()=>{if(!f)return[];const p=f.tab,b=!!r&&Ga(p);return[{id:"git-history",label:i("terminal:fileExplorer.showGitHistory")??"Show Git History",icon:e.jsx(T,{name:"git-commit",size:14}),disabled:!b,onClick:()=>{b&&r(p.path)}}]},[f,r,i]);return s.length===0?null:e.jsxs("div",{className:"file-tabs-bar",children:[e.jsx("div",{className:"file-tabs-container",children:s.map(p=>e.jsx(Aa,{tab:p,isActive:n===p.path,onSelect:l,onClose:c,onContextMenu:u},p.path))}),f&&e.jsx(it,{isOpen:f.isOpen,position:f.position,worldPosition:{x:0,z:0},actions:j,onClose:g})]})}const Ys=t.memo(Ua,(s,n)=>{if(s.activeTabPath!==n.activeTabPath||s.tabs.length!==n.tabs.length||s.onShowGitHistory!==n.onShowGitHistory)return!1;for(let l=0;l<s.tabs.length;l++)if(s.tabs[l].path!==n.tabs[l].path)return!1;return!0});Ys.displayName="FileTabs";const Ba=t.memo(function({currentFolder:n,gitStatus:l,onBranchChanged:c,onMerge:r,onCompare:i,onPullConflicts:f}){const{t:o}=le(["terminal","common"]),[u,g]=t.useState(!1),[j,p]=t.useState(""),[b,C]=t.useState(!1),[F,x]=t.useState(""),[N,d]=t.useState(!1),[v,w]=t.useState(null),[R,z]=t.useState(null),O=t.useRef(null),G=t.useRef(null),H=t.useRef(null),{branches:ae,loading:ee,operationInProgress:M,loadBranches:D,checkoutBranch:I,createBranch:re,pullFromRemote:_,pushToRemote:ge}=Qt();t.useEffect(()=>{u&&n&&(D(n),setTimeout(()=>{var E;return(E=G.current)==null?void 0:E.focus()},50)),u||(p(""),C(!1),x(""),w(null))},[u,n,D]),t.useEffect(()=>{if(v){const E=v.type==="error"?8e3:3e3,Q=setTimeout(()=>w(null),E);return()=>clearTimeout(Q)}},[v]),t.useEffect(()=>{b&&setTimeout(()=>{var E;return(E=H.current)==null?void 0:E.focus()},50)},[b]),t.useEffect(()=>{if(!u)return;const E=te=>{const Ne=te.target;!Ne.closest(".branch-widget-selector")&&!Ne.closest(".branch-widget-dropdown")&&g(!1)},Q=te=>{te.key==="Escape"&&(te.preventDefault(),te.stopPropagation(),g(!1))};return document.addEventListener("click",E),document.addEventListener("keydown",Q,!0),()=>{document.removeEventListener("click",E),document.removeEventListener("keydown",Q,!0)}},[u]);const A=t.useCallback(async E=>{if(!n||M||E.isCurrent)return;const Q=await I(n,E.name);Q.success?(w({type:"success",text:o("terminal:fileExplorer.switchedToBranch",{branch:Q.branch||E.name})}),c(),D(n)):w({type:"error",text:Q.error||o("terminal:fileExplorer.checkoutFailed")})},[n,M,I,c,D]),Z=t.useCallback(async()=>{if(!n||!F.trim()||M)return;const E=await re(n,F.trim());E.success?(w({type:"success",text:o("terminal:fileExplorer.createdBranch",{branch:E.branch})}),C(!1),x(""),c(),D(n)):w({type:"error",text:E.error||o("terminal:fileExplorer.createBranchFailed")})},[n,F,M,re,c,D]),L=t.useCallback(async()=>{if(!n||M)return;const E=await _(n);E.success?(E.stashConflicts&&E.stashConflicts.length>0?(w({type:"error",text:`Pull succeeded but stash pop had conflicts: ${E.stashConflicts.length} file(s). Resolve manually.`}),f==null||f(E.stashConflicts),g(!1)):E.stashed?w({type:"success",text:"Pull complete. Local changes were auto-stashed and restored."}):w({type:"success",text:o("terminal:fileExplorer.pullComplete")}),c(),D(n)):E.conflicts&&E.conflicts.length>0?(w({type:"error",text:`Pull conflicts: ${E.conflicts.length} file(s)`}),f==null||f(E.conflicts),g(!1)):w({type:"error",text:E.error||o("terminal:fileExplorer.pullFailed")})},[n,M,_,c,D,f]),S=t.useCallback(async()=>{if(!n||M)return;const E=await ge(n);E.success?w({type:"success",text:o("terminal:fileExplorer.pushComplete")}):w({type:"error",text:E.error||o("terminal:fileExplorer.pushFailed")})},[n,M,ge]),[W,se]=t.useState(!1),be=t.useCallback(async()=>{if(!(!n||M||W)){se(!0);try{const E=await q(K("/api/files/git-fetch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(E.ok)w({type:"success",text:"Fetch complete"}),c(),D(n);else{const Q=await E.json().catch(()=>({error:"Fetch failed"}));w({type:"error",text:Q.error||"Fetch failed"})}}catch{w({type:"error",text:"Fetch failed"})}finally{se(!1)}}},[n,M,W,c,D]),de=(l==null?void 0:l.branch)||"unknown",m=!!M,Y=t.useCallback((E,Q)=>{Q.isCurrent||(E.preventDefault(),E.stopPropagation(),z({isOpen:!0,position:{x:E.clientX,y:E.clientY},branch:Q.name}))},[]),ie=t.useMemo(()=>{if(!R)return[];const E=!!M||(l==null?void 0:l.mergeInProgress);return[{id:"compare",label:o("terminal:fileExplorer.showDiffWith",{branch:R.branch}),icon:e.jsx(T,{name:"arrows-horizontal",size:14}),disabled:!!M,onClick:()=>{i==null||i(R.branch),g(!1)}},{id:"merge",label:o("terminal:fileExplorer.mergeInto",{source:R.branch,target:de}),icon:"⤵",disabled:!!E,onClick:()=>{r&&r(R.branch),g(!1)}},{id:"divider-1",label:"",divider:!0,onClick:()=>{}},{id:"checkout",label:o("terminal:fileExplorer.checkoutBranch",{branch:R.branch}),icon:e.jsx(T,{name:"git-branch",size:14}),disabled:!!M,onClick:()=>{const Q=ae.find(te=>te.name===R.branch);Q&&A(Q)}}]},[R,M,l==null?void 0:l.mergeInProgress,de,r,i,ae,A]),ue=t.useMemo(()=>{const E=ae.filter(te=>!te.isRemote);if(!j)return E;const Q=j.toLowerCase();return E.filter(te=>te.name.toLowerCase().includes(Q))},[ae,j]),V=t.useMemo(()=>{const E=ae.filter(te=>te.isRemote);if(!j)return E;const Q=j.toLowerCase();return E.filter(te=>te.name.toLowerCase().includes(Q))},[ae,j]);return e.jsxs("div",{className:"branch-widget",style:{position:"relative"},children:[e.jsxs("div",{className:"branch-widget-selector",onClick:E=>{E.stopPropagation(),g(!u)},title:`Branch: ${de}`,children:[e.jsx("svg",{className:"branch-widget-icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M5 3.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm0 2.122a2.25 2.25 0 1 0-1 0v1.836A2.25 2.25 0 0 0 5.75 9.5h1.378a2.251 2.251 0 1 0 0-1H5.75a1.25 1.25 0 0 1-1.25-1.25V5.372Zm7.75 4.878a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3-8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"})}),e.jsx("span",{className:"branch-widget-name",children:de}),e.jsx("span",{className:"branch-widget-arrow",children:"▼"})]}),u&&e.jsxs("div",{className:"branch-widget-dropdown",ref:O,children:[e.jsx("div",{className:"branch-widget-search",children:e.jsx("input",{ref:G,type:"text",className:"branch-widget-search-input",placeholder:o("terminal:fileExplorer.searchBranches"),value:j,onChange:E=>p(E.target.value),onKeyDown:E=>E.stopPropagation()})}),v&&e.jsx("div",{className:`branch-widget-status ${v.type}`,children:v.text}),e.jsx("div",{className:"branch-widget-section-header",children:o("terminal:fileExplorer.actions")}),e.jsxs("div",{className:"branch-widget-actions",children:[e.jsxs("div",{className:`branch-widget-action-item ${m||W?"disabled":""}`,onClick:be,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 13l-3-3h2V6h2v4h2l-3 3zM8 3l3 3h-2v4H7V6H5l3-3z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:W?"Fetching...":"Fetch"})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:L,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 12l-4-4h2.5V3h3v5H12L8 12z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:o(M==="pull"?"terminal:fileExplorer.pulling":"terminal:fileExplorer.pull")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:S,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 4l4 4h-2.5v5h-3V8H4l4-4z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:o(M==="push"?"terminal:fileExplorer.pushing":"terminal:fileExplorer.push")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:()=>{m||C(!b)},children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 2v5H3v2h5v5h2V9h5V7H10V2H8z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:o("terminal:fileExplorer.newBranch")})]})]}),b&&e.jsxs("div",{className:"branch-widget-new-branch",children:[e.jsx("input",{ref:H,type:"text",className:"branch-widget-new-branch-input",placeholder:o("terminal:fileExplorer.branchNamePlaceholder"),value:F,onChange:E=>x(E.target.value),onKeyDown:E=>{E.stopPropagation(),E.key==="Enter"&&Z(),E.key==="Escape"&&(C(!1),x(""))}}),e.jsx("button",{className:"branch-widget-new-branch-confirm",onClick:Z,disabled:!F.trim()||m,children:M==="create"?"...":o("common:buttons.create")})]}),e.jsxs("div",{className:"branch-widget-section-header",children:[o("terminal:fileExplorer.localBranches"),ee&&e.jsxs("span",{className:"branch-widget-loading-hint",children:[" ",o("terminal:fileExplorer.loading")]})]}),e.jsxs("div",{className:"branch-widget-branch-list",children:[ue.length===0&&!ee&&e.jsx("div",{className:"branch-widget-empty",children:o("terminal:fileExplorer.noBranchesFound")}),ue.map(E=>e.jsxs("div",{className:`branch-widget-branch-item ${E.isCurrent?"current":""} ${m?"disabled":""}`,onClick:()=>A(E),onContextMenu:Q=>Y(Q,E),title:E.lastMessage||E.name,children:[e.jsxs("span",{className:"branch-widget-branch-name",children:[E.isCurrent&&e.jsx("span",{className:"branch-widget-current-marker",children:"*"}),E.name]}),E.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:E.lastCommit})]},E.name))]}),V.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"branch-widget-section-header clickable",onClick:()=>d(!N),children:[e.jsx("span",{className:"branch-widget-section-toggle",children:N?"▾":"▸"}),o("terminal:fileExplorer.remoteBranches",{count:V.length})]}),N&&e.jsx("div",{className:"branch-widget-branch-list",children:V.map(E=>e.jsxs("div",{className:`branch-widget-branch-item remote ${m?"disabled":""}`,onClick:()=>A(E),onContextMenu:Q=>Y(Q,E),title:E.lastMessage||E.name,children:[e.jsx("span",{className:"branch-widget-branch-name",children:E.name}),E.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:E.lastCommit})]},E.name))})]})]}),R&&e.jsx(it,{isOpen:R.isOpen,position:R.position,worldPosition:{x:0,z:0},actions:ie,onClose:()=>z(null)})]})});function _a(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function St(s,n){if(!s)return"";const l=Es.languages[n];return l?Es.highlight(s,l,n):_a(s)}function Va(s){const n=[],l=s.split(`
9
9
  `);let c=[],r=!1,i=[],f=[],o=!1;for(const u of l)u.startsWith("<<<<<<<")?(c.length>0&&(n.push({type:"unchanged",content:c.join(`
10
10
  `)}),c=[]),r=!0,o=!1,i=[],f=[]):u.startsWith("=======")&&r?o=!0:u.startsWith(">>>>>>>")&&r?(n.push({type:"conflict",ours:i.join(`