tide-commander 1.111.1 → 1.111.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/assets/{BossLogsModal-C1li4cnA.js → BossLogsModal-DLTh_jKZ.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-BJ-fx5zF.js → BossSpawnModal-DzivoRl1.js} +1 -1
  3. package/dist/assets/{ControlsModal-CHKX3bwB.js → ControlsModal-B8j6My0t.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-CwtdNToh.js → DockerLogsModal-BNwx7lVp.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-BTRUWN3W.js → EmbeddedEditor-CBoOoGL8.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-CxGheYrE.js → GmailOAuthSetup-BACIjX54.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-CqcDFcuw.js → GoogleOAuthSetup-BuASGyWh.js} +1 -1
  8. package/dist/assets/{IframeModal-DCI2xBDs.js → IframeModal-ckpeQpQB.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-BsBSuc5U.js → IntegrationsPanel-Dh7UOnTC.js} +2 -2
  10. package/dist/assets/{LogViewerModal-Cs4_VfRa.js → LogViewerModal-Cj7Hv-mD.js} +1 -1
  11. package/dist/assets/{MonitoringModal-CcQ0zYEr.js → MonitoringModal-Bx4vcjBr.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-r4FAIdxy.js → PM2LogsModal-RBIjfi4J.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-DqqxPSu-.js → RestoreArchivedAreaModal-BBYlYIso.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-_RP_XoMQ.js → Scene2DCanvas-CYB1Y5Wa.js} +1 -1
  15. package/dist/assets/{SceneManager-CD6E0rIP.js → SceneManager-6vk047Kd.js} +1 -1
  16. package/dist/assets/{SkillsPanel-CNEhrh4l.js → SkillsPanel-CRRypqdy.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-Cjylwazt.js → SlackMultiInstanceSetup-DisMBGxX.js} +1 -1
  18. package/dist/assets/{SpawnModal-hEtOcN47.js → SpawnModal-qiu5nT-F.js} +1 -1
  19. package/dist/assets/{StatisticsModal-BYA9cfTG.js → StatisticsModal-Bzk7qqOd.js} +1 -1
  20. package/dist/assets/{SubordinateAssignmentModal-CzcBncW1.js → SubordinateAssignmentModal-AUCAiGkE.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-DsOfMpov.js → TriggerManagerPanel-56SuYzNh.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-BHDvK1D5.js → WorkflowEditorPanel-H0IGkyMd.js} +1 -1
  23. package/dist/assets/{index-XGwd-4sy.js → index--3sQ1gHE.js} +3 -3
  24. package/dist/assets/{index-DtKnq4Lr.js → index-94AqwQn0.js} +1 -1
  25. package/dist/assets/{index-CxvFEZYp.js → index-9NugNkE4.js} +1 -1
  26. package/dist/assets/{index-Buzi9_q1.js → index-C-kx99MP.js} +1 -1
  27. package/dist/assets/{index-mCP4-x_q.js → index-DFWA70Lq.js} +1 -1
  28. package/dist/assets/{index-HTRPdYbU.js → index-DY395tVJ.js} +2 -2
  29. package/dist/assets/{index-C3dHJ4j6.js → index-DZP3fZ3b.js} +1 -1
  30. package/dist/assets/{index-DlUMlSJy.js → index-Dv0tQnLX.js} +1 -1
  31. package/dist/assets/{index-CPCKwSnq.js → index-pRI5GcXd.js} +1 -1
  32. package/dist/assets/{main-Cq5TB_d6.js → main-Bon1sZAi.js} +64 -64
  33. package/dist/assets/{web-BO9rHZoK.js → web-CccJFC0m.js} +1 -1
  34. package/dist/assets/{web-C4r_DTuF.js → web-CdhZGenV.js} +1 -1
  35. package/dist/assets/{web-CfhEju0q.js → web-RZLwjKCT.js} +1 -1
  36. package/dist/index.html +1 -1
  37. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-BTRUWN3W.js","assets/main-Cq5TB_d6.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-BUSv52j9.css","assets/EmbeddedEditor-O_u2UVA4.css"])))=>i.map(i=>d[i]);
2
- import{r as s,aM as Y,l as K,a_ as Kt,M as $s,S as Rt,N as Hs,s as mt,u as le,j as e,I as M,bB as Ft,f as zs,bC as As,bD as Rn,bE as Os,bF as Gs,bG as Fn,bH as In,bI as Tt,bJ as Pn,bK as Ln,bL as $n,bM as Xt,bN as Hn,bO as Us,bP as Mt,bQ as Dt,ac as it,bR as ft,bS as pt,bT as Es,bU as zn,b6 as An,bV as Jt,bW as On,bX as Gn,bY as Ss,C as Un,n as Bn}from"./main-Cq5TB_d6.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function _n(t){const[n,o]=s.useState(null),[c,r]=s.useState(!1),i=s.useCallback(async()=>{if(t){r(!0);try{const f=await Y(K(`/api/files/git-status?path=${encodeURIComponent(t)}`)),l=await f.json();f.ok?o(l):o({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),o({isGitRepo:!1,files:[]})}finally{r(!1)}}},[t]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function Vn(t){try{const n=await Y(K(`/api/files/git-original?path=${encodeURIComponent(t)}`)),o=await n.json();return n.ok&&!o.isNew?{content:o.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const Kn=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",""]),Wn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Yn=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 Jn(t){const n=t.toLowerCase();return Wn.has(n)?"image":Yn.has(n)?"pdf":qn.has(n)?"binary":(Kn.has(n),"text")}function Xn(){const[t,n]=s.useState(null),[o,c]=s.useState(!1),[r,i]=s.useState(null),f=s.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),y=Jn(p),C=u.substring(u.lastIndexOf("/")+1);if(y==="image"){const N=await Y(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(y==="pdf"){const N=await Y(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(Kt())}`)});return}if(y==="binary"){const N=await Y(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(Kt())}`)});return}const R=await Y(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await R.json();if(!R.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const N=await Y(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(Kt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const y=p instanceof Error?p.message:"Failed to load file";i(y),n(null)}finally{c(!1)}},[]),l=s.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:t,loading:o,error:r,loadFile:f,clearFile:l,setFile:n}}const Wt="file-explorer-state",Qn=10080*60*1e3;function Zn(t,n){return n?`${Wt}-folder-${n}`:t?`${Wt}-area-${t}`:`${Wt}-default`}async function ea(t){try{const n=await Y(K(`/api/files/exists?path=${encodeURIComponent(t)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function ta({areaId:t,folderPath:n,isOpen:o}){const c=Zn(t,n),r=s.useRef(!1);s.useEffect(()=>{r.current=!1},[t,n]);const i=s.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const l=localStorage.getItem(c);if(!l)return null;const u=JSON.parse(l);if(Date.now()-u.timestamp>Qn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async y=>({tab:y,exists:await ea(y.path)})))).filter(({exists:y})=>y).map(({tab:y})=>y);let p=u.activeTabPath;return p&&!j.some(y=>y.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(l){return console.error("[FileExplorerStorage] Failed to load state:",l),null}},[c]),f=s.useCallback(l=>{if(o)try{const u={tabs:l.tabs,activeTabPath:l.activeTabPath,viewMode:l.viewMode,selectedFolderIndex:l.selectedFolderIndex,expandedPaths:Array.from(l.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,o]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function sa(){const[t,n]=s.useState(()=>{const g=$s(Rt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),o=s.useRef(!1),[c,r]=s.useState(!1),i=s.useRef(0),f=s.useRef(0),l=s.useRef(t);l.current=t;const u=s.useCallback(g=>{g.preventDefault(),o.current=!0,r(!0),i.current=g.clientX,f.current=t,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[t]);return s.useEffect(()=>{const g=p=>{if(!o.current)return;const y=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+y));n(C)},j=()=>{o.current&&(o.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.TREE_PANEL_WIDTH,l.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:t,handleResizeStart:u,isResizing:c}}const na=100,aa=.65,ra=36;function ia(){const[t,n]=s.useState(()=>$s(Rt.MOBILE_TREE_PANEL_HEIGHT,0)),o=s.useRef(t);o.current=t;const c=s.useRef(0),r=s.useRef(0),i=()=>Math.floor((window.innerHeight-ra)*aa),f=p=>Math.min(i(),Math.max(na,p)),l=s.useCallback(p=>{n(p);const y=document.querySelector(".file-explorer-main");y&&y.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=s.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.MOBILE_TREE_PANEL_HEIGHT,o.current),mt.setTerminalResizing(!1)},[]),g=s.useCallback(p=>{p.preventDefault();const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.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 R=N=>{const d=N.clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",R),document.addEventListener("mouseup",x)},[l,u]),j=s.useCallback(p=>{if(p.touches.length!==1)return;const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.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 R=N=>{if(N.touches.length!==1)return;N.preventDefault();const d=N.touches[0].clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",R),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[l,u]);return{mobileTreeHeight:t,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(null),[f,l]=s.useState(null),u=s.useCallback(async N=>{c(!0),i(null);try{const d=await Y(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=s.useCallback(async(N,d)=>{l("checkout"),i(null);try{const v=await Y(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{l(null)}},[]),j=s.useCallback(async(N,d,v)=>{l("create"),i(null);try{const w=await Y(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,name:d,startPoint:v})}),S=await w.json();return w.ok||i(S.error||"Failed to create branch"),S}catch(w){console.error("[GitBranches] Create branch failed:",w);const S={success:!1,error:"Failed to create branch"};return i(S.error),S}finally{l(null)}},[]),p=s.useCallback(async N=>{l("pull"),i(null);try{const d=await Y(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{l(null)}},[]),y=s.useCallback(async N=>{l("push"),i(null);try{const d=await Y(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{l(null)}},[]),C=s.useCallback(async(N,d)=>{l("merge"),i(null);try{const v=await Y(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{l(null)}},[]),R=s.useCallback(async N=>{l("merge-abort"),i(null);try{const d=await Y(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{l(null)}},[]),x=s.useCallback(async N=>{l("merge-continue"),i(null);try{const d=await Y(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{l(null)}},[]);return{branches:t,loading:o,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:y,mergeBranch:C,mergeAbort:R,mergeContinue:x}}const la=50,oa=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function ca(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(!1),[f,l]=s.useState(null),[u,g]=s.useState(!1),[j,p]=s.useState(0),[y,C]=s.useState({...Rs}),[R,x]=s.useState(null),[N,d]=s.useState([]),[v,w]=s.useState(!1),[S,A]=s.useState([]),[H,G]=s.useState(!1),z=s.useRef(null),ae=s.useRef(""),ee=s.useCallback((O,Z,L)=>{const T=L||y,W=new URLSearchParams;return W.set("path",O),W.set("limit",String(la)),W.set("offset",String(Z)),T.branch&&W.set("branch",T.branch),T.author&&W.set("author",T.author),T.since&&W.set("since",T.since),T.until&&W.set("until",T.until),T.searchPath&&W.set("searchPath",T.searchPath),T.search&&W.set("search",T.search),W.toString()},[y]),D=s.useCallback(async O=>{ae.current=O,c(!0),l(null),x(null),d([]);try{const Z=ee(O,0),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok?(n(T.commits||[]),p(T.total||0),g(T.hasMore||!1)):(l(T.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),l("Failed to load git history"),n([])}finally{c(!1)}},[ee]),F=s.useCallback(async O=>{if(!(r||!u)){i(!0);try{const Z=ee(O,t.length),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok&&(n(W=>[...W,...T.commits||[]]),p(T.total||0),g(T.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,t.length,u,r]),I=s.useCallback(async O=>{if(x(O),!O){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:O.hash}),T=await Y(K(`/api/files/git-commit-files?${L}`)),W=await T.json();T.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=s.useCallback((O,Z)=>{C(L=>({...L,[O]:Z}))},[]),_=s.useCallback(()=>{C({...Rs})},[]);s.useEffect(()=>{const O=ae.current;if(O)return z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{D(O)},oa),()=>{z.current&&clearTimeout(z.current)}},[y]);const ge=s.useCallback(async O=>{G(!0);try{const Z=new URLSearchParams({path:O}),L=await Y(K(`/api/files/git-authors?${Z}`)),T=await L.json();L.ok&&A(T.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:t,loading:o,loadingMore:r,error:f,hasMore:u,total:j,filters:y,setFilter:re,resetFilters:_,selectedCommit:R,selectCommit:I,commitFiles:N,commitFilesLoading:v,loadHistory:D,loadMore:F,authors:S,authorsLoading:H,loadAuthors:ge}}function da(t){if(!t.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 o of n){const c=t.current.querySelector(o);if(c&&Fs(c))return c}return Fs(t.current)?t.current:null}function Fs(t){const n=["auto","scroll"].includes(getComputedStyle(t).overflowY),o=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth;return n&&o}function Bs(t){if(!t)return 19.5;const n=parseFloat(getComputedStyle(t).lineHeight);return isNaN(n)?19.5:n}function Yt(t,n=!0){const o=n?t.scrollHeight:0;t.scrollTo({top:o,behavior:"smooth"})}function ua(t){const{scrollTop:n,scrollHeight:o,clientHeight:c}=t;return o<=c?100:Math.round(n/(o-c)*100)}function ha(t,n){const o=Bs(t),c=t.scrollTop,r=Math.floor(c/o)+1,i=n.split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-CBoOoGL8.js","assets/main-Bon1sZAi.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-BUSv52j9.css","assets/EmbeddedEditor-O_u2UVA4.css"])))=>i.map(i=>d[i]);
2
+ import{r as s,aM as Y,l as K,a_ as Kt,M as $s,S as Rt,N as Hs,s as mt,u as le,j as e,I as M,bB as Ft,f as zs,bC as As,bD as Rn,bE as Os,bF as Gs,bG as Fn,bH as In,bI as Tt,bJ as Pn,bK as Ln,bL as $n,bM as Xt,bN as Hn,bO as Us,bP as Mt,bQ as Dt,ac as it,bR as ft,bS as pt,bT as Es,bU as zn,b6 as An,bV as Jt,bW as On,bX as Gn,bY as Ss,C as Un,n as Bn}from"./main-Bon1sZAi.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function _n(t){const[n,o]=s.useState(null),[c,r]=s.useState(!1),i=s.useCallback(async()=>{if(t){r(!0);try{const f=await Y(K(`/api/files/git-status?path=${encodeURIComponent(t)}`)),l=await f.json();f.ok?o(l):o({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),o({isGitRepo:!1,files:[]})}finally{r(!1)}}},[t]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function Vn(t){try{const n=await Y(K(`/api/files/git-original?path=${encodeURIComponent(t)}`)),o=await n.json();return n.ok&&!o.isNew?{content:o.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const Kn=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",""]),Wn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Yn=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 Jn(t){const n=t.toLowerCase();return Wn.has(n)?"image":Yn.has(n)?"pdf":qn.has(n)?"binary":(Kn.has(n),"text")}function Xn(){const[t,n]=s.useState(null),[o,c]=s.useState(!1),[r,i]=s.useState(null),f=s.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),y=Jn(p),C=u.substring(u.lastIndexOf("/")+1);if(y==="image"){const N=await Y(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(y==="pdf"){const N=await Y(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(Kt())}`)});return}if(y==="binary"){const N=await Y(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(Kt())}`)});return}const R=await Y(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await R.json();if(!R.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const N=await Y(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(Kt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const y=p instanceof Error?p.message:"Failed to load file";i(y),n(null)}finally{c(!1)}},[]),l=s.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:t,loading:o,error:r,loadFile:f,clearFile:l,setFile:n}}const Wt="file-explorer-state",Qn=10080*60*1e3;function Zn(t,n){return n?`${Wt}-folder-${n}`:t?`${Wt}-area-${t}`:`${Wt}-default`}async function ea(t){try{const n=await Y(K(`/api/files/exists?path=${encodeURIComponent(t)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function ta({areaId:t,folderPath:n,isOpen:o}){const c=Zn(t,n),r=s.useRef(!1);s.useEffect(()=>{r.current=!1},[t,n]);const i=s.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const l=localStorage.getItem(c);if(!l)return null;const u=JSON.parse(l);if(Date.now()-u.timestamp>Qn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async y=>({tab:y,exists:await ea(y.path)})))).filter(({exists:y})=>y).map(({tab:y})=>y);let p=u.activeTabPath;return p&&!j.some(y=>y.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(l){return console.error("[FileExplorerStorage] Failed to load state:",l),null}},[c]),f=s.useCallback(l=>{if(o)try{const u={tabs:l.tabs,activeTabPath:l.activeTabPath,viewMode:l.viewMode,selectedFolderIndex:l.selectedFolderIndex,expandedPaths:Array.from(l.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,o]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function sa(){const[t,n]=s.useState(()=>{const g=$s(Rt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),o=s.useRef(!1),[c,r]=s.useState(!1),i=s.useRef(0),f=s.useRef(0),l=s.useRef(t);l.current=t;const u=s.useCallback(g=>{g.preventDefault(),o.current=!0,r(!0),i.current=g.clientX,f.current=t,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[t]);return s.useEffect(()=>{const g=p=>{if(!o.current)return;const y=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+y));n(C)},j=()=>{o.current&&(o.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.TREE_PANEL_WIDTH,l.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:t,handleResizeStart:u,isResizing:c}}const na=100,aa=.65,ra=36;function ia(){const[t,n]=s.useState(()=>$s(Rt.MOBILE_TREE_PANEL_HEIGHT,0)),o=s.useRef(t);o.current=t;const c=s.useRef(0),r=s.useRef(0),i=()=>Math.floor((window.innerHeight-ra)*aa),f=p=>Math.min(i(),Math.max(na,p)),l=s.useCallback(p=>{n(p);const y=document.querySelector(".file-explorer-main");y&&y.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=s.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.MOBILE_TREE_PANEL_HEIGHT,o.current),mt.setTerminalResizing(!1)},[]),g=s.useCallback(p=>{p.preventDefault();const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.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 R=N=>{const d=N.clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",R),document.addEventListener("mouseup",x)},[l,u]),j=s.useCallback(p=>{if(p.touches.length!==1)return;const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.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 R=N=>{if(N.touches.length!==1)return;N.preventDefault();const d=N.touches[0].clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",R),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[l,u]);return{mobileTreeHeight:t,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(null),[f,l]=s.useState(null),u=s.useCallback(async N=>{c(!0),i(null);try{const d=await Y(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=s.useCallback(async(N,d)=>{l("checkout"),i(null);try{const v=await Y(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{l(null)}},[]),j=s.useCallback(async(N,d,v)=>{l("create"),i(null);try{const w=await Y(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,name:d,startPoint:v})}),S=await w.json();return w.ok||i(S.error||"Failed to create branch"),S}catch(w){console.error("[GitBranches] Create branch failed:",w);const S={success:!1,error:"Failed to create branch"};return i(S.error),S}finally{l(null)}},[]),p=s.useCallback(async N=>{l("pull"),i(null);try{const d=await Y(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{l(null)}},[]),y=s.useCallback(async N=>{l("push"),i(null);try{const d=await Y(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{l(null)}},[]),C=s.useCallback(async(N,d)=>{l("merge"),i(null);try{const v=await Y(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{l(null)}},[]),R=s.useCallback(async N=>{l("merge-abort"),i(null);try{const d=await Y(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{l(null)}},[]),x=s.useCallback(async N=>{l("merge-continue"),i(null);try{const d=await Y(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{l(null)}},[]);return{branches:t,loading:o,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:y,mergeBranch:C,mergeAbort:R,mergeContinue:x}}const la=50,oa=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function ca(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(!1),[f,l]=s.useState(null),[u,g]=s.useState(!1),[j,p]=s.useState(0),[y,C]=s.useState({...Rs}),[R,x]=s.useState(null),[N,d]=s.useState([]),[v,w]=s.useState(!1),[S,A]=s.useState([]),[H,G]=s.useState(!1),z=s.useRef(null),ae=s.useRef(""),ee=s.useCallback((O,Z,L)=>{const T=L||y,W=new URLSearchParams;return W.set("path",O),W.set("limit",String(la)),W.set("offset",String(Z)),T.branch&&W.set("branch",T.branch),T.author&&W.set("author",T.author),T.since&&W.set("since",T.since),T.until&&W.set("until",T.until),T.searchPath&&W.set("searchPath",T.searchPath),T.search&&W.set("search",T.search),W.toString()},[y]),D=s.useCallback(async O=>{ae.current=O,c(!0),l(null),x(null),d([]);try{const Z=ee(O,0),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok?(n(T.commits||[]),p(T.total||0),g(T.hasMore||!1)):(l(T.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),l("Failed to load git history"),n([])}finally{c(!1)}},[ee]),F=s.useCallback(async O=>{if(!(r||!u)){i(!0);try{const Z=ee(O,t.length),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok&&(n(W=>[...W,...T.commits||[]]),p(T.total||0),g(T.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,t.length,u,r]),I=s.useCallback(async O=>{if(x(O),!O){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:O.hash}),T=await Y(K(`/api/files/git-commit-files?${L}`)),W=await T.json();T.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=s.useCallback((O,Z)=>{C(L=>({...L,[O]:Z}))},[]),_=s.useCallback(()=>{C({...Rs})},[]);s.useEffect(()=>{const O=ae.current;if(O)return z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{D(O)},oa),()=>{z.current&&clearTimeout(z.current)}},[y]);const ge=s.useCallback(async O=>{G(!0);try{const Z=new URLSearchParams({path:O}),L=await Y(K(`/api/files/git-authors?${Z}`)),T=await L.json();L.ok&&A(T.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:t,loading:o,loadingMore:r,error:f,hasMore:u,total:j,filters:y,setFilter:re,resetFilters:_,selectedCommit:R,selectCommit:I,commitFiles:N,commitFilesLoading:v,loadHistory:D,loadMore:F,authors:S,authorsLoading:H,loadAuthors:ge}}function da(t){if(!t.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 o of n){const c=t.current.querySelector(o);if(c&&Fs(c))return c}return Fs(t.current)?t.current:null}function Fs(t){const n=["auto","scroll"].includes(getComputedStyle(t).overflowY),o=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth;return n&&o}function Bs(t){if(!t)return 19.5;const n=parseFloat(getComputedStyle(t).lineHeight);return isNaN(n)?19.5:n}function Yt(t,n=!0){const o=n?t.scrollHeight:0;t.scrollTo({top:o,behavior:"smooth"})}function ua(t){const{scrollTop:n,scrollHeight:o,clientHeight:c}=t;return o<=c?100:Math.round(n/(o-c)*100)}function ha(t,n){const o=Bs(t),c=t.scrollTop,r=Math.floor(c/o)+1,i=n.split(`
3
3
  `).length;return Math.min(r,i)}function ma(t,n,o=!1){if(!n)return[];o||t.toLowerCase();const c=o?n:n.toLowerCase(),r=[];let i=0;const f=t.split(`
4
4
  `);let l=0;for(let u=0;u<f.length;u++){const g=f[u],j=o?g:g.toLowerCase();let p=0,y=j.indexOf(c);for(;y!==-1;){const C=l+y;r.push({index:i++,line:u+1,column:y,length:c.length,charIndex:C}),p=y+c.length,y=j.indexOf(c,p)}l+=g.length+1}return r}function lt(t){return/[\w]/.test(t)}function Ge(t){return/\s/.test(t)}function fa(t,n,o){let c=n-1,r=o;const i=t.length,f=t[c]||"";if(r<f.length){const g=lt(f[r]);if(!Ge(f[r]))for(;r<f.length&&!Ge(f[r])&&lt(f[r])===g;)r++}for(;c<i;){const g=t[c]||"";for(;r<g.length&&Ge(g[r]);)r++;if(r<g.length)return{line:c+1,col:r};c++,r=0}const l=i,u=Math.max(0,(t[i-1]||"").length-1);return{line:l,col:u}}function pa(t,n,o){let c=n-1,r=o+1;const i=t.length;for(;c<i;){const u=t[c]||"";for(;r<u.length&&Ge(u[r]);)r++;if(r<u.length)break;c++,r=0}if(c>=i)return{line:i,col:Math.max(0,(t[i-1]||"").length-1)};const f=t[c]||"",l=lt(f[r]);for(;r+1<f.length&&!Ge(f[r+1])&&lt(f[r+1])===l;)r++;return{line:c+1,col:r}}function ga(t,n,o){let c=n-1,r=o-1;for(;c>=0;){const l=t[c]||"";for(;r>=0&&Ge(l[r]);)r--;if(r>=0)break;c--,c>=0&&(r=(t[c]||"").length-1)}if(c<0)return{line:1,col:0};const i=t[c]||"",f=lt(i[r]);for(;r>0&&!Ge(i[r-1])&&lt(i[r-1])===f;)r--;return{line:c+1,col:r}}function xa(t,n,o,c){if(c==="none")return"";const{anchorLine:r,anchorCol:i,headLine:f,headCol:l}=o;if(c==="line"){const C=Math.min(r,f),R=Math.max(r,f);return n.slice(C-1,R).join(`
5
5
  `)}let u,g,j,p;if(r<f||r===f&&i<=l?(u=r,g=i,j=f,p=l):(u=f,g=l,j=r,p=i),u===j)return(n[u-1]||"").substring(g,p+1);const y=[];y.push((n[u-1]||"").substring(g));for(let C=u;C<j-1;C++)y.push(n[C]||"");return y.push((n[j-1]||"").substring(0,p+1)),y.join(`
6
6
  `)}function _s(t){const{containerRef:n,isEnabled:o=!0,content:c="",onClose:r,onSearchOpen:i}=t,f=s.useRef({percentage:0,line:1,column:1}),l=s.useRef(null),u=s.useRef(19.5),g=s.useMemo(()=>c.split(`
7
- `),[c]),j=g.length,[p,y]=s.useState(1),[C,R]=s.useState(0),[x,N]=s.useState(!1),[d,v]=s.useState("none"),[w,S]=s.useState(null),[A,H]=s.useState(!1),[G,z]=s.useState(""),[ae,ee]=s.useState(0),[D,F]=s.useState(!1),I=s.useMemo(()=>ma(c,G,!1),[c,G]),re=s.useCallback(()=>{const m=l.current;if(!m)return;const q=ua(m),ie=ha(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:q,line:ie,column:V}},[c]),_=s.useCallback(()=>{H(!0),z(""),ee(0),i==null||i()},[i]),ge=s.useCallback(()=>{H(!1),z(""),ee(0)},[]),O=s.useCallback(()=>{F(m=>!m)},[]),Z=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.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;q.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);s.useEffect(()=>{!A||I.length===0||ee(0)},[I,A]),s.useEffect(()=>{if(!A||I.length===0)return;const m=I[ae];m&&(y(m.line),R(m.column),Z(m.line))},[A,I,ae,Z]);const L=s.useCallback(()=>{I.length!==0&&ee(m=>(m+1)%I.length)},[I]),T=s.useCallback(()=>{I.length!==0&&ee(m=>(m-1+I.length)%I.length)},[I]),W=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.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=q.scrollTop,U=xe+q.clientHeight;te<xe?q.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&q.scrollTo({top:Ne-q.clientHeight,behavior:"auto"})},[]),ne=s.useCallback((m,q)=>{y(m),R(q),W(m),d!=="none"&&S(ie=>ie?{...ie,headLine:m,headCol:q}:null)},[d,W]),be=s.useCallback(()=>{if(d==="none"||!w)return;const m=xa(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const q=document.createElement("textarea");q.value=m,q.style.position="fixed",q.style.left="-9999px",document.body.appendChild(q),q.select(),document.execCommand("copy"),document.body.removeChild(q)}),v("none"),S(null)},[d,w,c,g]),de=s.useCallback(m=>{const q=m.target;if((q.tagName==="INPUT"||q.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=l.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,se)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(se,Math.max(0,pe))},xe=(U,se)=>{const pe=Ne(U,se);ne(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),S(null)):(v("char"),S({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),S(null)):(v("line"),S({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"&&!A){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"&&!A){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"&&!A){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"&&!A||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"&&!A)m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),ne(j,0),Yt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),ne(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;ne(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=pa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="b"&&!A){m.preventDefault(),m.stopPropagation();const U=ga(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),ne(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const se=(g[p-1]||"").search(/\S/);ne(p,se>=0?se:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!A?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!A?(m.preventDefault(),m.stopPropagation(),T(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),O(),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"),S(null),V=!0):A?(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,A,ge,d,x,ne,be,_,L,T,O]);return s.useEffect(()=>{if(!o)return;const m=da(n);if(l.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const q=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",q,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",q)}},[o,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:A,searchQuery:G,searchMatches:I,currentMatchIndex:ae,startSearch:_,setSearchQuery:z,nextMatch:L,prevMatch:T,clearSearch:ge,helpActive:D,toggleHelp:O}}const Zt=({query:t,onQueryChange:n,matchCount:o,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:l}=le(["terminal"]),u=s.useRef(null);s.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=s.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=o===0&&t?l("terminal:fileExplorer.noMatches"):o>0?`${c+1}/${o}`:"";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:l("terminal:fileExplorer.searchInFile"),value:t,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),t&&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:o===0,title:l("terminal:fileExplorer.previousMatch"),"aria-label":l("terminal:fileExplorer.previousMatch"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:o===0,title:l("terminal:fileExplorer.nextMatch"),"aria-label":l("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:l("terminal:fileExplorer.closeSearch"),"aria-label":l("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const ya=[{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:t})=>{const{t:n}=le(["terminal"]),o=s.useCallback(i=>{i.target===i.currentTarget&&t()},[t]),c=s.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),t())},[t]),r=ya.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:o,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:t,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(M,{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((l,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:l.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:l.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Is=s.lazy(()=>Rn(()=>import("./EmbeddedEditor-BTRUWN3W.js"),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.EmbeddedEditor}))),ba=[".md",".mdx",".markdown"],Ps="file-viewer-markdown-render",ja=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",va="https://kroki.io/plantuml/svg";function wa(t){return ba.includes(t.toLowerCase())}function Ca(t){return ja.includes(t.toLowerCase())}function Na(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ps);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ps,String(r))}catch{}return r})},[]);return[t,o]}function ka(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[t,o]}function Ea(t){const n=new TextEncoder().encode(t);let o="";for(const c of n)o+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(o)}`}function Ue({file:t,rightContent:n,onRevealInTree:o,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,l]=s.useState("idle"),[u,g]=s.useState("idle"),[j,p]=s.useState("idle"),y=t.fileType==="text"?Ft(t.extension):t.extension.slice(1).toUpperCase(),C=t.fileType==="text"&&t.content!=null,{settings:R}=zs(),x=async()=>{try{await Tt(t.content),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},N=()=>{const S=new Blob([t.content],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),H=document.createElement("a");H.href=A,H.download=t.filename,document.body.appendChild(H),H.click(),H.remove(),setTimeout(()=>URL.revokeObjectURL(A),1e3)},d=async()=>{l("loading");try{const S=await Y(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,...R.externalEditorCommand&&{editorCommand:R.externalEditorCommand}})});if(!S.ok){const A=await S.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",A),l("error"),setTimeout(()=>l("idle"),2e3);return}l("success"),setTimeout(()=>l("idle"),2e3)}catch(S){console.error("Error opening file in editor:",S),l("error"),setTimeout(()=>l("idle"),2e3)}},v=async()=>{if(t.path)try{await $n(t.path),g("success"),setTimeout(()=>g("idle"),2e3)}catch(S){console.error("Error opening file explorer:",S),g("error"),setTimeout(()=>g("idle"),2e3)}},w=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:t.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[As(t.size)," • ",y,t.content&&` • ${t.content.split(`
7
+ `),[c]),j=g.length,[p,y]=s.useState(1),[C,R]=s.useState(0),[x,N]=s.useState(!1),[d,v]=s.useState("none"),[w,S]=s.useState(null),[A,H]=s.useState(!1),[G,z]=s.useState(""),[ae,ee]=s.useState(0),[D,F]=s.useState(!1),I=s.useMemo(()=>ma(c,G,!1),[c,G]),re=s.useCallback(()=>{const m=l.current;if(!m)return;const q=ua(m),ie=ha(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:q,line:ie,column:V}},[c]),_=s.useCallback(()=>{H(!0),z(""),ee(0),i==null||i()},[i]),ge=s.useCallback(()=>{H(!1),z(""),ee(0)},[]),O=s.useCallback(()=>{F(m=>!m)},[]),Z=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.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;q.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);s.useEffect(()=>{!A||I.length===0||ee(0)},[I,A]),s.useEffect(()=>{if(!A||I.length===0)return;const m=I[ae];m&&(y(m.line),R(m.column),Z(m.line))},[A,I,ae,Z]);const L=s.useCallback(()=>{I.length!==0&&ee(m=>(m+1)%I.length)},[I]),T=s.useCallback(()=>{I.length!==0&&ee(m=>(m-1+I.length)%I.length)},[I]),W=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.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=q.scrollTop,U=xe+q.clientHeight;te<xe?q.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&q.scrollTo({top:Ne-q.clientHeight,behavior:"auto"})},[]),ne=s.useCallback((m,q)=>{y(m),R(q),W(m),d!=="none"&&S(ie=>ie?{...ie,headLine:m,headCol:q}:null)},[d,W]),be=s.useCallback(()=>{if(d==="none"||!w)return;const m=xa(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const q=document.createElement("textarea");q.value=m,q.style.position="fixed",q.style.left="-9999px",document.body.appendChild(q),q.select(),document.execCommand("copy"),document.body.removeChild(q)}),v("none"),S(null)},[d,w,c,g]),de=s.useCallback(m=>{const q=m.target;if((q.tagName==="INPUT"||q.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=l.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,se)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(se,Math.max(0,pe))},xe=(U,se)=>{const pe=Ne(U,se);ne(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),S(null)):(v("char"),S({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),S(null)):(v("line"),S({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"&&!A){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"&&!A){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"&&!A){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"&&!A||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"&&!A)m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),ne(j,0),Yt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),ne(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;ne(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=pa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="b"&&!A){m.preventDefault(),m.stopPropagation();const U=ga(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),ne(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const se=(g[p-1]||"").search(/\S/);ne(p,se>=0?se:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!A?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!A?(m.preventDefault(),m.stopPropagation(),T(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),O(),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"),S(null),V=!0):A?(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,A,ge,d,x,ne,be,_,L,T,O]);return s.useEffect(()=>{if(!o)return;const m=da(n);if(l.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const q=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",q,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",q)}},[o,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:A,searchQuery:G,searchMatches:I,currentMatchIndex:ae,startSearch:_,setSearchQuery:z,nextMatch:L,prevMatch:T,clearSearch:ge,helpActive:D,toggleHelp:O}}const Zt=({query:t,onQueryChange:n,matchCount:o,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:l}=le(["terminal"]),u=s.useRef(null);s.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=s.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=o===0&&t?l("terminal:fileExplorer.noMatches"):o>0?`${c+1}/${o}`:"";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:l("terminal:fileExplorer.searchInFile"),value:t,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),t&&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:o===0,title:l("terminal:fileExplorer.previousMatch"),"aria-label":l("terminal:fileExplorer.previousMatch"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:o===0,title:l("terminal:fileExplorer.nextMatch"),"aria-label":l("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:l("terminal:fileExplorer.closeSearch"),"aria-label":l("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const ya=[{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:t})=>{const{t:n}=le(["terminal"]),o=s.useCallback(i=>{i.target===i.currentTarget&&t()},[t]),c=s.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),t())},[t]),r=ya.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:o,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:t,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(M,{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((l,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:l.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:l.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Is=s.lazy(()=>Rn(()=>import("./EmbeddedEditor-CBoOoGL8.js"),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.EmbeddedEditor}))),ba=[".md",".mdx",".markdown"],Ps="file-viewer-markdown-render",ja=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",va="https://kroki.io/plantuml/svg";function wa(t){return ba.includes(t.toLowerCase())}function Ca(t){return ja.includes(t.toLowerCase())}function Na(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ps);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ps,String(r))}catch{}return r})},[]);return[t,o]}function ka(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[t,o]}function Ea(t){const n=new TextEncoder().encode(t);let o="";for(const c of n)o+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(o)}`}function Ue({file:t,rightContent:n,onRevealInTree:o,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,l]=s.useState("idle"),[u,g]=s.useState("idle"),[j,p]=s.useState("idle"),y=t.fileType==="text"?Ft(t.extension):t.extension.slice(1).toUpperCase(),C=t.fileType==="text"&&t.content!=null,{settings:R}=zs(),x=async()=>{try{await Tt(t.content),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},N=()=>{const S=new Blob([t.content],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),H=document.createElement("a");H.href=A,H.download=t.filename,document.body.appendChild(H),H.click(),H.remove(),setTimeout(()=>URL.revokeObjectURL(A),1e3)},d=async()=>{l("loading");try{const S=await Y(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,...R.externalEditorCommand&&{editorCommand:R.externalEditorCommand}})});if(!S.ok){const A=await S.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",A),l("error"),setTimeout(()=>l("idle"),2e3);return}l("success"),setTimeout(()=>l("idle"),2e3)}catch(S){console.error("Error opening file in editor:",S),l("error"),setTimeout(()=>l("idle"),2e3)}},v=async()=>{if(t.path)try{await $n(t.path),g("success"),setTimeout(()=>g("idle"),2e3)}catch(S){console.error("Error opening file explorer:",S),g("error"),setTimeout(()=>g("idle"),2e3)}},w=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:t.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[As(t.size)," • ",y,t.content&&` • ${t.content.split(`
8
8
  `).length} lines`]})]}),e.jsxs("div",{className:"file-viewer-header-right",children:[r&&t.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"})})}),C&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:x,title:i("terminal:fileExplorer.copyAllTitle"),children:i(j==="copied"?"terminal:fileExplorer.copied":j==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyAll")}),e.jsx("button",{className:"file-viewer-download-btn",onClick:N,title:i("terminal:fileExplorer.downloadFileTitle"),children:i("common:buttons.download")})]}),e.jsx("button",{className:`file-viewer-reveal-explorer-btn ${u}`,onClick:v,disabled:!t.path,title:w,"aria-label":w,children:u==="success"?e.jsx(M,{name:"check",size:14}):u==="error"?e.jsx(M,{name:"cross",size:14}):e.jsx(M,{name:"folder-open",size:14})}),e.jsx("button",{className:`file-viewer-open-editor-btn ${f}`,onClick:d,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"})})}),o&&e.jsx("button",{className:"file-viewer-locate-btn",onClick:()=>o(t.path),title:i("terminal:fileExplorer.locateInTree"),children:e.jsx(M,{name:"target",size:14})}),n]})]})}function Sa({file:t,onRevealInTree:n,renderMarkdown:o,onToggleRender:c,editMode:r,onToggleEdit:i}){const f=s.useRef(null),l=s.useRef(null),u=s.useRef(null),{t:g}=le(["terminal","common"]),[j,p]=s.useState("idle"),[y,C]=s.useState("idle"),[R,x]=s.useState("idle"),[N,d]=s.useState("idle"),v=_s({containerRef:u,isEnabled:!0,content:t.content});s.useEffect(()=>{if(!o&&f.current){const z=Ft(t.extension);Os(z).then(()=>{f.current&&Gs(f.current)})}},[t,o]);const w=s.useCallback(async()=>{if(!l.current){p("error"),setTimeout(()=>p("idle"),2e3);return}try{const z=l.current.innerHTML,ae=Fn(z),ee=l.current.innerText;await In(ae,ee),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},[]),S=s.useCallback(async()=>{if(!l.current){C("error"),setTimeout(()=>C("idle"),2e3);return}try{const z=l.current.innerHTML;await Tt(z),C("copied"),setTimeout(()=>C("idle"),2e3)}catch{C("error"),setTimeout(()=>C("idle"),2e3)}},[]),A=s.useCallback(async()=>{try{await Tt(t.content),x("copied"),setTimeout(()=>x("idle"),2e3)}catch{x("error"),setTimeout(()=>x("idle"),2e3)}},[t.content]),H=s.useCallback(async()=>{try{await Tt(t.content),d("copied"),setTimeout(()=>d("idle"),2e3)}catch{d("error"),setTimeout(()=>d("idle"),2e3)}},[t.content]),G=e.jsxs("div",{className:"file-viewer-header-buttons",children:[o&&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 ${y}`,onClick:S,title:g("terminal:fileExplorer.copyHtmlTitle"),children:g(y==="copied"?"terminal:fileExplorer.copied":y==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyHtml")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${R}`,onClick:A,title:g("terminal:fileExplorer.copyMarkdownTitle"),children:g(R==="copied"?"terminal:fileExplorer.copied":R==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyMarkdown")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${N}`,onClick:H,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 ${o?"active":""}`,onClick:c,title:g(o?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderMarkdown"),children:o?"</>":"Aa"})]});return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:G,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[o?e.jsx("div",{className:"file-viewer-markdown-wrapper",children:e.jsx("div",{className:"markdown-content",ref:l,children:e.jsx(Pn,{remarkPlugins:[Ln],children:t.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:t.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 Ta({file:t,onRevealInTree:n,renderPlantUml:o,onToggleRender:c,editMode:r,onToggleEdit:i}){const{t:f}=le(["terminal"]),l=s.useRef(null),u=s.useRef(null),[g,j]=s.useState(null),[p,y]=s.useState(!1),[C,R]=s.useState(null),x=_s({containerRef:u,isEnabled:!0,content:t.content});s.useEffect(()=>{if(!o&&l.current){const d=Ft(t.extension);Os(d).then(()=>{l.current&&Gs(l.current)})}},[t,o]),s.useEffect(()=>{if(!o)return;if(!t.content.trim()){j(null),R("Diagram is empty");return}const d=new AbortController;return y(!0),R(null),(async()=>{try{const w=await fetch(va,{method:"POST",headers:{"Content-Type":"text/plain; charset=utf-8",Accept:"image/svg+xml"},body:t.content,signal:d.signal});if(!w.ok)throw new Error(`Render failed (${w.status})`);const S=await w.text();if(!S.includes("<svg"))throw new Error("Invalid SVG output");j(Ea(S))}catch(w){if(d.signal.aborted)return;const S=w instanceof Error?w.message:"Failed to render diagram";R(S),j(null)}finally{d.signal.aborted||y(!1)}})(),()=>d.abort()},[t.path,t.content,o]);const N=e.jsx("div",{className:"file-viewer-header-buttons",children:e.jsx("button",{className:`file-viewer-render-toggle ${o?"active":""}`,onClick:c,title:f(o?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderDiagram"),children:o?"</>":f("terminal:fileExplorer.diagram")})});return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:N,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[o?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:t.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:l,className:"language-plaintext",children:t.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 Ma({file:t,onRevealInTree:n}){const{t:o}=le(["common","terminal"]),c=()=>{if(t.dataUrl){const r=document.createElement("a");r.href=t.dataUrl,r.download=t.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:o("common:buttons.download"),children:o("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-image-wrapper",children:t.dataUrl?e.jsx("img",{src:t.dataUrl,alt:t.filename,className:"file-viewer-image"}):e.jsx("div",{className:"file-viewer-placeholder",children:o("terminal:fileExplorer.failedToLoadImage")})})]})}function Da({file:t,onRevealInTree:n}){const{t:o}=le(["common","terminal"]),c=()=>{if(t.dataUrl){const r=document.createElement("a");r.href=t.dataUrl,r.download=t.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:o("common:buttons.download"),children:o("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-pdf-wrapper",children:t.dataUrl?e.jsx("iframe",{src:t.dataUrl,title:t.filename,className:"file-viewer-pdf"}):e.jsx("div",{className:"file-viewer-placeholder",children:o("terminal:fileExplorer.failedToLoadPdf")})})]})}function Ra({file:t,onRevealInTree:n}){const{t:o}=le(["terminal","common"]),c=()=>{if(t.dataUrl){const i=document.createElement("a");i.href=t.dataUrl,i.download=t.filename,i.click()}},r=()=>{const i=t.extension.toLowerCase();return[".xlsx",".xls"].includes(i)?e.jsx(M,{name:"dashboard",size:48}):[".docx",".doc"].includes(i)?e.jsx(M,{name:"edit",size:48}):[".pptx",".ppt"].includes(i)?e.jsx(M,{name:"film",size:48}):[".zip",".tar",".gz",".rar",".7z"].includes(i)?e.jsx(M,{name:"file-zip",size:48}):[".mp3",".wav",".flac",".ogg"].includes(i)?e.jsx(M,{name:"music-note",size:48}):[".mp4",".avi",".mov",".mkv",".webm"].includes(i)?e.jsx(M,{name:"film",size:48}):[".exe",".dmg",".app",".msi"].includes(i)?e.jsx(M,{name:"gear",size:48}):[".apk",".aab",".ipa"].includes(i)?e.jsx(M,{name:"mobile",size:48}):[".jar",".war",".ear"].includes(i)?e.jsx(M,{name:"coffee",size:48}):[".iso",".img"].includes(i)?e.jsx(M,{name:"disc",size:48}):[".so",".dll",".dylib"].includes(i)?e.jsx(M,{name:"wrench",size:48}):e.jsx(M,{name:"folder",size:48})};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,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:t.filename}),e.jsx("div",{className:"file-viewer-binary-size",children:As(t.size)}),e.jsx("div",{className:"file-viewer-binary-message",children:o("terminal:fileExplorer.cannotPreview")}),e.jsx("button",{className:"file-viewer-download-btn large",onClick:c,children:o("terminal:fileExplorer.downloadFile")})]})]})}function Fa({file:t,loading:n,error:o,onRevealInTree:c,onFileEdited:r}){const{t:i}=le(["terminal","common"]),[f,l]=Na(),[u,g]=ka(),[j,p]=s.useState(!1);s.useEffect(()=>{p(!1)},[t==null?void 0:t.path]);const y=s.useCallback(async w=>{if(!t)return;const S=await Y(K("/api/files/write"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,content:w})});if(!S.ok){const A=await S.json().catch(()=>({error:"Save failed"}));throw new Error(A.error||"Save failed")}},[t]),C=s.useCallback(()=>{p(w=>(w&&t&&(r==null||r(t.path)),!w))},[t,r]),R=s.useCallback(()=>{t&&(r==null||r(t.path))},[t,r]);if(n)return e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")});if(o)return e.jsx("div",{className:"file-viewer-placeholder error",children:o});if(!t)return e.jsxs("div",{className:"file-viewer-placeholder",children:[e.jsx("div",{className:"placeholder-icon",children:e.jsx(M,{name:"folder-open",size:32})}),e.jsx("div",{className:"placeholder-text",children:i("terminal:fileExplorer.selectFileToView")})]});const x=t.fileType||"text",N=x==="text"&&wa(t.extension),d=x==="text"&&Ca(t.extension),v=N||d;return v&&j&&t.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ue,{file:t,onRevealInTree:c,editMode:!0,onToggleEdit:C}),e.jsx(s.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:t.content,extension:t.extension,onSave:y,onCancel:C},t.path)})]}):x==="text"&&!v&&t.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ue,{file:t,onRevealInTree:c}),e.jsx(s.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:t.content,extension:t.extension,onSave:y,onCancel:R},t.path)})]}):e.jsxs("div",{className:"file-viewer-content",children:[N&&e.jsx(Sa,{file:t,onRevealInTree:c,renderMarkdown:f,onToggleRender:l,editMode:j,onToggleEdit:C}),d&&!N&&e.jsx(Ta,{file:t,onRevealInTree:c,renderPlantUml:u,onToggleRender:g,editMode:j,onToggleEdit:C}),x==="image"&&e.jsx(Ma,{file:t,onRevealInTree:c}),x==="pdf"&&e.jsx(Da,{file:t,onRevealInTree:c}),x==="binary"&&e.jsx(Ra,{file:t,onRevealInTree:c})]})}const Vs=s.memo(Fa,(t,n)=>t.loading!==n.loading||t.error!==n.error?!1:t.file===null&&n.file===null?!0:t.file===null||n.file===null?!1:t.file.path===n.file.path&&t.file.content===n.file.content&&t.file.modified===n.file.modified);Vs.displayName="FileViewer";function Ks({text:t,query:n}){if(!n)return e.jsx(e.Fragment,{children:t});const o=Hn(t,n);if(o)return e.jsxs(e.Fragment,{children:[t.slice(0,o.start),e.jsx("mark",{className:"search-highlight",children:t.slice(o.start,o.end)}),t.slice(o.end)]});const c=n.toLowerCase(),i=t.toLowerCase().indexOf(c);return i===-1?e.jsx(e.Fragment,{children:t}):e.jsxs(e.Fragment,{children:[t.slice(0,i),e.jsx("mark",{className:"search-highlight",children:t.slice(i,i+n.length)}),t.slice(i+n.length)]})}const Ia=s.memo(function({node:n,query:o,isSelected:c,onSelect:r,lineNumber:i}){const f=n.isDirectory?null:Xt(n),l=n.path.split("/");l[l.length-1];const u=l.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(M,{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(M,{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:o}),i&&e.jsxs("span",{className:"search-result-line-badge",children:[":",i]})]}),e.jsx("span",{className:"search-result-path",children:u})]})]})}),Pa=s.memo(function({match:n,query:o,isSelected:c,onSelect:r}){const{t:i}=le(["terminal"]),f={name:n.name,path:n.path,isDirectory:!1,extension:n.extension},l=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:[l?e.jsx("span",{className:"content-search-icon",style:{backgroundImage:`url('${l}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"content-search-icon",children:e.jsx(M,{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,y)=>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:o})})]},`${n.path}-${p.line}-${y}`)),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 La({filenameResults:t,contentResults:n,onSelectFile:o,onSelectContent:c,selectedPath:r,query:i,lineNumber:f}){const{t:l}=le(["terminal"]),u=t.length>0,g=n.length>0;return!u&&!g?e.jsx("div",{className:"search-no-results",children:l("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(M,{name:"file-text",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:l("terminal:fileExplorer.files")}),e.jsx("span",{className:"unified-search-section-count",children:t.length})]}),e.jsx("div",{className:"unified-search-section-content",children:t.map(j=>e.jsx(Ia,{node:j,query:i,isSelected:r===j.path,onSelect:o,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(M,{name:"edit",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:l("terminal:fileExplorer.content")}),e.jsx("span",{className:"unified-search-section-count",children:l("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(Pa,{match:j,query:i,isSelected:r===j.path,onSelect:c},j.path))})]})]})}const Ws=s.memo(La,(t,n)=>!(t.query!==n.query||t.selectedPath!==n.selectedPath||t.filenameResults.length!==n.filenameResults.length||t.contentResults.length!==n.contentResults.length));Ws.displayName="UnifiedSearchResults";const $a=s.memo(function({file:n,isSelected:o,onSelect:c,onStage:r,isStaging:i,showDirPath:f,isChecked:l,onToggleCheck:u,onContextMenu:g,onDiscard:j}){const{t:p}=le(["terminal"]),y=n.status,C=pt[y],R=y==="deleted",x=y==="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 ${o?"selected":""}`,onClick:()=>!R&&c(n.path,y),onContextMenu:v=>{v.preventDefault(),g==null||g(v,n,y)},style:{cursor:R?"not-allowed":"pointer"},title:n.path,children:[u&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:l||!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(M,{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,y)},title:y==="untracked"||y==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}),Ha=16,za=22,Aa=s.memo(function t({node:n,depth:o,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:l,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:y,onDiscard:C}){const{t:R}=le(["terminal"]),x=o*Ha;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+za}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(M,{name:"subitem",size:10,style:{transform:"rotate(180deg)"}})," ",n.file.oldPath.split("/").pop()]}),d==="untracked"&&l&&e.jsx("button",{className:`git-stage-btn ${u!=null&&u.has(n.path)?"staging":""}`,onClick:w=>{w.stopPropagation(),u!=null&&u.has(n.path)||l(n.file.path)},title:R("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(M,{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(),y==null||y(d,n)},children:[e.jsx("span",{className:`tree-arrow ${N?"expanded":""}`,children:e.jsx(M,{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:R("terminal:fileExplorer.fileCount",{count:n.fileCount})})]}),N&&e.jsx("div",{className:"tree-children",children:n.children.map(d=>e.jsx(t,{node:d,depth:o+1,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:l,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:y,onDiscard:C},d.path))})]})}),qt=s.memo(function({groupLabel:n,groupIcon:o,groupColor:c,files:r,treeNodes:i,viewMode:f,selectedPath:l,expandedDirs:u,onToggleDir:g,onFileSelect:j,onStageFile:p,onStageAll:y,stagingPaths:C,checkedFiles:R,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscardFile:v,onDiscardAll:w}){const{t:S}=le(["terminal"]);if(r.length===0)return null;const A=r.some(z=>z.status==="untracked"),H=A&&y&&r.length>0,G=C?r.every(z=>C.has(z.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:o}),n," (",r.length,")",H&&e.jsx("button",{className:`git-stage-all-btn ${G?"staging":""}`,onClick:z=>{z.stopPropagation(),G||y()},title:S("terminal:fileExplorer.stageAllUntracked"),disabled:G,children:G?"...":S("terminal:fileExplorer.stageAll")}),w&&e.jsxs("button",{className:"git-discard-all-btn",onClick:z=>{z.stopPropagation(),w()},title:A?`Delete all ${r.length} files`:`Discard all ${r.length} changes`,children:[e.jsx(M,{name:"revert",size:12})," All"]})]}),f==="tree"?e.jsx("div",{className:"git-tree-content",children:i.map(z=>e.jsx(Aa,{node:z,depth:0,expandedDirs:u,onToggleDir:g,selectedPath:l,onSelect:j,onStage:p,stagingPaths:C,checkedFiles:R,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscard:v},z.path))}):e.jsx("div",{className:"git-flat-content",children:r.map(z=>e.jsx($a,{file:z,isSelected:l===z.path,onSelect:j,onStage:z.status==="untracked"?p:void 0,isStaging:C==null?void 0:C.has(z.path),showDirPath:!0,isChecked:R==null?void 0:R.has(z.path),onToggleCheck:x,onContextMenu:N,onDiscard:v},z.path))})]})});function Oa({gitStatus:t,loading:n,onFileSelect:o,selectedPath:c,onRefresh:r,onStageFiles:i,stagingPaths:f,currentFolder:l,onCommitComplete:u,mergeInProgress:g,mergingBranch:j,onMergeContinue:p,onMergeAbort:y,onConflictOpen:C,onRevealInTree:R}){const{t:x}=le(["terminal","common"]),[N,d]=s.useState("tree"),[v,w]=s.useState(new Set),[S,A]=s.useState(""),[H,G]=s.useState(""),[z,ae]=s.useState(!1),[ee,D]=s.useState(new Set),[F,I]=s.useState(!1),[re,_]=s.useState(null),ge=s.useRef(null),{showToast:O}=Us(),[Z,L]=s.useState(null),[T,W]=s.useState(null),[ne,be]=s.useState(null),de=s.useCallback((k,P)=>{be({files:[k],label:k.name})},[]),m=s.useCallback(async()=>{if(!(!ne||!l))try{const k=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:ne.files.map(B=>({path:B.path,status:B.status})),directory:l})}),P=await k.json();k.ok&&P.success?(O("success","Discarded",`Reverted ${ne.files.length} file(s)`),r()):O("error","Discard Failed",P.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}finally{be(null)}},[ne,l,r,O]),q=s.useCallback((k,P,B)=>{k.preventDefault(),k.stopPropagation(),L({isOpen:!0,position:{x:k.clientX,y:k.clientY},file:P,status:B})},[]),ie=s.useCallback(async(k,P)=>{if(l)try{const B=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{path:k.path,status:P}],directory:l})}),ke=await B.json();B.ok&&ke.success?(O("success","Discarded",`Restored ${k.name}`),r()):O("error","Discard Failed",ke.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}},[l,r,O]),ue=s.useCallback(async k=>{try{await navigator.clipboard.writeText(k),O("success","Copied","Full path copied")}catch{O("error","Copy Failed","Could not copy path")}},[O]),V=s.useCallback(async k=>{const P=l&&k.startsWith(l+"/")?k.slice(l.length+1):k;try{await navigator.clipboard.writeText(P),O("success","Copied","Relative path copied")}catch{O("error","Copy Failed","Could not copy path")}},[l,O]),E=s.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(M,{name:"warn",size:14}),onClick:()=>C(k.path)}):P!=="deleted"&&B.push({id:"open-file",label:x("terminal:fileExplorer.gitContextMenu.openFile"),icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>o(k.path,P)}),P!=="conflict"&&B.push({id:"stage-file",label:x("terminal:fileExplorer.gitContextMenu.stageFile"),icon:e.jsx(M,{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(M,{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(M,{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(M,{name:"pin",size:14}),onClick:()=>{ue(k.path)}}),B.push({id:"copy-relative-path",label:x("terminal:fileExplorer.gitContextMenu.copyRelativePath"),icon:e.jsx(M,{name:"clipboard",size:14}),onClick:()=>{V(k.path)}}),R&&P!=="deleted"&&B.push({id:"reveal-in-tree",label:x("terminal:fileExplorer.gitContextMenu.revealInTree"),icon:e.jsx(M,{name:"target",size:14}),onClick:()=>R(k.path)}),B},[Z,o,i,C,R,ie,ue,V,x]),Q=s.useCallback((k,P)=>{k.preventDefault(),k.stopPropagation(),W({isOpen:!0,position:{x:k.clientX,y:k.clientY},node:P})},[]),te=s.useCallback(k=>!k.isDirectory&&k.file?[k.file]:k.children.flatMap(P=>te(P)),[]),Ne=s.useCallback(async k=>{if(!l)return;const P=te(k);if(P.length!==0)try{const B=await Y(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:l})}),ke=await B.json();B.ok&&ke.success?(O("success","Discarded",`Reverted ${P.length} file(s) in ${k.name}`),r()):O("error","Discard Failed",ke.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}},[l,te,r,O]),xe=s.useMemo(()=>{if(!T)return[];const{node:k}=T,P=te(k);return[{id:"discard-dir",label:`Discard Changes (${P.length} files)`,icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{Ne(k)}},{id:"stage-dir",label:`Stage All (${P.length} files)`,icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i(P.map(B=>B.path))}}]},[T,te,Ne,i]),U=s.useCallback(k=>{w(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),{conflictFiles:se,conflictTree:pe,changesFiles:me,changesTree:Be,untrackedFiles:Se,untrackedTree:It,allDirPaths:He}=s.useMemo(()=>{if(!t||!t.isGitRepo||t.files.length===0)return{conflictFiles:[],conflictTree:[],changesFiles:[],changesTree:[],untrackedFiles:[],untrackedTree:[],allDirPaths:new Set};const k=new Set,P=t.files.filter(Re=>Re.status==="conflict"),B=Mt(P);Dt(B,k);const ke=t.files.filter(Re=>Re.status==="modified"||Re.status==="added"||Re.status==="deleted"||Re.status==="renamed"),Te=Mt(ke);Dt(Te,k);const ot=t.files.filter(Re=>Re.status==="untracked"),We=Mt(ot);return Dt(We,k),{conflictFiles:P,conflictTree:B,changesFiles:ke,changesTree:Te,untrackedFiles:ot,untrackedTree:We,allDirPaths:k}},[t]);s.useEffect(()=>{w(He)},[He]),s.useEffect(()=>{t!=null&&t.files&&D(new Set(t.files.map(k=>k.path)))},[t==null?void 0:t.files]);const Pt=s.useCallback(()=>{me.length!==0&&be({files:me,label:`${me.length} changed files`})},[me]),_e=s.useCallback(()=>{Se.length!==0&&be({files:Se,label:`${Se.length} unversioned files`})},[Se]),Lt=s.useCallback(()=>{se.length!==0&&be({files:se,label:`${se.length} conflicted files`})},[se]),Ve=se.length>0;s.useEffect(()=>{if(re){const k=re.type==="error"?8e3:4e3,P=setTimeout(()=>_(null),k);return()=>clearTimeout(P)}},[re]);const gt=s.useCallback(async()=>{const k=!z;if(ae(k),k&&l){G(S);try{const B=await(await Y(K(`/api/files/git-log-message?path=${encodeURIComponent(l)}`))).json();B.message&&A(B.message)}catch{}}else A(H)},[z,l,S,H]),je=s.useCallback(k=>{D(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),$t=s.useCallback(()=>{if(!(t!=null&&t.files))return;const k=t.files.map(B=>B.path),P=k.every(B=>ee.has(B));D(P?new Set:new Set(k))},[t==null?void 0:t.files,ee]),ve=s.useCallback(async k=>{if(!(!l||!S.trim()||ee.size===0||F)){I(!0),_(null);try{const P=await Y(K("/api/files/git-commit"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:l,message:S.trim(),amend:z,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 Y(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:l})}),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")});A(""),G(""),ae(!1),r(),u==null||u()}catch(P){_({type:"error",text:P.message||"Commit failed"})}finally{I(!1)}}},[l,S,z,ee,F,r,u]);if(n)return e.jsx("div",{className:"git-changes-loading",children:x("terminal:fileExplorer.loadingGitStatus")});if(!t||!t.isGitRepo)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{name:"package",size:32})}),e.jsx("div",{className:"git-empty-text",children:x("terminal:fileExplorer.notGitRepo")})]});if(t.files.length===0)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{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:t.branch})})]});const xt=k=>{i([k])},Ke=()=>{const k=Se.map(P=>P.path);k.length>0&&i(k)},De=(k,P)=>{P==="conflict"&&C?C(k):o(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(M,{name:"git-branch",size:12})}),t.branch]}),t.counts&&e.jsxs("div",{className:"git-changes-summary",children:[(t.counts.conflict??0)>0&&e.jsxs("span",{className:"git-count conflict",children:[t.counts.conflict,"C"]}),t.counts.modified>0&&e.jsxs("span",{className:"git-count modified",children:[t.counts.modified,"M"]}),t.counts.added>0&&e.jsxs("span",{className:"git-count added",children:[t.counts.added,"A"]}),t.counts.deleted>0&&e.jsxs("span",{className:"git-count deleted",children:[t.counts.deleted,"D"]}),t.counts.untracked>0&&e.jsxs("span",{className:"git-count untracked",children:[t.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(M,{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:Ve,title:x(Ve?"terminal:fileExplorer.resolveAllConflictsFirst":"terminal:fileExplorer.continueMerge"),children:x("terminal:fileExplorer.continue")}),e.jsx("button",{className:"git-merge-abort-btn",onClick:y,title:x("terminal:fileExplorer.abortMerge"),children:x("terminal:fileExplorer.abort")})]})]}),e.jsxs("div",{className:"git-changes-list",children:[e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.conflicts"),groupIcon:"C",groupColor:"#ff5555",files:se,treeNodes:pe,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Lt}),e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.changes"),groupIcon:"~",groupColor:"#c89a5a",files:me,treeNodes:Be,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Pt}),e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.unversioned"),groupIcon:"?",groupColor:"#6ab8c8",files:Se,treeNodes:It,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,onStageFile:xt,onStageAll:Ke,stagingPaths:f,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:_e})]}),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:z,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:$t,title:ee.size===t.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll"),children:ee.size===t.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:S,onChange:k=>A(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:F}),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:!S.trim()||ee.size===0||F,title:x("terminal:fileExplorer.commitCtrlEnter"),children:x(F?"terminal:fileExplorer.committing":"terminal:fileExplorer.commitAction")}),e.jsx("button",{className:"git-commit-push-btn",onClick:()=>ve(!0),disabled:!S.trim()||ee.size===0||F,title:x("terminal:fileExplorer.commitAndPushCtrlShiftEnter"),children:F?"...":x("terminal:fileExplorer.commitAndPush")})]})]}),Z&&e.jsx(it,{isOpen:Z.isOpen,position:Z.position,worldPosition:{x:0,z:0},actions:E,onClose:()=>L(null)}),T&&e.jsx(it,{isOpen:T.isOpen,position:T.position,worldPosition:{x:0,z:0},actions:xe,onClose:()=>W(null)}),ne&&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:ne.files.some(k=>k.status==="untracked"||k.status==="added")?e.jsxs(e.Fragment,{children:["Delete ",e.jsx("strong",{children:ne.label}),"?"]}):e.jsxs(e.Fragment,{children:["Discard changes to ",e.jsx("strong",{children:ne.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:ne.files.some(k=>k.status==="untracked"||k.status==="added")?"Delete":"Discard"})]})]})})]})}const Ys=s.memo(Oa,(t,n)=>t.loading!==n.loading||t.selectedPath!==n.selectedPath||t.stagingPaths!==n.stagingPaths||t.currentFolder!==n.currentFolder||t.mergeInProgress!==n.mergeInProgress||t.mergingBranch!==n.mergingBranch?!1:t.gitStatus===null&&n.gitStatus===null?!0:!(t.gitStatus===null||n.gitStatus===null||t.gitStatus.isGitRepo!==n.gitStatus.isGitRepo||t.gitStatus.branch!==n.gitStatus.branch||t.gitStatus.files.length!==n.gitStatus.files.length||t.gitStatus.mergeInProgress!==n.gitStatus.mergeInProgress));Ys.displayName="GitChanges";const Ga=s.memo(function({tab:n,isActive:o,onSelect:c,onClose:r,onContextMenu:i}){const{t:f}=le(["terminal"]),l={name:n.filename,path:n.path,isDirectory:!1,extension:n.extension},u=s.useCallback(()=>{c(n.path)},[c,n.path]),g=s.useCallback(y=>{y.button===1&&(y.preventDefault(),y.stopPropagation(),r(n.path))},[r,n.path]),j=s.useCallback(y=>{y.preventDefault(),y.stopPropagation(),r(n.path)},[r,n.path]),p=s.useCallback(y=>{y.preventDefault(),y.stopPropagation(),i(y,n)},[i,n]);return e.jsxs("div",{className:`file-tab ${o?"active":""}`,onClick:u,onMouseDown:g,onContextMenu:p,title:n.path,children:[e.jsx("img",{className:"file-tab-icon",src:Xt(l),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 Ua(t){return typeof t.path=="string"&&t.path.startsWith("/")}function Ba({tabs:t,activeTabPath:n,onSelectTab:o,onCloseTab:c,onCloseAllTabs:r,onShowGitHistory:i}){const{t:f}=le(["terminal"]),[l,u]=s.useState(null),g=s.useCallback((y,C)=>{u({isOpen:!0,position:{x:y.clientX,y:y.clientY},tab:C})},[]),j=s.useCallback(()=>u(null),[]),p=s.useMemo(()=>{if(!l)return[];const y=l.tab,C=!!i&&Ua(y),R=[{id:"git-history",label:f("terminal:fileExplorer.showGitHistory")??"Show Git History",icon:e.jsx(M,{name:"git-commit",size:14}),disabled:!C,onClick:()=>{C&&i(y.path)}}];return r&&R.push({id:"divider-close-all",label:"",divider:!0,onClick:()=>{}},{id:"close-all-tabs",label:f("terminal:fileExplorer.closeAllTabs")??"Close all tabs",icon:e.jsx(M,{name:"cross",size:14}),danger:!0,onClick:()=>r()}),R},[l,i,r,f]);return t.length===0?null:e.jsxs("div",{className:"file-tabs-bar",children:[e.jsx("div",{className:"file-tabs-container",children:t.map(y=>e.jsx(Ga,{tab:y,isActive:n===y.path,onSelect:o,onClose:c,onContextMenu:g},y.path))}),l&&e.jsx(it,{isOpen:l.isOpen,position:l.position,worldPosition:{x:0,z:0},actions:p,onClose:j})]})}const qs=s.memo(Ba,(t,n)=>{if(t.activeTabPath!==n.activeTabPath||t.tabs.length!==n.tabs.length||t.onShowGitHistory!==n.onShowGitHistory||t.onCloseAllTabs!==n.onCloseAllTabs)return!1;for(let o=0;o<t.tabs.length;o++)if(t.tabs[o].path!==n.tabs[o].path)return!1;return!0});qs.displayName="FileTabs";const _a=s.memo(function({currentFolder:n,gitStatus:o,onBranchChanged:c,onMerge:r,onCompare:i,onPullConflicts:f}){const{t:l}=le(["terminal","common"]),[u,g]=s.useState(!1),[j,p]=s.useState(""),[y,C]=s.useState(!1),[R,x]=s.useState(""),[N,d]=s.useState(!1),[v,w]=s.useState(null),[S,A]=s.useState(null),H=s.useRef(null),G=s.useRef(null),z=s.useRef(null),{branches:ae,loading:ee,operationInProgress:D,loadBranches:F,checkoutBranch:I,createBranch:re,pullFromRemote:_,pushToRemote:ge}=Qt();s.useEffect(()=>{u&&n&&(F(n),setTimeout(()=>{var E;return(E=G.current)==null?void 0:E.focus()},50)),u||(p(""),C(!1),x(""),w(null))},[u,n,F]),s.useEffect(()=>{if(v){const E=v.type==="error"?8e3:3e3,Q=setTimeout(()=>w(null),E);return()=>clearTimeout(Q)}},[v]),s.useEffect(()=>{y&&setTimeout(()=>{var E;return(E=z.current)==null?void 0:E.focus()},50)},[y]),s.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 O=s.useCallback(async E=>{if(!n||D||E.isCurrent)return;const Q=await I(n,E.name);Q.success?(w({type:"success",text:l("terminal:fileExplorer.switchedToBranch",{branch:Q.branch||E.name})}),c(),F(n)):w({type:"error",text:Q.error||l("terminal:fileExplorer.checkoutFailed")})},[n,D,I,c,F]),Z=s.useCallback(async()=>{if(!n||!R.trim()||D)return;const E=await re(n,R.trim());E.success?(w({type:"success",text:l("terminal:fileExplorer.createdBranch",{branch:E.branch})}),C(!1),x(""),c(),F(n)):w({type:"error",text:E.error||l("terminal:fileExplorer.createBranchFailed")})},[n,R,D,re,c,F]),L=s.useCallback(async()=>{if(!n||D)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:l("terminal:fileExplorer.pullComplete")}),c(),F(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||l("terminal:fileExplorer.pullFailed")})},[n,D,_,c,F,f]),T=s.useCallback(async()=>{if(!n||D)return;const E=await ge(n);E.success?w({type:"success",text:l("terminal:fileExplorer.pushComplete")}):w({type:"error",text:E.error||l("terminal:fileExplorer.pushFailed")})},[n,D,ge]),[W,ne]=s.useState(!1),be=s.useCallback(async()=>{if(!(!n||D||W)){ne(!0);try{const E=await Y(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(),F(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{ne(!1)}}},[n,D,W,c,F]),de=(o==null?void 0:o.branch)||"unknown",m=!!D,q=s.useCallback((E,Q)=>{Q.isCurrent||(E.preventDefault(),E.stopPropagation(),A({isOpen:!0,position:{x:E.clientX,y:E.clientY},branch:Q.name}))},[]),ie=s.useMemo(()=>{if(!S)return[];const E=!!D||(o==null?void 0:o.mergeInProgress);return[{id:"compare",label:l("terminal:fileExplorer.showDiffWith",{branch:S.branch}),icon:e.jsx(M,{name:"arrows-horizontal",size:14}),disabled:!!D,onClick:()=>{i==null||i(S.branch),g(!1)}},{id:"merge",label:l("terminal:fileExplorer.mergeInto",{source:S.branch,target:de}),icon:"⤵",disabled:!!E,onClick:()=>{r&&r(S.branch),g(!1)}},{id:"divider-1",label:"",divider:!0,onClick:()=>{}},{id:"checkout",label:l("terminal:fileExplorer.checkoutBranch",{branch:S.branch}),icon:e.jsx(M,{name:"git-branch",size:14}),disabled:!!D,onClick:()=>{const Q=ae.find(te=>te.name===S.branch);Q&&O(Q)}}]},[S,D,o==null?void 0:o.mergeInProgress,de,r,i,ae,O]),ue=s.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=s.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:H,children:[e.jsx("div",{className:"branch-widget-search",children:e.jsx("input",{ref:G,type:"text",className:"branch-widget-search-input",placeholder:l("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:l("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:l(D==="pull"?"terminal:fileExplorer.pulling":"terminal:fileExplorer.pull")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:T,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:l(D==="push"?"terminal:fileExplorer.pushing":"terminal:fileExplorer.push")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:()=>{m||C(!y)},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:l("terminal:fileExplorer.newBranch")})]})]}),y&&e.jsxs("div",{className:"branch-widget-new-branch",children:[e.jsx("input",{ref:z,type:"text",className:"branch-widget-new-branch-input",placeholder:l("terminal:fileExplorer.branchNamePlaceholder"),value:R,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:!R.trim()||m,children:D==="create"?"...":l("common:buttons.create")})]}),e.jsxs("div",{className:"branch-widget-section-header",children:[l("terminal:fileExplorer.localBranches"),ee&&e.jsxs("span",{className:"branch-widget-loading-hint",children:[" ",l("terminal:fileExplorer.loading")]})]}),e.jsxs("div",{className:"branch-widget-branch-list",children:[ue.length===0&&!ee&&e.jsx("div",{className:"branch-widget-empty",children:l("terminal:fileExplorer.noBranchesFound")}),ue.map(E=>e.jsxs("div",{className:`branch-widget-branch-item ${E.isCurrent?"current":""} ${m?"disabled":""}`,onClick:()=>O(E),onContextMenu:Q=>q(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?"▾":"▸"}),l("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:()=>O(E),onContextMenu:Q=>q(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))})]})]}),S&&e.jsx(it,{isOpen:S.isOpen,position:S.position,worldPosition:{x:0,z:0},actions:ie,onClose:()=>A(null)})]})});function Va(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function St(t,n){if(!t)return"";const o=Es.languages[n];return o?Es.highlight(t,o,n):Va(t)}function Ka(t){const n=[],o=t.split(`
9
9
  `);let c=[],r=!1,i=[],f=[],l=!1;for(const u of o)u.startsWith("<<<<<<<")?(c.length>0&&(n.push({type:"unchanged",content:c.join(`
10
10
  `)}),c=[]),r=!0,l=!1,i=[],f=[]):u.startsWith("=======")&&r?l=!0:u.startsWith(">>>>>>>")&&r?(n.push({type:"conflict",ours:i.join(`
@@ -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 At,M as Rt,N as ht,O as le,P as pn,s as x,U as Ht,W as Vt,X as mn,v as Dt,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 $t,C as Sn,ad as En,ae as Mn,af as Tn,ag as Pn,ah as Ln,ai as Rn,aj as Dn,ak as zn,al as $n,am as On,an as Bn,ao as Fn,ap as Wn,aq as Hn,ar as Vn,as as Xn,at as Gn}from"./main-Cq5TB_d6.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Un(w){const d=a.useRef(w);d.current=w,a.useEffect(()=>{if(!rn())return;let v=null,A=!1;return Tt.addListener("backButton",()=>{d.current()==="exit"&&Tt.exitApp()}).then(E=>{A?E.remove():v=E}),()=>{A=!0,v&&(v.remove(),v=null)}},[])}const qn=a.memo(function({className:d=""}){const{t:v}=Wt(["common"]),[A,E]=on(),K=a.useRef(null),[B,De]=a.useState(null);a.useLayoutEffect(()=>{const g=K.current;if(!g)return;const Z=g.querySelector(".view-mode-toggle__btn--active");Z&&De({left:Z.offsetLeft,width:Z.offsetWidth})},[A]);const ie=a.useCallback(g=>{if(g!==A){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:g}})),g==="3d"){requestAnimationFrame(()=>E(g));return}E(g)}},[A,E]);return e.jsxs("div",{className:`view-mode-toggle ${d}`,ref:K,children:[B&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:B.left,width:B.width}}),cn.map(g=>e.jsxs("button",{className:`view-mode-toggle__btn ${A===g?"view-mode-toggle__btn--active":""}`,onClick:()=>ie(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))]})}),gt=3,xt=280,Ot=320,yt=240,Bt=64,Yn=["simple","chat","advanced"],Kn={simple:"Simple",chat:"Chat",advanced:"Advanced"},Zn={simple:"○",chat:"◐",advanced:"◉"},Jn={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 Qn(w){const d=w.split("/").filter(Boolean);return d.length===0?w:d.slice(-2).join("/")}function ea(w){if(w.provider==="codex"){const K=w.codexModel||"gpt-5.3-codex",B=Vn[K];return{model:(B==null?void 0:B.label)||K}}if(w.provider==="opencode")return{model:w.opencodeModel||"opencode"};const d=w.model||"sonnet",v=Gn[d],A=w.effort,E=A?Xn[A]:void 0;return{model:(v==null?void 0:v.label)||d,effort:E==null?void 0:E.label}}function ta(w,d){if(d.type==="rectangle"&&d.width&&d.height){const v=d.width/2,A=d.height/2;return w.x>=d.center.x-v&&w.x<=d.center.x+v&&w.z>=d.center.z-A&&w.z<=d.center.z+A}if(d.type==="circle"&&d.radius){const v=w.x-d.center.x,A=w.z-d.center.z;return v*v+A*A<=d.radius*d.radius}return!1}const na=En.memo(function({agentId:d,terminalViewMode:v,onTerminalViewModeChange:A,inspectorOpen:E,onToggleInspector:K,onImageClick:B,onFileClick:De,onBashClick:ie,onViewMarkdown:g,onRequestClearSubordinates:Z,onOpenBuilding:ye,keyboard:Ge,canNavigateBack:Ue,canNavigateForward:qe,onNavigateBack:pe,onNavigateForward:re,agentInfoOpen:me,onToggleAgentInfo:Ye,onHeaderContextMenu:J,onBuildingContextMenu:fe}){var ne,ct,$,ae;const f=Mn(d),F=Vt(),W=a.useRef(null),Ae=a.useRef(null);a.useEffect(()=>{const l=Ae.current;if(!l)return;const r=c=>{c.button===3?(c.preventDefault(),c.stopPropagation(),pe()):c.button===4&&(c.preventDefault(),c.stopPropagation(),re())},o=c=>{(c.button===3||c.button===4)&&c.preventDefault()};return l.addEventListener("mouseup",r),l.addEventListener("mousedown",o),()=>{l.removeEventListener("mouseup",r),l.removeEventListener("mousedown",o)}},[pe,re]),a.useEffect(()=>{const l=Ae.current;if(!l)return;let r=0,o=0,c=0;const Pe=250,Le=600,Re=80,Y=1.5,We=O=>{let T=O instanceof HTMLElement?O:null;for(;T&&T!==l;){const Ve=window.getComputedStyle(T).overflowX;if((Ve==="auto"||Ve==="scroll")&&T.scrollWidth>T.clientWidth)return!0;T=T.parentElement}return!1},He=O=>{const T=Date.now();if(T<c){O.preventDefault();return}if(Math.abs(O.deltaX)<=Math.abs(O.deltaY)*Y){r=0;return}if(We(O.target)){r=0;return}T-o>Pe&&(r=0),o=T,r+=O.deltaX,r<=-Re?(r=0,c=T+Le,O.preventDefault(),pe()):r>=Re&&(r=0,c=T+Le,O.preventDefault(),re())};return l.addEventListener("wheel",He,{passive:!1}),()=>l.removeEventListener("wheel",He)},[pe,re]);const Ie=Ht(),he=a.useMemo(()=>{if(!f)return null;const l=new Set,r=[];for(const o of Ie.values())o.archived||o.directories.length===0||o.assignedAgentIds.includes(d)&&(l.add(o.id),r.push(o));for(const o of Ie.values())o.archived||o.directories.length===0||l.has(o.id)||ta({x:f.position.x,z:f.position.z},o)&&(l.add(o.id),r.push(o));return r.length===0?null:r.flatMap(o=>o.directories.filter(c=>c&&c.trim().length>0).map(c=>({areaId:o.id,areaName:o.name,dir:c})))},[f,d,Ie]),{branches:Ke,fetchRemote:Ze,fetchingDirs:Je}=Tn(he),ge=a.useMemo(()=>{var o;const l=x.getAreaForAgent(d);if(!l)return[];const r=[];for(const c of F.values())c.type==="terminal"&&x.isPositionInArea(c.position,l)&&r.push({id:c.id,name:c.name,hasUrl:!!((o=c.terminalStatus)!=null&&o.url)});return r},[d,F]),Qe=a.useMemo(()=>{var o;const l=x.getAreaForAgent(d);if(!l)return[];const r=[];for(const c of F.values())c.type==="server"&&((o=c.pm2)!=null&&o.enabled)&&x.isPositionInArea(c.position,l)&&r.push({id:c.id,name:c.name});return r},[d,F]),xe=a.useMemo(()=>{const l=x.getAreaForAgent(d);if(!l)return[];const r=[];for(const o of F.values())o.type==="database"&&o.database&&x.isPositionInArea(o.position,l)&&r.push({id:o.id,name:o.name});return r},[d,F]),[,be]=a.useReducer(l=>l+1,0),H=((ne=W.current)==null?void 0:ne.search.searchMode)??!1,oe=a.useCallback(()=>{var l;(l=W.current)==null||l.search.toggleSearch(),be()},[]),et=Pn(),ze=et.isPending(Ft),[V,X]=a.useState(null),D=V?F.get(V):null,{height:Se,onResizeStart:G}=Ln(),{sidePanelWidth:Ee,handleSidePanelResizeStart:ce}=Rn(),[z,tt]=a.useState(()=>At(y.GIT_PANEL_OPEN,!1)),[_e,$e]=a.useState(()=>At(y.BUILDINGS_PANEL_OPEN,!1)),[U,nt]=a.useState(!1),bt=a.useCallback(()=>{nt(l=>{const r=!l;return r&&Dn.setEnabled(!0),r})},[]),we=a.useCallback(()=>nt(!1),[]),_t=a.useCallback(()=>{tt(l=>{const r=!l;return le(y.GIT_PANEL_OPEN,r),r})},[]),at=a.useCallback(()=>{$e(l=>{const r=!l;return le(y.BUILDINGS_PANEL_OPEN,r),r})},[]),wt=a.useCallback(()=>{tt(!1),le(y.GIT_PANEL_OPEN,!1)},[]),Oe=a.useCallback(()=>{$e(!1),le(y.BUILDINGS_PANEL_OPEN,!1)},[]),vt=zn();a.useEffect(()=>{if(!V)return;ge.some(r=>r.id===V)||X(null)},[V,ge]);const[ve,de]=a.useState(!1),Be=a.useRef(null);if(a.useEffect(()=>{if(!ve)return;const l=r=>{Be.current&&!Be.current.contains(r.target)&&de(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[ve]),!f)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const Q=f.contextStats,st=!!Q,Ce=Q?Q.totalTokens:f.contextUsed||0,h=Q?Q.contextWindow:f.contextLimit||2e5,ee=Q?Q.usedPercent:Math.round(Ce/h*100),M=Math.max(0,Math.min(100,ee)),Me=Math.round(M*10)/10,lt=Math.round((100-M)*10)/10,it=M>=80?"#ff4a4a":M>=60?"#ff9e4a":M>=40?"#ffd700":"#4aff9e",rt=(Ce/1e3).toFixed(1),ot=(h/1e3).toFixed(1),te=f.cwd,Te=te?Qn(te):null,q=((ct=f.subordinateIds)==null?void 0:ct.length)||0,Fe=q>0;return e.jsxs("div",{ref:Ae,className:`flat-terminal-wrapper ${z||_e||U?"flat-terminal-wrapper--with-side-panel":""}`,style:{"--guake-side-panel-width":`min(${Ee}px, 70%)`},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:Ye,onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),J({x:l.clientX,y:l.clientY})},title:me?"Hide agent info":"Show agent info","aria-pressed":me,children:[e.jsx(Xt,{agent:f,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:f.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:Gt(f.status)},children:f.status})]}),f.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:f.taskLabel,children:["📋 ",f.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:f.provider==="codex"?"/assets/codex.png":f.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:f.provider,className:"flat-terminal-wrapper__header-provider-icon",title:f.provider==="codex"?"Codex Agent":f.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:l,effort:r}=ea(f);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:Yn.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:Jn[l],"aria-pressed":v===l,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:Zn[l]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:Kn[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:!Ue,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:re,disabled:!qe,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 ${H?"flat-terminal-wrapper__action-btn--active":""}`,onClick:oe,title:H?"Close search":"Search messages","aria-pressed":H,children:e.jsx(u,{name:H?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${ze?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>et.handleClick(Ft,()=>{var l;x.clearContext(d),(l=W.current)==null||l.historyLoader.clearHistory()}),title:ze?"Click again to confirm clear context":"Clear context",children:e.jsx(u,{name:ze?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${z?"flat-terminal-wrapper__action-btn--active":""}`,onClick:_t,title:z?"Hide git panel":"Show git changes","aria-pressed":z,children:e.jsx(u,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${_e?"flat-terminal-wrapper__action-btn--active":""}`,onClick:at,title:_e?"Hide buildings panel":"Show area buildings","aria-pressed":_e,children:e.jsx(u,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:Be,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ve?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>de(l=>!l),title:"More actions","aria-expanded":ve,children:"⋮"}),ve&&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 ${U?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{bt(),de(!1)},title:U?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(u,{name:"bug",size:14}),e.jsx("span",{children:U?"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(d),de(!1)},disabled:f.status!=="idle",title:f.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"})]}),Fe&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{Z(d,q),de(!1)},children:[e.jsx(u,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",q," subordinate",q===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(d),de(!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 ${E?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:K,title:E?"Hide inspector panel":"Show inspector panel","aria-label":E?"Hide inspector panel":"Show inspector panel","aria-pressed":E,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($n,{ref:W,agentId:d,agent:f,viewMode:v,isOpen:!0,onImageClick:B,onFileClick:De,onBashClick:ie,onViewMarkdown:g,keyboard:Ge,hasModalOpen:!1}),D&&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: ${D.name}`,style:{height:Se},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:D.name}),!(($=D.terminalStatus)!=null&&$.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:(ae=D.terminalStatus)!=null&&ae.url?e.jsx(On,{terminalUrl:D.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."})})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[f.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(u,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),te&&Te&&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:Te})]}),he&&he.map(({areaId:l,areaName:r,dir:o})=>{const c=Ke.get(o),Pe=Je.has(o),Le=o.split("/").filter(Boolean).pop()||o;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${r}: ${o}${c?` (${c.branch}${c.ahead?` ↑${c.ahead}`:""}${c.behind?` ↓${c.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:Le}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(u,{name:"git-branch",size:10})," ",c.branch]}),c.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${c.ahead} ahead`,children:[e.jsx(u,{name:"arrow-up",size:9}),c.ahead]}),c.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${c.behind} behind`,children:[e.jsx(u,{name:"arrow-down",size:9}),c.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${Pe?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Re=>{Re.stopPropagation(),Ze(o)},children:e.jsx(u,{name:Pe?"hourglass":"download",size:12})})]})]},`${l}:${o}`)}),e.jsxs("span",{className:"flat-terminal-wrapper__context",onClick:()=>x.setContextModalAgentId(d),title:st?`Context usage: ${rt}k / ${ot}k tokens (${Me}% 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:`${M}%`,backgroundColor:it}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:it},children:[rt,"k/",ot,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",lt,"% free)"]}),!st&&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=V===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)})}),Qe.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:Qe.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(Bn,{})})]}),z&&e.jsx(Fn,{agentId:d,agents:vt,onClose:wt,branchInfoMap:Ke,fetchRemote:Ze,fetchingDirs:Je,onResizeStart:l=>ce(l,"right")}),_e&&e.jsx(Wn,{agentId:d,onClose:Oe}),U&&e.jsx(Hn,{agentId:d,onClose:we})]})});function ia({onAgentClick:w,onBuildingClick:d,onBuildingDoubleClick:v,onBuildingPopup:A,onAreaContextMenu:E,onOpenSpawnModal:K,onOpenBossSpawnModal:B,onOpenAreaModal:De}){const{t:ie}=Wt(["common"]),g=dn(),Z=un(),[ye,Ge]=a.useState(null),[Ue,qe]=a.useState(null),[pe,re]=a.useState(null),[me,Ye]=a.useState(null),[J,fe]=a.useState(null),[f,F]=a.useState(null),[W,Ae]=a.useState(null),[Ie,he]=a.useState(!1),Ke=a.useCallback(()=>{he(t=>!t)},[]),Ze=a.useCallback(()=>{he(!1)},[]),[Je,ge]=a.useState(()=>{const t=Pt(y.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Qe=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(()=>At(y.FLAT_INSPECTOR_OPEN,!1)),[H,oe]=a.useState(!1),et=a.useCallback(()=>oe(t=>!t),[]),ze=a.useCallback(()=>oe(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:H}}))},[H]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:xe}}))},[xe]),a.useEffect(()=>{const t=()=>oe(_=>!_),n=()=>{be(_=>{const i=!_;return le(y.FLAT_INSPECTOR_OPEN,i),i})},s=()=>{oe(!1),be(!1),le(y.FLAT_INSPECTOR_OPEN,!1)},p=()=>oe(!1),m=()=>{be(!1),le(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 V=a.useRef(null),X=a.useRef(null),[D,Se]=a.useState(()=>{const t=Rt(y.FLAT_MIDDLE_WIDTH,0);return t>=xt?t:null}),[G,Ee]=a.useState(()=>{const t=Rt(y.FLAT_INSPECTOR_WIDTH,0);return t>=yt?t:null}),ce=a.useCallback(t=>{if(typeof window>"u")return t;const n=G!==null?gt+G:0,s=window.innerWidth-Bt-gt-Ot-n;return Math.max(xt,Math.min(Math.max(s,xt),t))},[G]),z=a.useCallback(t=>{var m;if(typeof window>"u")return t;const n=(m=V.current)==null?void 0:m.querySelector(".flat-middle"),s=(n==null?void 0:n.getBoundingClientRect().width)??xt,p=window.innerWidth-Bt-s-gt-Ot-gt;return Math.max(yt,Math.min(Math.max(p,yt),t))},[]);a.useEffect(()=>{if(D===null&&G===null)return;const t=()=>{Se(n=>{if(n===null)return n;const s=ce(n);return s===n?n:s}),Ee(n=>{if(n===null)return n;const s=z(n);return s===n?n:s})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[D,G,ce,z]);const tt=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=V.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=V.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"))},[]),$e=a.useCallback(t=>{const n=X.current;if(!n||t.pointerId!==n.pointerId)return;const s=t.clientX-n.startX;n.kind==="middle"?Se(ce(n.startWidth+s)):Ee(z(n.startWidth-s))},[ce,z]),U=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=ce(n.startWidth+p);Se(m),ht(y.FLAT_MIDDLE_WIDTH,m)}else{const m=z(n.startWidth-p);Ee(m),ht(y.FLAT_INSPECTOR_WIDTH,m)}},[ce,z]),nt=a.useCallback(()=>{Se(null),ht(y.FLAT_MIDDLE_WIDTH,0)},[]),bt=a.useCallback(()=>{Ee(null),ht(y.FLAT_INSPECTOR_WIDTH,0)},[]),[we,_t]=a.useState(()=>Pt(y.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),at=a.useCallback(t=>{_t(t),Lt(y.FLAT_INSPECTOR_VIEW,t)},[]),wt=a.useCallback(()=>{be(t=>{const n=!t;return le(y.FLAT_INSPECTOR_OPEN,n),n})},[]),Oe=a.useCallback(()=>{be(!1),le(y.FLAT_INSPECTOR_OPEN,!1)},[]),vt=pn(),ve=a.useCallback((t,n)=>{Ge({url:t,name:n})},[]),de=a.useCallback((t,n)=>{qe({command:t,output:n,isLive:!1})},[]),Be=a.useCallback((t,n)=>{x.setFileViewerPath(t,n)},[]),Q=a.useCallback(t=>{re(t)},[]),st=a.useCallback((t,n)=>{Ye({agentId:t,count:n})},[]),Ce=a.useCallback(t=>{v?v(t):d(t)},[d,v]),h=a.useMemo(()=>Z.size>0?Array.from(Z)[0]:null,[Z]);a.useEffect(()=>{he(!1)},[h]);const ee=a.useRef([]),M=a.useRef(-1),Me=a.useRef(!1),lt=a.useRef(null),[it,rt]=a.useState(!1),[ot,te]=a.useState(!1),Te=a.useRef(!1),q=a.useRef(null),Fe=a.useRef(!1),ne=a.useMemo(()=>new Set(g.map(t=>t.id)),[g]),ct=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]),$=a.useCallback(()=>{const t=ee.current,n=M.current;rt(n>0),te(n>=0&&n<t.length-1)},[]),ae=a.useCallback(t=>{const n=ee.current;if(n.length===0)return;let s=M.current+t;for(;s>=0&&s<n.length;){const p=n[s];if(ne.has(p)){Me.current=!0,M.current=s,$(),x.selectAgent(p);return}s+=t}},[ne,$]),l=a.useCallback(()=>ae(-1),[ae]),r=a.useCallback(()=>ae(1),[ae]);Un(a.useCallback(()=>{const t=ee.current,n=M.current;return t.length>0&&n>0?(ae(-1),"handled"):"exit"},[ae]));const o=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(!h){Te.current=!1,q.current=null;return}if(!Te.current){o(h,"replace"),Te.current=!0,q.current=h;return}if(Fe.current){Fe.current=!1,q.current=h;return}q.current!==h&&(o(h,"push"),q.current=h)},[h,o]),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===h)return;Fe.current=!0,Me.current=!0;const p=ee.current,m=p.lastIndexOf(s);m>=0?M.current=m:(p.push(s),M.current=p.length-1),$(),x.selectAgent(s)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ne,h,$]),a.useEffect(()=>{if(!h){ee.current=[],M.current=-1,$();return}if(lt.current=h,Me.current){Me.current=!1,$();return}const t=ee.current,n=M.current;if(n>=0&&t[n]===h){$();return}const s=n<t.length-1?t.slice(0,n+1):t.slice();s.push(h),s.length>100&&s.shift(),ee.current=s,M.current=s.length-1,$()},[h,$]);const c=a.useCallback(t=>{w(t),oe(!1)},[w]),Pe=h??"",Le=a.useCallback(()=>{},[]),Re=a.useCallback(t=>{c(t)},[c]),Y=xe,[We,He]=a.useState(Y),[O,T]=a.useState(Y);a.useEffect(()=>{if(Y){He(!0);return}T(!1);const t=setTimeout(()=>He(!1),240);return()=>clearTimeout(t)},[Y]),a.useEffect(()=>{if(!We||!Y)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>T(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[We,Y]);const Ve=a.useRef(null);a.useEffect(()=>{if(h)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=lt.current;!p||!ne.has(p)||(n.preventDefault(),x.selectAgent(p))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[h,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[dt,Kt]=a.useState(null),Zt=a.useCallback(t=>{Kt(n=>n===t?null:t)},[]),Ct=Ht(),ut=Vt(),[Jt]=mn(),Ne=a.useMemo(()=>{const t=new Map,n=[];for(const b of g){const k=x.getAreaForAgent(b.id);if(!Dt((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 ut.values()){let k=!1;for(const N of Ct.values())if(!N.archived&&zt(N.id)&&x.isPositionInArea(b.position,N)){const se=s.get(N.id);se?se.push(b):s.set(N.id,[b]),k=!0;break}!k&&Dt(null)&&p.push(b)}const m=[];for(const[,b]of Ct){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 S=new Map;if(_.length>1){let b=1/0,k=-1/0,N=1/0,se=-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),se=Math.max(se,L.area.center.z);const pt=k-b||1,mt=se-N||1;if(_.length<=4){I=_.length,j=1;const L=[..._].sort((R,jt)=>R.area.center.x-jt.area.center.x);for(let R=0;R<L.length;R++)S.set(L[R].area.id,{row:1,col:R+1})}else{const L=[..._].sort((C,P)=>C.area.center.x-P.area.center.x),R=[];for(let C=1;C<L.length;C++)R.push(L[C].area.center.x-L[C-1].area.center.x);const jt=R.reduce((C,P)=>C+P,0)/R.length||1;let St=1;for(const C of R)C>jt*1.3&&St++;I=Math.max(2,Math.min(St,_.length));const Nt=[..._].sort((C,P)=>C.area.center.z-P.area.center.z),ft=[];for(let C=1;C<Nt.length;C++)ft.push(Nt[C].area.center.z-Nt[C-1].area.center.z);const nn=ft.reduce((C,P)=>C+P,0)/ft.length||1;let Et=1;for(const C of ft)C>nn*1.3&&Et++;j=Math.max(2,Math.min(Et,_.length)),I=Math.max(I,Math.ceil(_.length/j)),j=Math.max(j,Math.ceil(_.length/I));const an=pt/I,sn=mt/j,kt=new Set;for(const C of _){let P=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))),Xe=`${ke},${P}`,Mt=0;const ln=j*I;for(;kt.has(Xe)&&Mt<ln;)P++,P>=I&&(P=0,ke=(ke+1)%j),Xe=`${ke},${P}`,Mt++;kt.has(Xe)&&(ke=j,P=0,Xe=`${ke},${P}`,j++),kt.add(Xe),S.set(C.area.id,{row:ke+1,col:P+1})}}}const ue=b=>{b.sort((k,N)=>{var pt,mt,L,R;const se=(((pt=k.position)==null?void 0:pt.z)??0)-(((mt=N.position)==null?void 0:mt.z)??0);return se!==0?se:(((L=k.position)==null?void 0:L.x)??0)-(((R=N.position)==null?void 0:R.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:S}},[g,Ct,ut,Jt]),Qt=a.useMemo(()=>{if(!J)return[];const t=g.find(n=>n.id===J.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})}}]:[]},[J,g,w]),en=a.useMemo(()=>{var _;if(!f)return[];const t=ut.get(f.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:()=>Ce(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},[f,ut,Ce]),tn=a.useCallback(t=>{const n=new Set(Ne.groups.map(s=>s.area.id));n.delete(t),It(n),requestAnimationFrame(()=>{const s=Ve.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:V,className:`flat-view ${Y?"flat-view--with-inspector":""} ${h?"flat-view--has-chat":""} ${H?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(D===null&&G===null)return;const t={};return D!==null&&(t["--flat-middle-width"]=`${D}px`),G!==null&&(t["--flat-inspector-width"]=`${G}px`),t})(),children:[H&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:ze,"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:K,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:B,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:Pe,onClose:Le,onSelectAgent:Re,collapsedAreas:Ut,onToggleArea:qt,agentListRef:Ve})})]}),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:tt,onPointerMove:$e,onPointerUp:U,onPointerCancel:U,onDoubleClick:nt}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":H?"Close agents sidebar":"Open agents sidebar","aria-expanded":H,onClick:et,children:[e.jsx(u,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),h?e.jsx(na,{agentId:h,terminalViewMode:Je,onTerminalViewModeChange:Qe,inspectorOpen:xe,onToggleInspector:wt,onImageClick:ve,onFileClick:Be,onBashClick:de,onViewMarkdown:Q,onRequestClearSubordinates:st,onOpenBuilding:Ce,keyboard:vt,canNavigateBack:it,canNavigateForward:ot,onNavigateBack:l,onNavigateForward:r,agentInfoOpen:Ie,onToggleAgentInfo:Ke,onHeaderContextMenu:t=>{h&&fe({agentId:h,position:t})},onBuildingContextMenu:(t,n)=>{F({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(qn,{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&&dt?((n=Ne.positions.get(dt))==null?void 0:n.row)??null:null;return Ne.groups.map(s=>{const p=s.area.id,m=Ne.positions.get(p),_=je&&dt!==p;return je&&t!=null&&(m==null?void 0:m.row)===t&&p!==dt?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=>{E&&(i.preventDefault(),i.stopPropagation(),E(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?ct.get(i.id):void 0,S=hn(i),ue=S.usedPercent>=80?"#ff4a4a":S.usedPercent>=60?"#ff9e4a":S.usedPercent>=40?"#ffd700":"#4aff9e",b=`Context: ${(S.totalTokens/1e3).toFixed(1)}k / ${(S.contextWindow/1e3).toFixed(1)}k (${S.usedPercent}% used, ${S.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 At,M as Rt,N as ht,O as le,P as pn,s as x,U as Ht,W as Vt,X as mn,v as Dt,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 $t,C as Sn,ad as En,ae as Mn,af as Tn,ag as Pn,ah as Ln,ai as Rn,aj as Dn,ak as zn,al as $n,am as On,an as Bn,ao as Fn,ap as Wn,aq as Hn,ar as Vn,as as Xn,at as Gn}from"./main-Bon1sZAi.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Un(w){const d=a.useRef(w);d.current=w,a.useEffect(()=>{if(!rn())return;let v=null,A=!1;return Tt.addListener("backButton",()=>{d.current()==="exit"&&Tt.exitApp()}).then(E=>{A?E.remove():v=E}),()=>{A=!0,v&&(v.remove(),v=null)}},[])}const qn=a.memo(function({className:d=""}){const{t:v}=Wt(["common"]),[A,E]=on(),K=a.useRef(null),[B,De]=a.useState(null);a.useLayoutEffect(()=>{const g=K.current;if(!g)return;const Z=g.querySelector(".view-mode-toggle__btn--active");Z&&De({left:Z.offsetLeft,width:Z.offsetWidth})},[A]);const ie=a.useCallback(g=>{if(g!==A){if(typeof window<"u"&&window.dispatchEvent(new CustomEvent("tide:viewmode-switch-pressed",{detail:{mode:g}})),g==="3d"){requestAnimationFrame(()=>E(g));return}E(g)}},[A,E]);return e.jsxs("div",{className:`view-mode-toggle ${d}`,ref:K,children:[B&&e.jsx("div",{className:"view-mode-toggle__indicator",style:{left:B.left,width:B.width}}),cn.map(g=>e.jsxs("button",{className:`view-mode-toggle__btn ${A===g?"view-mode-toggle__btn--active":""}`,onClick:()=>ie(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))]})}),gt=3,xt=280,Ot=320,yt=240,Bt=64,Yn=["simple","chat","advanced"],Kn={simple:"Simple",chat:"Chat",advanced:"Advanced"},Zn={simple:"○",chat:"◐",advanced:"◉"},Jn={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 Qn(w){const d=w.split("/").filter(Boolean);return d.length===0?w:d.slice(-2).join("/")}function ea(w){if(w.provider==="codex"){const K=w.codexModel||"gpt-5.3-codex",B=Vn[K];return{model:(B==null?void 0:B.label)||K}}if(w.provider==="opencode")return{model:w.opencodeModel||"opencode"};const d=w.model||"sonnet",v=Gn[d],A=w.effort,E=A?Xn[A]:void 0;return{model:(v==null?void 0:v.label)||d,effort:E==null?void 0:E.label}}function ta(w,d){if(d.type==="rectangle"&&d.width&&d.height){const v=d.width/2,A=d.height/2;return w.x>=d.center.x-v&&w.x<=d.center.x+v&&w.z>=d.center.z-A&&w.z<=d.center.z+A}if(d.type==="circle"&&d.radius){const v=w.x-d.center.x,A=w.z-d.center.z;return v*v+A*A<=d.radius*d.radius}return!1}const na=En.memo(function({agentId:d,terminalViewMode:v,onTerminalViewModeChange:A,inspectorOpen:E,onToggleInspector:K,onImageClick:B,onFileClick:De,onBashClick:ie,onViewMarkdown:g,onRequestClearSubordinates:Z,onOpenBuilding:ye,keyboard:Ge,canNavigateBack:Ue,canNavigateForward:qe,onNavigateBack:pe,onNavigateForward:re,agentInfoOpen:me,onToggleAgentInfo:Ye,onHeaderContextMenu:J,onBuildingContextMenu:fe}){var ne,ct,$,ae;const f=Mn(d),F=Vt(),W=a.useRef(null),Ae=a.useRef(null);a.useEffect(()=>{const l=Ae.current;if(!l)return;const r=c=>{c.button===3?(c.preventDefault(),c.stopPropagation(),pe()):c.button===4&&(c.preventDefault(),c.stopPropagation(),re())},o=c=>{(c.button===3||c.button===4)&&c.preventDefault()};return l.addEventListener("mouseup",r),l.addEventListener("mousedown",o),()=>{l.removeEventListener("mouseup",r),l.removeEventListener("mousedown",o)}},[pe,re]),a.useEffect(()=>{const l=Ae.current;if(!l)return;let r=0,o=0,c=0;const Pe=250,Le=600,Re=80,Y=1.5,We=O=>{let T=O instanceof HTMLElement?O:null;for(;T&&T!==l;){const Ve=window.getComputedStyle(T).overflowX;if((Ve==="auto"||Ve==="scroll")&&T.scrollWidth>T.clientWidth)return!0;T=T.parentElement}return!1},He=O=>{const T=Date.now();if(T<c){O.preventDefault();return}if(Math.abs(O.deltaX)<=Math.abs(O.deltaY)*Y){r=0;return}if(We(O.target)){r=0;return}T-o>Pe&&(r=0),o=T,r+=O.deltaX,r<=-Re?(r=0,c=T+Le,O.preventDefault(),pe()):r>=Re&&(r=0,c=T+Le,O.preventDefault(),re())};return l.addEventListener("wheel",He,{passive:!1}),()=>l.removeEventListener("wheel",He)},[pe,re]);const Ie=Ht(),he=a.useMemo(()=>{if(!f)return null;const l=new Set,r=[];for(const o of Ie.values())o.archived||o.directories.length===0||o.assignedAgentIds.includes(d)&&(l.add(o.id),r.push(o));for(const o of Ie.values())o.archived||o.directories.length===0||l.has(o.id)||ta({x:f.position.x,z:f.position.z},o)&&(l.add(o.id),r.push(o));return r.length===0?null:r.flatMap(o=>o.directories.filter(c=>c&&c.trim().length>0).map(c=>({areaId:o.id,areaName:o.name,dir:c})))},[f,d,Ie]),{branches:Ke,fetchRemote:Ze,fetchingDirs:Je}=Tn(he),ge=a.useMemo(()=>{var o;const l=x.getAreaForAgent(d);if(!l)return[];const r=[];for(const c of F.values())c.type==="terminal"&&x.isPositionInArea(c.position,l)&&r.push({id:c.id,name:c.name,hasUrl:!!((o=c.terminalStatus)!=null&&o.url)});return r},[d,F]),Qe=a.useMemo(()=>{var o;const l=x.getAreaForAgent(d);if(!l)return[];const r=[];for(const c of F.values())c.type==="server"&&((o=c.pm2)!=null&&o.enabled)&&x.isPositionInArea(c.position,l)&&r.push({id:c.id,name:c.name});return r},[d,F]),xe=a.useMemo(()=>{const l=x.getAreaForAgent(d);if(!l)return[];const r=[];for(const o of F.values())o.type==="database"&&o.database&&x.isPositionInArea(o.position,l)&&r.push({id:o.id,name:o.name});return r},[d,F]),[,be]=a.useReducer(l=>l+1,0),H=((ne=W.current)==null?void 0:ne.search.searchMode)??!1,oe=a.useCallback(()=>{var l;(l=W.current)==null||l.search.toggleSearch(),be()},[]),et=Pn(),ze=et.isPending(Ft),[V,X]=a.useState(null),D=V?F.get(V):null,{height:Se,onResizeStart:G}=Ln(),{sidePanelWidth:Ee,handleSidePanelResizeStart:ce}=Rn(),[z,tt]=a.useState(()=>At(y.GIT_PANEL_OPEN,!1)),[_e,$e]=a.useState(()=>At(y.BUILDINGS_PANEL_OPEN,!1)),[U,nt]=a.useState(!1),bt=a.useCallback(()=>{nt(l=>{const r=!l;return r&&Dn.setEnabled(!0),r})},[]),we=a.useCallback(()=>nt(!1),[]),_t=a.useCallback(()=>{tt(l=>{const r=!l;return le(y.GIT_PANEL_OPEN,r),r})},[]),at=a.useCallback(()=>{$e(l=>{const r=!l;return le(y.BUILDINGS_PANEL_OPEN,r),r})},[]),wt=a.useCallback(()=>{tt(!1),le(y.GIT_PANEL_OPEN,!1)},[]),Oe=a.useCallback(()=>{$e(!1),le(y.BUILDINGS_PANEL_OPEN,!1)},[]),vt=zn();a.useEffect(()=>{if(!V)return;ge.some(r=>r.id===V)||X(null)},[V,ge]);const[ve,de]=a.useState(!1),Be=a.useRef(null);if(a.useEffect(()=>{if(!ve)return;const l=r=>{Be.current&&!Be.current.contains(r.target)&&de(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[ve]),!f)return e.jsx("div",{className:"flat-chat flat-chat--empty",children:e.jsxs("div",{className:"flat-chat__placeholder",children:[e.jsx("span",{className:"flat-chat__placeholder-icon",children:"💬"}),e.jsx("span",{className:"flat-chat__placeholder-text",children:"Select an agent to start chatting"})]})});const Q=f.contextStats,st=!!Q,Ce=Q?Q.totalTokens:f.contextUsed||0,h=Q?Q.contextWindow:f.contextLimit||2e5,ee=Q?Q.usedPercent:Math.round(Ce/h*100),M=Math.max(0,Math.min(100,ee)),Me=Math.round(M*10)/10,lt=Math.round((100-M)*10)/10,it=M>=80?"#ff4a4a":M>=60?"#ff9e4a":M>=40?"#ffd700":"#4aff9e",rt=(Ce/1e3).toFixed(1),ot=(h/1e3).toFixed(1),te=f.cwd,Te=te?Qn(te):null,q=((ct=f.subordinateIds)==null?void 0:ct.length)||0,Fe=q>0;return e.jsxs("div",{ref:Ae,className:`flat-terminal-wrapper ${z||_e||U?"flat-terminal-wrapper--with-side-panel":""}`,style:{"--guake-side-panel-width":`min(${Ee}px, 70%)`},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:Ye,onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),J({x:l.clientX,y:l.clientY})},title:me?"Hide agent info":"Show agent info","aria-pressed":me,children:[e.jsx(Xt,{agent:f,size:28}),e.jsxs("span",{className:"flat-terminal-wrapper__header-info",children:[e.jsx("span",{className:"flat-terminal-wrapper__header-name",children:f.name}),e.jsx("span",{className:"flat-terminal-wrapper__header-status",style:{color:Gt(f.status)},children:f.status})]}),f.taskLabel&&e.jsxs("span",{className:"flat-terminal-wrapper__header-task",title:f.taskLabel,children:["📋 ",f.taskLabel]}),e.jsxs("span",{className:"flat-terminal-wrapper__header-model",children:[e.jsx("img",{src:f.provider==="codex"?"/assets/codex.png":f.provider==="opencode"?"/assets/opencode.png":"/assets/claude.png",alt:f.provider,className:"flat-terminal-wrapper__header-provider-icon",title:f.provider==="codex"?"Codex Agent":f.provider==="opencode"?"OpenCode Agent":"Claude Agent"}),(()=>{const{model:l,effort:r}=ea(f);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:Yn.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:Jn[l],"aria-pressed":v===l,children:[e.jsx("span",{className:"flat-terminal-wrapper__view-mode-icon","aria-hidden":"true",children:Zn[l]}),e.jsx("span",{className:"flat-terminal-wrapper__view-mode-label",children:Kn[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:!Ue,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:re,disabled:!qe,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 ${H?"flat-terminal-wrapper__action-btn--active":""}`,onClick:oe,title:H?"Close search":"Search messages","aria-pressed":H,children:e.jsx(u,{name:H?"cross":"search",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn flat-terminal-wrapper__action-btn--danger ${ze?"flat-terminal-wrapper__action-btn--confirm":""}`,onClick:()=>et.handleClick(Ft,()=>{var l;x.clearContext(d),(l=W.current)==null||l.historyLoader.clearHistory()}),title:ze?"Click again to confirm clear context":"Clear context",children:e.jsx(u,{name:ze?"question":"clear",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${z?"flat-terminal-wrapper__action-btn--active":""}`,onClick:_t,title:z?"Hide git panel":"Show git changes","aria-pressed":z,children:e.jsx(u,{name:"git-branch",size:14})}),e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${_e?"flat-terminal-wrapper__action-btn--active":""}`,onClick:at,title:_e?"Hide buildings panel":"Show area buildings","aria-pressed":_e,children:e.jsx(u,{name:"buildings",size:14})}),e.jsxs("div",{className:"flat-terminal-wrapper__more",ref:Be,children:[e.jsx("button",{type:"button",className:`flat-terminal-wrapper__action-btn ${ve?"flat-terminal-wrapper__action-btn--active":""}`,onClick:()=>de(l=>!l),title:"More actions","aria-expanded":ve,children:"⋮"}),ve&&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 ${U?"flat-terminal-wrapper__more-item--active":""}`,onClick:()=>{bt(),de(!1)},title:U?"Hide Debug Panel":"Show Debug Panel",children:[e.jsx(u,{name:"bug",size:14}),e.jsx("span",{children:U?"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(d),de(!1)},disabled:f.status!=="idle",title:f.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"})]}),Fe&&e.jsxs("button",{type:"button",role:"menuitem",className:"flat-terminal-wrapper__more-item flat-terminal-wrapper__more-item--danger",onClick:()=>{Z(d,q),de(!1)},children:[e.jsx(u,{name:"crown",size:14}),e.jsxs("span",{children:["Clear ",q," subordinate",q===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(d),de(!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 ${E?"flat-terminal-wrapper__inspector-toggle--active":""}`,onClick:K,title:E?"Hide inspector panel":"Show inspector panel","aria-label":E?"Hide inspector panel":"Show inspector panel","aria-pressed":E,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($n,{ref:W,agentId:d,agent:f,viewMode:v,isOpen:!0,onImageClick:B,onFileClick:De,onBashClick:ie,onViewMarkdown:g,keyboard:Ge,hasModalOpen:!1}),D&&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: ${D.name}`,style:{height:Se},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:D.name}),!(($=D.terminalStatus)!=null&&$.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:(ae=D.terminalStatus)!=null&&ae.url?e.jsx(On,{terminalUrl:D.terminalStatus.url,visible:!0}):e.jsx("div",{className:"flat-bottom-panel__placeholder",children:"Starting terminal..."})})]})]}),e.jsxs("div",{className:"flat-terminal-wrapper__statusbar",role:"contentinfo",children:[f.isDetached&&e.jsxs("span",{className:"flat-terminal-wrapper__detached",title:"Reattaching session...",children:[e.jsx(u,{name:"refresh",size:12}),e.jsx("span",{children:"Reattaching"})]}),te&&Te&&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:Te})]}),he&&he.map(({areaId:l,areaName:r,dir:o})=>{const c=Ke.get(o),Pe=Je.has(o),Le=o.split("/").filter(Boolean).pop()||o;return e.jsxs("span",{className:"flat-terminal-wrapper__area-dir",title:`${r}: ${o}${c?` (${c.branch}${c.ahead?` ↑${c.ahead}`:""}${c.behind?` ↓${c.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:Le}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flat-terminal-wrapper__area-dir-branch",children:[e.jsx(u,{name:"git-branch",size:10})," ",c.branch]}),c.ahead>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-ahead",title:`${c.ahead} ahead`,children:[e.jsx(u,{name:"arrow-up",size:9}),c.ahead]}),c.behind>0&&e.jsxs("span",{className:"flat-terminal-wrapper__branch-behind",title:`${c.behind} behind`,children:[e.jsx(u,{name:"arrow-down",size:9}),c.behind]}),e.jsx("span",{className:`flat-terminal-wrapper__area-fetch ${Pe?"flat-terminal-wrapper__area-fetch--fetching":""}`,title:"Git fetch",onClick:Re=>{Re.stopPropagation(),Ze(o)},children:e.jsx(u,{name:Pe?"hourglass":"download",size:12})})]})]},`${l}:${o}`)}),e.jsxs("span",{className:"flat-terminal-wrapper__context",onClick:()=>x.setContextModalAgentId(d),title:st?`Context usage: ${rt}k / ${ot}k tokens (${Me}% 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:`${M}%`,backgroundColor:it}})}),e.jsxs("span",{className:"flat-terminal-wrapper__context-tokens",style:{color:it},children:[rt,"k/",ot,"k"]}),e.jsxs("span",{className:"flat-terminal-wrapper__context-free",children:["(",lt,"% free)"]}),!st&&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=V===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)})}),Qe.length>0&&e.jsx("span",{className:"flat-terminal-wrapper__buildings",role:"group","aria-label":"Area PM2 logs",children:Qe.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(Bn,{})})]}),z&&e.jsx(Fn,{agentId:d,agents:vt,onClose:wt,branchInfoMap:Ke,fetchRemote:Ze,fetchingDirs:Je,onResizeStart:l=>ce(l,"right")}),_e&&e.jsx(Wn,{agentId:d,onClose:Oe}),U&&e.jsx(Hn,{agentId:d,onClose:we})]})});function ia({onAgentClick:w,onBuildingClick:d,onBuildingDoubleClick:v,onBuildingPopup:A,onAreaContextMenu:E,onOpenSpawnModal:K,onOpenBossSpawnModal:B,onOpenAreaModal:De}){const{t:ie}=Wt(["common"]),g=dn(),Z=un(),[ye,Ge]=a.useState(null),[Ue,qe]=a.useState(null),[pe,re]=a.useState(null),[me,Ye]=a.useState(null),[J,fe]=a.useState(null),[f,F]=a.useState(null),[W,Ae]=a.useState(null),[Ie,he]=a.useState(!1),Ke=a.useCallback(()=>{he(t=>!t)},[]),Ze=a.useCallback(()=>{he(!1)},[]),[Je,ge]=a.useState(()=>{const t=Pt(y.VIEW_MODE);return t==="simple"||t==="chat"||t==="advanced"?t:"simple"}),Qe=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(()=>At(y.FLAT_INSPECTOR_OPEN,!1)),[H,oe]=a.useState(!1),et=a.useCallback(()=>oe(t=>!t),[]),ze=a.useCallback(()=>oe(!1),[]);a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-agents-drawer-state",{detail:{open:H}}))},[H]),a.useEffect(()=>{window.dispatchEvent(new CustomEvent("tide-flat-inspector-state",{detail:{open:xe}}))},[xe]),a.useEffect(()=>{const t=()=>oe(_=>!_),n=()=>{be(_=>{const i=!_;return le(y.FLAT_INSPECTOR_OPEN,i),i})},s=()=>{oe(!1),be(!1),le(y.FLAT_INSPECTOR_OPEN,!1)},p=()=>oe(!1),m=()=>{be(!1),le(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 V=a.useRef(null),X=a.useRef(null),[D,Se]=a.useState(()=>{const t=Rt(y.FLAT_MIDDLE_WIDTH,0);return t>=xt?t:null}),[G,Ee]=a.useState(()=>{const t=Rt(y.FLAT_INSPECTOR_WIDTH,0);return t>=yt?t:null}),ce=a.useCallback(t=>{if(typeof window>"u")return t;const n=G!==null?gt+G:0,s=window.innerWidth-Bt-gt-Ot-n;return Math.max(xt,Math.min(Math.max(s,xt),t))},[G]),z=a.useCallback(t=>{var m;if(typeof window>"u")return t;const n=(m=V.current)==null?void 0:m.querySelector(".flat-middle"),s=(n==null?void 0:n.getBoundingClientRect().width)??xt,p=window.innerWidth-Bt-s-gt-Ot-gt;return Math.max(yt,Math.min(Math.max(p,yt),t))},[]);a.useEffect(()=>{if(D===null&&G===null)return;const t=()=>{Se(n=>{if(n===null)return n;const s=ce(n);return s===n?n:s}),Ee(n=>{if(n===null)return n;const s=z(n);return s===n?n:s})};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[D,G,ce,z]);const tt=a.useCallback(t=>{var s;if(t.button!==0)return;const n=(s=V.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=V.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"))},[]),$e=a.useCallback(t=>{const n=X.current;if(!n||t.pointerId!==n.pointerId)return;const s=t.clientX-n.startX;n.kind==="middle"?Se(ce(n.startWidth+s)):Ee(z(n.startWidth-s))},[ce,z]),U=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=ce(n.startWidth+p);Se(m),ht(y.FLAT_MIDDLE_WIDTH,m)}else{const m=z(n.startWidth-p);Ee(m),ht(y.FLAT_INSPECTOR_WIDTH,m)}},[ce,z]),nt=a.useCallback(()=>{Se(null),ht(y.FLAT_MIDDLE_WIDTH,0)},[]),bt=a.useCallback(()=>{Ee(null),ht(y.FLAT_INSPECTOR_WIDTH,0)},[]),[we,_t]=a.useState(()=>Pt(y.FLAT_INSPECTOR_VIEW)==="tracking"?"tracking":"agent"),at=a.useCallback(t=>{_t(t),Lt(y.FLAT_INSPECTOR_VIEW,t)},[]),wt=a.useCallback(()=>{be(t=>{const n=!t;return le(y.FLAT_INSPECTOR_OPEN,n),n})},[]),Oe=a.useCallback(()=>{be(!1),le(y.FLAT_INSPECTOR_OPEN,!1)},[]),vt=pn(),ve=a.useCallback((t,n)=>{Ge({url:t,name:n})},[]),de=a.useCallback((t,n)=>{qe({command:t,output:n,isLive:!1})},[]),Be=a.useCallback((t,n)=>{x.setFileViewerPath(t,n)},[]),Q=a.useCallback(t=>{re(t)},[]),st=a.useCallback((t,n)=>{Ye({agentId:t,count:n})},[]),Ce=a.useCallback(t=>{v?v(t):d(t)},[d,v]),h=a.useMemo(()=>Z.size>0?Array.from(Z)[0]:null,[Z]);a.useEffect(()=>{he(!1)},[h]);const ee=a.useRef([]),M=a.useRef(-1),Me=a.useRef(!1),lt=a.useRef(null),[it,rt]=a.useState(!1),[ot,te]=a.useState(!1),Te=a.useRef(!1),q=a.useRef(null),Fe=a.useRef(!1),ne=a.useMemo(()=>new Set(g.map(t=>t.id)),[g]),ct=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]),$=a.useCallback(()=>{const t=ee.current,n=M.current;rt(n>0),te(n>=0&&n<t.length-1)},[]),ae=a.useCallback(t=>{const n=ee.current;if(n.length===0)return;let s=M.current+t;for(;s>=0&&s<n.length;){const p=n[s];if(ne.has(p)){Me.current=!0,M.current=s,$(),x.selectAgent(p);return}s+=t}},[ne,$]),l=a.useCallback(()=>ae(-1),[ae]),r=a.useCallback(()=>ae(1),[ae]);Un(a.useCallback(()=>{const t=ee.current,n=M.current;return t.length>0&&n>0?(ae(-1),"handled"):"exit"},[ae]));const o=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(!h){Te.current=!1,q.current=null;return}if(!Te.current){o(h,"replace"),Te.current=!0,q.current=h;return}if(Fe.current){Fe.current=!1,q.current=h;return}q.current!==h&&(o(h,"push"),q.current=h)},[h,o]),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===h)return;Fe.current=!0,Me.current=!0;const p=ee.current,m=p.lastIndexOf(s);m>=0?M.current=m:(p.push(s),M.current=p.length-1),$(),x.selectAgent(s)};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[ne,h,$]),a.useEffect(()=>{if(!h){ee.current=[],M.current=-1,$();return}if(lt.current=h,Me.current){Me.current=!1,$();return}const t=ee.current,n=M.current;if(n>=0&&t[n]===h){$();return}const s=n<t.length-1?t.slice(0,n+1):t.slice();s.push(h),s.length>100&&s.shift(),ee.current=s,M.current=s.length-1,$()},[h,$]);const c=a.useCallback(t=>{w(t),oe(!1)},[w]),Pe=h??"",Le=a.useCallback(()=>{},[]),Re=a.useCallback(t=>{c(t)},[c]),Y=xe,[We,He]=a.useState(Y),[O,T]=a.useState(Y);a.useEffect(()=>{if(Y){He(!0);return}T(!1);const t=setTimeout(()=>He(!1),240);return()=>clearTimeout(t)},[Y]),a.useEffect(()=>{if(!We||!Y)return;let t=0;const n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>T(!0))});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(t)}},[We,Y]);const Ve=a.useRef(null);a.useEffect(()=>{if(h)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=lt.current;!p||!ne.has(p)||(n.preventDefault(),x.selectAgent(p))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[h,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[dt,Kt]=a.useState(null),Zt=a.useCallback(t=>{Kt(n=>n===t?null:t)},[]),Ct=Ht(),ut=Vt(),[Jt]=mn(),Ne=a.useMemo(()=>{const t=new Map,n=[];for(const b of g){const k=x.getAreaForAgent(b.id);if(!Dt((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 ut.values()){let k=!1;for(const N of Ct.values())if(!N.archived&&zt(N.id)&&x.isPositionInArea(b.position,N)){const se=s.get(N.id);se?se.push(b):s.set(N.id,[b]),k=!0;break}!k&&Dt(null)&&p.push(b)}const m=[];for(const[,b]of Ct){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 S=new Map;if(_.length>1){let b=1/0,k=-1/0,N=1/0,se=-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),se=Math.max(se,L.area.center.z);const pt=k-b||1,mt=se-N||1;if(_.length<=4){I=_.length,j=1;const L=[..._].sort((R,jt)=>R.area.center.x-jt.area.center.x);for(let R=0;R<L.length;R++)S.set(L[R].area.id,{row:1,col:R+1})}else{const L=[..._].sort((C,P)=>C.area.center.x-P.area.center.x),R=[];for(let C=1;C<L.length;C++)R.push(L[C].area.center.x-L[C-1].area.center.x);const jt=R.reduce((C,P)=>C+P,0)/R.length||1;let St=1;for(const C of R)C>jt*1.3&&St++;I=Math.max(2,Math.min(St,_.length));const Nt=[..._].sort((C,P)=>C.area.center.z-P.area.center.z),ft=[];for(let C=1;C<Nt.length;C++)ft.push(Nt[C].area.center.z-Nt[C-1].area.center.z);const nn=ft.reduce((C,P)=>C+P,0)/ft.length||1;let Et=1;for(const C of ft)C>nn*1.3&&Et++;j=Math.max(2,Math.min(Et,_.length)),I=Math.max(I,Math.ceil(_.length/j)),j=Math.max(j,Math.ceil(_.length/I));const an=pt/I,sn=mt/j,kt=new Set;for(const C of _){let P=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))),Xe=`${ke},${P}`,Mt=0;const ln=j*I;for(;kt.has(Xe)&&Mt<ln;)P++,P>=I&&(P=0,ke=(ke+1)%j),Xe=`${ke},${P}`,Mt++;kt.has(Xe)&&(ke=j,P=0,Xe=`${ke},${P}`,j++),kt.add(Xe),S.set(C.area.id,{row:ke+1,col:P+1})}}}const ue=b=>{b.sort((k,N)=>{var pt,mt,L,R;const se=(((pt=k.position)==null?void 0:pt.z)??0)-(((mt=N.position)==null?void 0:mt.z)??0);return se!==0?se:(((L=k.position)==null?void 0:L.x)??0)-(((R=N.position)==null?void 0:R.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:S}},[g,Ct,ut,Jt]),Qt=a.useMemo(()=>{if(!J)return[];const t=g.find(n=>n.id===J.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})}}]:[]},[J,g,w]),en=a.useMemo(()=>{var _;if(!f)return[];const t=ut.get(f.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:()=>Ce(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},[f,ut,Ce]),tn=a.useCallback(t=>{const n=new Set(Ne.groups.map(s=>s.area.id));n.delete(t),It(n),requestAnimationFrame(()=>{const s=Ve.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:V,className:`flat-view ${Y?"flat-view--with-inspector":""} ${h?"flat-view--has-chat":""} ${H?"flat-view--mobile-sidebar-open":""}`,style:(()=>{if(D===null&&G===null)return;const t={};return D!==null&&(t["--flat-middle-width"]=`${D}px`),G!==null&&(t["--flat-inspector-width"]=`${G}px`),t})(),children:[H&&e.jsx("div",{className:"flat-mobile-sidebar-backdrop",onClick:ze,"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:K,title:"Create new agent",children:"+ Agent"}),e.jsx("button",{className:"flat-cta-btn flat-cta-btn--boss",onClick:B,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:Pe,onClose:Le,onSelectAgent:Re,collapsedAreas:Ut,onToggleArea:qt,agentListRef:Ve})})]}),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:tt,onPointerMove:$e,onPointerUp:U,onPointerCancel:U,onDoubleClick:nt}),e.jsxs("div",{className:"flat-right",children:[e.jsxs("button",{type:"button",className:"flat-mobile-sidebar-toggle","aria-label":H?"Close agents sidebar":"Open agents sidebar","aria-expanded":H,onClick:et,children:[e.jsx(u,{name:"list",size:18}),e.jsx("span",{className:"flat-mobile-sidebar-toggle__label",children:"Agents"})]}),h?e.jsx(na,{agentId:h,terminalViewMode:Je,onTerminalViewModeChange:Qe,inspectorOpen:xe,onToggleInspector:wt,onImageClick:ve,onFileClick:Be,onBashClick:de,onViewMarkdown:Q,onRequestClearSubordinates:st,onOpenBuilding:Ce,keyboard:vt,canNavigateBack:it,canNavigateForward:ot,onNavigateBack:l,onNavigateForward:r,agentInfoOpen:Ie,onToggleAgentInfo:Ke,onHeaderContextMenu:t=>{h&&fe({agentId:h,position:t})},onBuildingContextMenu:(t,n)=>{F({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(qn,{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&&dt?((n=Ne.positions.get(dt))==null?void 0:n.row)??null:null;return Ne.groups.map(s=>{const p=s.area.id,m=Ne.positions.get(p),_=je&&dt!==p;return je&&t!=null&&(m==null?void 0:m.row)===t&&p!==dt?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=>{E&&(i.preventDefault(),i.stopPropagation(),E(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?ct.get(i.id):void 0,S=hn(i),ue=S.usedPercent>=80?"#ff4a4a":S.usedPercent>=60?"#ff9e4a":S.usedPercent>=40?"#ffd700":"#4aff9e",b=`Context: ${(S.totalTokens/1e3).toFixed(1)}k / ${(S.contextWindow/1e3).toFixed(1)}k (${S.usedPercent}% used, ${S.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:`${S.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:S=>{if(A){const ue=S.currentTarget.getBoundingClientRect();A(i.id,{x:ue.right,y:ue.top+ue.height/2})}else Ce(i.id)},onContextMenu:S=>{S.preventDefault(),S.stopPropagation(),F({buildingId:i.id,position:{x:S.clientX,y:S.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)})})()})]})})]}),Y&&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:$e,onPointerUp:U,onPointerCancel:U,onDoubleClick:bt}),We&&e.jsxs("aside",{className:`flat-inspector ${O?"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:()=>at("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:()=>at("tracking"),children:"Tracking"})]}),e.jsx("button",{type:"button",className:"flat-inspector__close",onClick:Oe,title:"Close inspector","aria-label":"Close inspector",children:"✕"})]}),e.jsx("div",{className:"flat-inspector__body",children:we==="tracking"?e.jsx(Cn,{activeAgentId:h??"",onSelectAgent:t=>{w(t),window.innerWidth<=768&&Oe()}}):(()=>{if(!h)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===h);return t?e.jsx(jn,{agent:t,onFocusAgent:n=>{w(n),window.innerWidth<=768&&Oe()},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:()=>Ge(null)}),Ue&&e.jsx(kn,{state:Ue,onClose:()=>qe(null)}),e.jsx(yn,{agent:h?g.find(t=>t.id===h)??null:null,content:pe,onClose:()=>re(null)}),me&&e.jsx(An,{action:"clear-subordinates",selectedAgentId:me.agentId,subordinateCount:me.count,onClose:()=>Ye(null),onClearHistory:()=>{}}),e.jsx(In,{agent:h?g.find(t=>t.id===h)??null:null,isOpen:Ie&&!!h,onClose:Ze}),e.jsx($t,{isOpen:J!==null,position:(J==null?void 0:J.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:Qt,onClose:()=>fe(null)}),e.jsx($t,{isOpen:f!==null,position:(f==null?void 0:f.position)??{x:0,y:0},worldPosition:{x:0,z:0},actions:en,onClose:()=>F(null)}),e.jsx(Sn,{isOpen:W!==null,title:ie("common:confirm.removeAgentTitle"),message:ie("common:confirm.removeAgentMessage",{name:(W==null?void 0:W.name)??""}),confirmLabel:ie("common:buttons.remove"),cancelLabel:ie("common:buttons.cancel"),variant:"danger",onConfirm:()=>{W&&x.removeAgentFromServer(W.agentId)},onClose:()=>Ae(null)})]})}export{ia as FlatView};