tide-commander 1.133.0 → 1.133.1
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.
- package/dist/assets/{BossLogsModal-DrdxKTb-.js → BossLogsModal-BaX_B_N5.js} +1 -1
- package/dist/assets/{BossSpawnModal-B2w4kFpi.js → BossSpawnModal-C00UowDz.js} +1 -1
- package/dist/assets/{ControlsModal-BWYKL25r.js → ControlsModal-Dt7oE27Q.js} +1 -1
- package/dist/assets/{DockerLogsModal-0fJudEU2.js → DockerLogsModal-lx6mKZ4i.js} +1 -1
- package/dist/assets/{EmbeddedEditor-BDzAm2JK.js → EmbeddedEditor-DIo_5FuD.js} +1 -1
- package/dist/assets/{GmailOAuthSetup-CR0SPH0J.js → GmailOAuthSetup-C2U2nxPP.js} +1 -1
- package/dist/assets/{GoogleOAuthSetup-BTDncXU3.js → GoogleOAuthSetup-Dc_Z6eoa.js} +1 -1
- package/dist/assets/{IframeModal-Csor52D5.js → IframeModal-Cee04vV5.js} +1 -1
- package/dist/assets/{IntegrationsPanel-qTRjzZ-I.js → IntegrationsPanel-Bmcek1lk.js} +2 -2
- package/dist/assets/{LogViewerModal-BiPg_NL7.js → LogViewerModal-D7rUAo21.js} +1 -1
- package/dist/assets/{MonitoringModal-BKjwjSqZ.js → MonitoringModal-CIVDImlk.js} +1 -1
- package/dist/assets/{PM2LogsModal-BAEeg_iW.js → PM2LogsModal-BL6J-qAf.js} +1 -1
- package/dist/assets/{RestoreArchivedAreaModal-Hm9Osmc4.js → RestoreArchivedAreaModal-BQ9_Ek9-.js} +1 -1
- package/dist/assets/{Scene2DCanvas-T-7D8dQ_.js → Scene2DCanvas-DgGN3yZr.js} +1 -1
- package/dist/assets/{SceneManager-C2rng0PA.js → SceneManager-DeF_SgXg.js} +1 -1
- package/dist/assets/{SkillsPanel-BD9RO30O.js → SkillsPanel-Dewf3uKl.js} +1 -1
- package/dist/assets/{SlackMultiInstanceSetup-CiK0r5fz.js → SlackMultiInstanceSetup-DWzkYONn.js} +1 -1
- package/dist/assets/{SpawnModal-Di4xD6Ue.js → SpawnModal-B0NGfZ2O.js} +1 -1
- package/dist/assets/{StatisticsModal-Dnl8segJ.js → StatisticsModal-ChDwmrkc.js} +1 -1
- package/dist/assets/{SubordinateAssignmentModal-CBIMPvXj.js → SubordinateAssignmentModal-DmazQXKC.js} +1 -1
- package/dist/assets/{TriggerManagerPanel-Bt5jFa9e.js → TriggerManagerPanel-DkIXFFWd.js} +1 -1
- package/dist/assets/{WorkflowEditorPanel-Dr7w30kC.js → WorkflowEditorPanel-CTqX4HYi.js} +1 -1
- package/dist/assets/{area-logos-CbqAEc5x.js → area-logos-BXaYMk1M.js} +1 -1
- package/dist/assets/{index-DHPrZrMN.js → index-BKf_8kzR.js} +1 -1
- package/dist/assets/{index-BajNxeMu.js → index-BPkrDTdP.js} +1 -1
- package/dist/assets/{index-D5ncPXgD.js → index-B_z6xFfT.js} +1 -1
- package/dist/assets/{index-DAjLIFPG.js → index-CFiTx9XT.js} +1 -1
- package/dist/assets/{index-Cah-uKuh.js → index-CI38phrA.js} +1 -1
- package/dist/assets/{index-B_EnZVF3.js → index-Cq-sPYkl.js} +3 -3
- package/dist/assets/{index-D-b-ReZX.js → index-DecYdDhH.js} +1 -1
- package/dist/assets/{index-C7vxRa_S.js → index-sSOmA52G.js} +1 -1
- package/dist/assets/{index-Cs3R3S9l.js → index-zRJvCXm1.js} +2 -2
- package/dist/assets/{main-D5m1NJ8q.js → main-D1dj_wn_.js} +5 -5
- package/dist/assets/main-rrlO1Py8.css +1 -0
- package/dist/assets/{web-Dh2cBvOj.js → web-BBfhX6Mx.js} +1 -1
- package/dist/assets/{web-CbFuYEMc.js → web-Br_mMcoY.js} +1 -1
- package/dist/assets/{web-C--hoJ1w.js → web-DG_dqGGb.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/main-BUUWICEe.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as l,b4 as Ue,b5 as Je,j as e,I as $,u as X,b6 as ns,ab as is,f as Ke,s as _,b7 as ms,b8 as gs,aZ as fs,b9 as xs,C as he,G as se,H as Y,h as je,i as ke,m as bs,ba as js,bb as ws,bc as ys,bd as vs,P as Ns,be as Se,a6 as ks,bf as os,bg as Ss,bh as Ve,bi as Cs,bj as As,bk as Ts,bl as _s,bm as Is,bn as Es,bo as Ps,aT as Ls,W as $s,S as Ne,bp as Ds,bq as Os,aV as Fs,br as ze,X as Ee,b1 as Rs,bs as Me,bt as Us}from"./main-D5m1NJ8q.js";import{g as zs,d as Ms,u as Bs}from"./area-logos-CbqAEc5x.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const He="deivid11/tide-commander",Vs=`https://api.github.com/repos/${He}/releases/latest`,Ks=`https://api.github.com/repos/${He}/releases?per_page=3`,Hs=3600*1e3,Ze="app_update_dismissed_version",Xe="1.133.0";function Ws(){var N,S;const[s,a]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Xe}),t=((S=(N=Ue)==null?void 0:N.getPlatform)==null?void 0:S.call(N))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(m=>parseInt(m,10)||0),d=(u,p)=>{const m=o(u),j=o(p),b=Math.max(m.length,j.length);for(let h=0;h<b;h++){const y=m[h]||0,P=j[h]||0;if(y>P)return 1;if(y<P)return-1}return 0},r=async u=>{var m,j;if(Ue&&Je&&((j=(m=Ue).isNativePlatform)==null?void 0:j.call(m))===!0){const b=await Je.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:b.data,status:b.status}}else{const b=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return b.ok?{data:await b.json(),status:b.status}:{data:null,status:b.status}}},c=l.useCallback(async(u=!1)=>{a(p=>({...p,isChecking:!0,error:null}));try{const[p,m]=await Promise.all([r(Vs),r(Ks)]);if(p.status!==200)throw new Error(`GitHub API error: ${p.status}`);const j=p.data,b=j.tag_name;let h=[];m.status===200&&m.data&&(h=m.data.map(w=>({version:w.tag_name,name:w.name,publishedAt:w.published_at,releaseUrl:w.html_url})));const y=localStorage.getItem(Ze);if(!u&&y===b)return a(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;if(!(d(b,Xe)>0))return a(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;const I=j.assets.find(w=>w.name.endsWith(".apk")&&w.content_type==="application/vnd.android.package-archive"),H={version:b,name:j.name,changelog:j.body,releaseUrl:j.html_url,apkUrl:(I==null?void 0:I.browser_download_url)||null,apkSize:(I==null?void 0:I.size)||null,publishedAt:j.published_at};return a(w=>({...w,isChecking:!1,updateAvailable:!0,updateInfo:H,recentReleases:h})),H}catch(p){const m=p instanceof Error?p.message:"Failed to check for updates";return a(j=>({...j,isChecking:!1,error:m})),null}},[]),x=l.useCallback(async()=>{var u,p,m;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(p=s.updateInfo)!=null&&p.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(m=s.updateInfo)!=null&&m.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),a(j=>({...j,error:null}))}catch(j){const b=j instanceof Error?j.message:"Failed to open download";a(h=>({...h,error:b}))}},[s.updateInfo,t]),n=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Ze,s.updateInfo.version),a(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),g=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${He}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),p=setInterval(()=>{c()},Hs);return()=>{clearTimeout(u),clearInterval(p)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:x,dismissUpdate:n,openReleasePage:g}}const ls="tide-toolbox-collapse";function qs(s,a){try{const t=localStorage.getItem(`${ls}-${s}`);if(t!==null)return t==="true"}catch{}return a}function Gs(s,a){try{localStorage.setItem(`${ls}-${s}`,String(a))}catch{}}function G({title:s,storageKey:a,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,x]=l.useState(()=>a?qs(a,t):t),n=()=>{const N=!c;x(N),a&&Gs(a,N)},g=o||c;return e.jsxs("div",{className:`collapsible-section ${g?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:n,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[r,e.jsx("span",{className:"collapsible-arrow",children:e.jsx($,{name:g?"caret-down":"caret-right",size:10})})]})]}),g&&e.jsx("div",{className:"collapsible-content",children:d})]})}function Ys({area:s,isSelected:a,onClick:t,onDelete:o}){const{t:d}=X(["config","common"]),r=s.assignedAgentIds.length,c=s.type==="rectangle"?d("config:areas.rect"):d("config:areas.circle");return e.jsxs("div",{className:`area-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"area-color-dot",style:{backgroundColor:s.color}}),e.jsxs("div",{className:"area-info",children:[e.jsx("div",{className:"area-name",children:s.name}),e.jsxs("div",{className:"area-meta",children:[c," ",r>0&&`• ${r} ${r>1?d("common:labels.agents").toLowerCase():d("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:o,title:d("config:areas.deleteArea"),children:"×"})]})}function Js({building:s,isSelected:a,onClick:t,onEdit:o}){var x;const{t:d}=X(["config"]),r=((x=s.pm2Status)==null?void 0:x.ports)||[],c=(n,g)=>{n.stopPropagation(),window.open(`http://${window.location.hostname}:${g}`,"_blank")};return e.jsxs("div",{className:`building-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:ns[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx($,{name:is(s.type),size:16})}),e.jsxs("div",{className:"building-info",children:[e.jsx("div",{className:"building-name",children:s.name}),e.jsxs("div",{className:"building-meta",children:[s.type,r.length>0&&e.jsx("span",{className:"building-ports",children:r.map(n=>e.jsxs("a",{href:`http://${window.location.hostname}:${n}`,className:"building-port-link",onClick:g=>c(g,n),title:`Open :${n}`,children:[":",n]},n))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:n=>{n.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx($,{name:"gear",size:14})})]})}function Zs({building:s,onClose:a,onOpenModal:t}){var g,N,S,u,p,m,j,b;const{t:o}=X(["config","common"]),{buildingLogs:d}=Ke(),r=_.getBuildingLogs(s.id),c=ms[s.style||"server-rack"],x=h=>{_.sendBuildingCommand(s.id,h)},n=h=>{window.open(h,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx($,{name:is(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:ns[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:a,children:"×"})]}),e.jsx("div",{className:"building-editor-section",children:e.jsxs("div",{className:"building-editor-info-grid",children:[e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("common:labels.type")}),e.jsx("span",{className:"building-editor-info-value",children:s.type})]}),e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:c.label})]}),s.cwd&&e.jsxs("div",{className:"building-editor-info-item building-editor-info-wide",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.directory")}),e.jsx("span",{className:"building-editor-info-value building-editor-cwd",title:s.cwd,children:s.cwd.split("/").pop()||s.cwd})]})]})}),s.type==="server"&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>x("start"),disabled:!((g=s.commands)!=null&&g.start)||s.status==="running",title:((N=s.commands)==null?void 0:N.start)||o("config:buildings.noStartCommand"),children:[e.jsx($,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>x("stop"),disabled:!((S=s.commands)!=null&&S.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx($,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>x("restart"),disabled:!((p=s.commands)!=null&&p.restart),title:((m=s.commands)==null?void 0:m.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx($,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>x("healthCheck"),disabled:!((j=s.commands)!=null&&j.healthCheck),title:((b=s.commands)==null?void 0:b.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx($,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((h,y)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>n(h.url),title:h.url,children:[e.jsx($,{name:"link",size:12})," ",h.label||h.url]},y))})]}),r.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[o("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>_.clearBuildingLogs(s.id),title:o("common:buttons.clear"),children:o("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:r.slice(-5).map((h,y)=>e.jsx("div",{className:"building-editor-log-entry",children:h},y))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx($,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const Xs=[{key:"center",labelKey:"posCenter"},{key:"top-left",labelKey:"posTopLeft"},{key:"top-right",labelKey:"posTopRight"},{key:"bottom-left",labelKey:"posBottomLeft"},{key:"bottom-right",labelKey:"posBottomRight"}];function Qs({area:s,onClose:a,onOpenFolder:t}){var te;const{t:o}=X(["config","common"]),[d,r]=l.useState(s.name),[c,x]=l.useState(s.prompt||""),[n,g]=l.useState(!1),[N,S]=l.useState(""),[u,p]=l.useState(!1),m=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{x(s.prompt||"")},[s.id,s.prompt]);const j=k=>{const O=k.target.value;r(O),_.updateArea(s.id,{name:O})},b=k=>{_.updateArea(s.id,{color:k})},h=k=>{const O=k.target.value;x(O),_.updateArea(s.id,{prompt:O})},y=()=>{N.trim()&&(_.addDirectoryToArea(s.id,N.trim()),S(""),g(!1))},P=(k,O)=>{O.stopPropagation(),_.removeDirectoryFromArea(s.id,k)},I=()=>{_.bringAreaToFront(s.id)},H=()=>{_.sendAreaToBack(s.id)},w=l.useCallback(()=>{let k=2,O=2;s.type==="rectangle"&&s.width&&s.height?(k=s.width,O=s.height):s.type==="circle"&&s.radius&&(k=s.radius*1.414,O=s.radius*1.414);const V=Math.min(k,O)*.4;return{width:Math.round(V*10)/10,height:Math.round(V*10)/10}},[s.type,s.width,s.height,s.radius]),z=async k=>{var V;const O=(V=k.target.files)==null?void 0:V[0];if(O){p(!0);try{const v=await Bs(s.id,O),D=w();_.updateArea(s.id,{logo:{filename:v.filename,position:"center",width:D.width,height:D.height,keepAspectRatio:!0,opacity:.8}})}catch(v){console.error("Failed to upload logo:",v)}finally{p(!1),m.current&&(m.current.value="")}}},B=async()=>{try{await Ms(s.id),_.updateArea(s.id,{logo:void 0})}catch(k){console.error("Failed to remove logo:",k)}},q=k=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,position:k}})},C=k=>{if(!s.logo)return;const O=parseFloat(k.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const V=s.logo.height/s.logo.width;_.updateArea(s.id,{logo:{...s.logo,width:O,height:Math.round(O*V*10)/10}})}else _.updateArea(s.id,{logo:{...s.logo,width:O}})},R=k=>{if(!s.logo)return;const O=parseFloat(k.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const V=s.logo.width/s.logo.height;_.updateArea(s.id,{logo:{...s.logo,height:O,width:Math.round(O*V*10)/10}})}else _.updateArea(s.id,{logo:{...s.logo,height:O}})},K=()=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},W=k=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(k.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:o("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:a,children:"×"})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:d,onChange:j,placeholder:o("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:gs.map(k=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===k?"selected":""}`,style:{backgroundColor:k},onClick:()=>b(k),"aria-label":`Set area color ${k}`,"aria-pressed":s.color===k,title:k},k))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:I,title:o("config:areas.bringToFront"),children:[e.jsx($,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:H,title:o("config:areas.sendToBack"),children:[e.jsx($,{name:"arrow-down",size:12})," ",o("config:areas.back")]})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(te=s.logo)!=null&&te.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:zs(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:B,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var k;return(k=m.current)==null?void 0:k.click()},disabled:u,children:u?"...":e.jsx($,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Xs.map(({key:k,labelKey:O})=>{var V;return e.jsx("button",{className:`area-logo-pos-btn ${((V=s.logo)==null?void 0:V.position)===k?"active":""}`,onClick:()=>q(k),children:o(`config:areas.${O}`)},k)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:C,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:R,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:o("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:K}),o("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoOpacity")}),e.jsxs("div",{className:"area-logo-opacity-row",children:[e.jsx("input",{type:"range",min:0,max:1,step:.05,value:s.logo.opacity??.8,onChange:W,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var k;return(k=m.current)==null?void 0:k.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:m,type:"file",accept:"image/*",style:{display:"none"},onChange:z})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(k=>e.jsxs("div",{className:"area-folder-item",title:k,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx($,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:k.split("/").pop()||k}),e.jsx("button",{className:"area-folder-remove",onClick:O=>P(k,O),title:o("config:areas.removeFolder"),children:"×"})]},k)),n?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(fs,{value:N,onChange:S,onSubmit:y,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:y,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>g(!0),children:o("config:areas.addFolder")})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:c,onChange:h,placeholder:o("config:areas.promptPlaceholder","System prompt for agents in this area..."),rows:4,style:{resize:"vertical",fontFamily:"monospace",fontSize:12}}),e.jsx("div",{style:{fontSize:11,color:"var(--text-secondary)",marginTop:4},children:o("config:areas.promptHint","This prompt is injected into agents assigned to this area. Takes effect on next context refresh.")})]}),s.assignedAgentIds.length>0&&e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:o("config:areas.rightClickUnassign")})]})]})}function et(){const{t:s}=X(["config","common"]),a=xs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,x]=l.useState({name:"",key:"",value:"",description:""}),[n,g]=l.useState(null),N=()=>{o(!0),r(null),x({name:"",key:"",value:"",description:""})},S=h=>{r(h.id),o(!1),x({name:h.name,key:h.key,value:h.value,description:h.description||""})},u=()=>{o(!1),r(null),x({name:"",key:"",value:"",description:""})},p=()=>{!c.name.trim()||!c.key.trim()||(d?_.updateSecret(d,{name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}):_.createSecret({name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}),u())},m=h=>{g(h)},j=()=>{n&&(_.deleteSecret(n),d===n&&u())},b=h=>{navigator.clipboard.writeText(`{{${h}}}`)};return e.jsxs("div",{className:"secrets-section",children:[e.jsx("div",{className:"secrets-description",children:s("config:secrets.description",{placeholder:"{{KEY}}"})}),e.jsx("div",{className:"secrets-list",children:a.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):a.map(h=>e.jsxs("div",{className:`secret-item ${d===h.id?"editing":""}`,children:[e.jsxs("div",{className:"secret-item-header",children:[e.jsxs("div",{className:"secret-item-info",children:[e.jsx("span",{className:"secret-item-name",children:h.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>b(h.key),title:s("config:secrets.copyPlaceholder"),children:`{{${h.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>S(h),title:s("common:buttons.edit"),children:e.jsx($,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>m(h.id),title:s("common:buttons.delete"),children:"×"})]})]}),h.description&&e.jsx("div",{className:"secret-item-description",children:h.description})]},h.id))}),(t||d)&&e.jsxs("div",{className:"secret-form",children:[e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.name")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.namePlaceholder"),value:c.name,onChange:h=>x({...c,name:h.target.value}),autoFocus:!0})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:"Key"}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.keyPlaceholder"),value:c.key,onChange:h=>x({...c,key:h.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${c.key||"KEY"}}}`})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("config:secrets.secretValue")}),e.jsx("input",{type:"password",className:"secret-form-input",placeholder:s("config:secrets.valuePlaceholder"),value:c.value,onChange:h=>x({...c,value:h.target.value})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.description")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.descriptionPlaceholder"),value:c.description,onChange:h=>x({...c,description:h.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:u,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:p,disabled:!c.name.trim()||!c.key.trim(),children:s(d?"config:secrets.update":"common:buttons.add")})]})]}),!t&&!d&&e.jsx("button",{className:"secrets-add-btn",onClick:N,children:s("config:secrets.addSecret")}),e.jsx(he,{isOpen:n!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:j,onClose:()=>g(null)})]})}async function st(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch system prompt: ${a.statusText}`);return(await a.json()).prompt||""}async function tt(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({prompt:s})});if(!t.ok)throw new Error(`Failed to update system prompt: ${t.statusText}`)}async function at(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/prompt`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to clear system prompt: ${a.statusText}`)}async function nt(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch echo prompt setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function it(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function ot(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch codex binary path: ${a.statusText}`);return(await a.json()).path||""}async function lt(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function ct(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch tmux mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function rt(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function dt(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch interactive mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function ut(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function pt(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch backup status: ${a.statusText}`);return a.json()}async function ht(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||`Failed to update backup setting: ${t.statusText}`)}return t.json()}function mt({checked:s,onChange:a,disabled:t}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:t,onChange:o=>a(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function gt(){const{t:s}=X(["config","common"]),[a,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[x,n]=l.useState(!1),[g,N]=l.useState(!1),[S,u]=l.useState(null),[p,m]=l.useState(null),[j,b]=l.useState(null),[h,y]=l.useState(null),[P,I]=l.useState(!1),[H,w]=l.useState(null);l.useEffect(()=>{je(ke("/api/config/categories")).then(v=>v.json()).then(v=>{const D=Array.isArray(v)?v:[];t(D),d(new Set(D.map(F=>F.id)))}).catch(v=>console.error("Failed to fetch config categories:",v))},[]),l.useEffect(()=>{pt().then(y).catch(v=>{console.error("Failed to fetch backup status:",v),w(v.message||"Failed to fetch backup status")})},[]);const z=async v=>{if(!P){I(!0),w(null);try{const D=await ht(v);y(D)}catch(D){w(D.message||"Failed to update backup setting")}finally{I(!1)}}},B=v=>{d(D=>{const F=new Set(D);return F.has(v)?F.delete(v):F.add(v),F})},q=v=>{c(D=>{const F=new Set(D);return F.has(v)?F.delete(v):F.add(v),F})},C=()=>d(new Set(a.map(v=>v.id))),R=()=>d(new Set),K=()=>{p&&c(new Set(p.categories.map(v=>v.id)))},W=()=>c(new Set),te=async()=>{var v;if(o.size!==0){n(!0),b(null);try{const D=Array.from(o).join(","),F=await je(ke(`/api/config/export?categories=${D}`));if(!F.ok)throw new Error("Export failed");const Q=await F.blob(),ee=window.URL.createObjectURL(Q),T=document.createElement("a");T.href=ee;const A=F.headers.get("Content-Disposition"),J=((v=A==null?void 0:A.match(/filename="(.+)"/))==null?void 0:v[1])||"tide-commander-config.zip";T.download=J,document.body.appendChild(T),T.click(),document.body.removeChild(T),window.URL.revokeObjectURL(ee),b({type:"success",text:s("config:data.exportSuccess")})}catch(D){b({type:"error",text:D.message||"Export failed"})}finally{n(!1)}}},k=async v=>{var F;const D=(F=v.target.files)==null?void 0:F[0];if(D){u(D),b(null),m(null),c(new Set);try{const Q=await je(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await D.arrayBuffer()});if(!Q.ok){const A=await Q.json();throw new Error(A.error||"Failed to preview config file")}const ee=await Q.json(),T=Array.isArray(ee.categories)?ee.categories:[];m({...ee,categories:T}),c(new Set(T.map(A=>A.id)))}catch(Q){b({type:"error",text:Q.message||"Failed to read config file"}),u(null)}}},O=async()=>{if(!(!S||r.size===0)){N(!0),b(null);try{const v=Array.from(r).join(","),D=await je(ke(`/api/config/import?categories=${v}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await S.arrayBuffer()}),F=await D.json();if(!D.ok)throw new Error(F.error||"Import failed");b({type:"success",text:F.message||s("config:data.importSuccess")}),u(null),m(null),c(new Set)}catch(v){b({type:"error",text:v.message||"Import failed"})}finally{N(!1)}}},V=()=>{u(null),m(null),c(new Set),b(null)};return e.jsxs("div",{className:"data-section",children:[j&&e.jsx("div",{className:`data-message data-message-${j.type}`,children:j.text}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:"Hourly Backups"}),e.jsx(mt,{checked:!!(h!=null&&h.enabled),disabled:P||!h,onChange:z})]}),e.jsxs("div",{className:"data-backup-info",children:[h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:h.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!h.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:h.scriptPath})]}),h.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(h.lastRunAt).toLocaleString(),h.lastRunOk===!0&&" — ok",h.lastRunOk===!1&&h.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",h.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),H&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:H})]})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:s("config:data.exportData")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:C,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:R,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:a.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(v.id),onChange:()=>B(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name})]},v.id))}),e.jsx("button",{className:"data-action-btn export",onClick:te,disabled:x||o.size===0,children:x?s("config:data.exporting"):s("config:data.exportCount",{count:o.size})})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsx("div",{className:"data-subsection-header",children:e.jsx("span",{className:"data-subsection-title",children:s("config:data.importData")})}),S?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:S.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(p.exportedAt).toLocaleDateString()]})]}),e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-subtitle",children:s("config:data.selectToImport")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:K,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:W,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:p.categories.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(v.id),onChange:()=>q(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name}),v.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",v.fileCount," ",s("config:data.files"),")"]})]},v.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:V,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:O,disabled:g||r.size===0,children:g?s("config:data.importing"):s("config:data.importCount",{count:r.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:k,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function ft(){const s=await je(`${Y()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function xt(s,a){const t=new AbortController;return(async()=>{try{const o=await fetch(bs(`${Y()}/api/system/self-update`),{method:"POST",signal:t.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const x=await o.text().catch(()=>"");let n=null;try{n=JSON.parse(x)}catch{}const g=n&&typeof n=="object"&&"error"in n&&typeof n.error=="string"?n.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:g}),a(new Error(g));return}const d=o.body.getReader(),r=new TextDecoder("utf-8");let c="";for(;;){const{value:x,done:n}=await d.read();if(n)break;c+=r.decode(x,{stream:!0});let g=c.indexOf(`
|
|
1
|
+
import{r as l,b4 as Ue,b5 as Je,j as e,I as $,u as X,b6 as ns,ab as is,f as Ke,s as _,b7 as ms,b8 as gs,aZ as fs,b9 as xs,C as he,G as se,H as Y,h as je,i as ke,m as bs,ba as js,bb as ws,bc as ys,bd as vs,P as Ns,be as Se,a6 as ks,bf as os,bg as Ss,bh as Ve,bi as Cs,bj as As,bk as Ts,bl as _s,bm as Is,bn as Es,bo as Ps,aT as Ls,W as $s,S as Ne,bp as Ds,bq as Os,aV as Fs,br as ze,X as Ee,b1 as Rs,bs as Me,bt as Us}from"./main-D1dj_wn_.js";import{g as zs,d as Ms,u as Bs}from"./area-logos-BXaYMk1M.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const He="deivid11/tide-commander",Vs=`https://api.github.com/repos/${He}/releases/latest`,Ks=`https://api.github.com/repos/${He}/releases?per_page=3`,Hs=3600*1e3,Ze="app_update_dismissed_version",Xe="1.133.1";function Ws(){var N,S;const[s,a]=l.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Xe}),t=((S=(N=Ue)==null?void 0:N.getPlatform)==null?void 0:S.call(N))==="android"||!1,o=u=>u.replace(/^v/,"").split(".").map(m=>parseInt(m,10)||0),d=(u,p)=>{const m=o(u),j=o(p),b=Math.max(m.length,j.length);for(let h=0;h<b;h++){const y=m[h]||0,P=j[h]||0;if(y>P)return 1;if(y<P)return-1}return 0},r=async u=>{var m,j;if(Ue&&Je&&((j=(m=Ue).isNativePlatform)==null?void 0:j.call(m))===!0){const b=await Je.get({url:u,headers:{Accept:"application/vnd.github.v3+json"}});return{data:b.data,status:b.status}}else{const b=await fetch(u,{headers:{Accept:"application/vnd.github.v3+json"}});return b.ok?{data:await b.json(),status:b.status}:{data:null,status:b.status}}},c=l.useCallback(async(u=!1)=>{a(p=>({...p,isChecking:!0,error:null}));try{const[p,m]=await Promise.all([r(Vs),r(Ks)]);if(p.status!==200)throw new Error(`GitHub API error: ${p.status}`);const j=p.data,b=j.tag_name;let h=[];m.status===200&&m.data&&(h=m.data.map(w=>({version:w.tag_name,name:w.name,publishedAt:w.published_at,releaseUrl:w.html_url})));const y=localStorage.getItem(Ze);if(!u&&y===b)return a(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;if(!(d(b,Xe)>0))return a(w=>({...w,isChecking:!1,updateAvailable:!1,recentReleases:h})),null;const I=j.assets.find(w=>w.name.endsWith(".apk")&&w.content_type==="application/vnd.android.package-archive"),H={version:b,name:j.name,changelog:j.body,releaseUrl:j.html_url,apkUrl:(I==null?void 0:I.browser_download_url)||null,apkSize:(I==null?void 0:I.size)||null,publishedAt:j.published_at};return a(w=>({...w,isChecking:!1,updateAvailable:!0,updateInfo:H,recentReleases:h})),H}catch(p){const m=p instanceof Error?p.message:"Failed to check for updates";return a(j=>({...j,isChecking:!1,error:m})),null}},[]),x=l.useCallback(async()=>{var u,p,m;if(!((u=s.updateInfo)!=null&&u.apkUrl)){(p=s.updateInfo)!=null&&p.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(m=s.updateInfo)!=null&&m.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),a(j=>({...j,error:null}))}catch(j){const b=j instanceof Error?j.message:"Failed to open download";a(h=>({...h,error:b}))}},[s.updateInfo,t]),n=l.useCallback(()=>{s.updateInfo&&localStorage.setItem(Ze,s.updateInfo.version),a(u=>({...u,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),g=l.useCallback(()=>{var u;(u=s.updateInfo)!=null&&u.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${He}/releases`,"_blank")},[s.updateInfo]);return l.useEffect(()=>{if(!t)return;const u=setTimeout(()=>{c()},5e3),p=setInterval(()=>{c()},Hs);return()=>{clearTimeout(u),clearInterval(p)}},[t,c]),{...s,isAndroid:t,checkForUpdate:c,downloadAndInstall:x,dismissUpdate:n,openReleasePage:g}}const ls="tide-toolbox-collapse";function qs(s,a){try{const t=localStorage.getItem(`${ls}-${s}`);if(t!==null)return t==="true"}catch{}return a}function Gs(s,a){try{localStorage.setItem(`${ls}-${s}`,String(a))}catch{}}function G({title:s,storageKey:a,defaultOpen:t=!1,forceOpen:o=!1,children:d,headerExtra:r}){const[c,x]=l.useState(()=>a?qs(a,t):t),n=()=>{const N=!c;x(N),a&&Gs(a,N)},g=o||c;return e.jsxs("div",{className:`collapsible-section ${g?"open":"collapsed"}`,children:[e.jsxs("button",{className:"collapsible-header",onClick:n,children:[e.jsx("span",{className:"collapsible-title",children:s}),e.jsxs("span",{className:"collapsible-header-right",children:[r,e.jsx("span",{className:"collapsible-arrow",children:e.jsx($,{name:g?"caret-down":"caret-right",size:10})})]})]}),g&&e.jsx("div",{className:"collapsible-content",children:d})]})}function Ys({area:s,isSelected:a,onClick:t,onDelete:o}){const{t:d}=X(["config","common"]),r=s.assignedAgentIds.length,c=s.type==="rectangle"?d("config:areas.rect"):d("config:areas.circle");return e.jsxs("div",{className:`area-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"area-color-dot",style:{backgroundColor:s.color}}),e.jsxs("div",{className:"area-info",children:[e.jsx("div",{className:"area-name",children:s.name}),e.jsxs("div",{className:"area-meta",children:[c," ",r>0&&`• ${r} ${r>1?d("common:labels.agents").toLowerCase():d("common:labels.agent").toLowerCase()}`]})]}),e.jsx("button",{className:"area-delete-btn",onClick:o,title:d("config:areas.deleteArea"),children:"×"})]})}function Js({building:s,isSelected:a,onClick:t,onEdit:o}){var x;const{t:d}=X(["config"]),r=((x=s.pm2Status)==null?void 0:x.ports)||[],c=(n,g)=>{n.stopPropagation(),window.open(`http://${window.location.hostname}:${g}`,"_blank")};return e.jsxs("div",{className:`building-item ${a?"selected":""}`,onClick:t,children:[e.jsx("div",{className:"building-status-dot",style:{backgroundColor:ns[s.status]},title:s.status}),e.jsx("div",{className:"building-icon",children:e.jsx($,{name:is(s.type),size:16})}),e.jsxs("div",{className:"building-info",children:[e.jsx("div",{className:"building-name",children:s.name}),e.jsxs("div",{className:"building-meta",children:[s.type,r.length>0&&e.jsx("span",{className:"building-ports",children:r.map(n=>e.jsxs("a",{href:`http://${window.location.hostname}:${n}`,className:"building-port-link",onClick:g=>c(g,n),title:`Open :${n}`,children:[":",n]},n))})]})]}),e.jsx("button",{className:"building-edit-btn",onClick:n=>{n.stopPropagation(),o()},title:d("config:buildings.editBuilding"),children:e.jsx($,{name:"gear",size:14})})]})}function Zs({building:s,onClose:a,onOpenModal:t}){var g,N,S,u,p,m,j,b;const{t:o}=X(["config","common"]),{buildingLogs:d}=Ke(),r=_.getBuildingLogs(s.id),c=ms[s.style||"server-rack"],x=h=>{_.sendBuildingCommand(s.id,h)},n=h=>{window.open(h,"_blank")};return e.jsxs("div",{className:"building-editor",children:[e.jsxs("div",{className:"building-editor-header",children:[e.jsxs("div",{className:"building-editor-title-row",children:[e.jsx("span",{className:"building-editor-icon",children:e.jsx($,{name:is(s.type),size:18})}),e.jsx("span",{className:"building-editor-title",children:s.name}),e.jsx("span",{className:"building-editor-status",style:{backgroundColor:ns[s.status]},children:s.status})]}),e.jsx("button",{className:"building-editor-close",onClick:a,children:"×"})]}),e.jsx("div",{className:"building-editor-section",children:e.jsxs("div",{className:"building-editor-info-grid",children:[e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("common:labels.type")}),e.jsx("span",{className:"building-editor-info-value",children:s.type})]}),e.jsxs("div",{className:"building-editor-info-item",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.style")}),e.jsx("span",{className:"building-editor-info-value",children:c.label})]}),s.cwd&&e.jsxs("div",{className:"building-editor-info-item building-editor-info-wide",children:[e.jsx("span",{className:"building-editor-info-label",children:o("config:buildings.directory")}),e.jsx("span",{className:"building-editor-info-value building-editor-cwd",title:s.cwd,children:s.cwd.split("/").pop()||s.cwd})]})]})}),s.type==="server"&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.actions")}),e.jsxs("div",{className:"building-editor-actions",children:[e.jsxs("button",{className:"building-editor-action-btn start",onClick:()=>x("start"),disabled:!((g=s.commands)!=null&&g.start)||s.status==="running",title:((N=s.commands)==null?void 0:N.start)||o("config:buildings.noStartCommand"),children:[e.jsx($,{name:"play",size:12})," ",o("common:buttons.start")]}),e.jsxs("button",{className:"building-editor-action-btn stop",onClick:()=>x("stop"),disabled:!((S=s.commands)!=null&&S.stop)||s.status==="stopped",title:((u=s.commands)==null?void 0:u.stop)||o("config:buildings.noStopCommand"),children:[e.jsx($,{name:"stop",size:12,weight:"fill"})," ",o("common:buttons.stop")]}),e.jsxs("button",{className:"building-editor-action-btn restart",onClick:()=>x("restart"),disabled:!((p=s.commands)!=null&&p.restart),title:((m=s.commands)==null?void 0:m.restart)||o("config:buildings.noRestartCommand"),children:[e.jsx($,{name:"refresh",size:12})," ",o("common:buttons.retry")]}),e.jsxs("button",{className:"building-editor-action-btn health",onClick:()=>x("healthCheck"),disabled:!((j=s.commands)!=null&&j.healthCheck),title:((b=s.commands)==null?void 0:b.healthCheck)||o("config:buildings.noHealthCheck"),children:[e.jsx($,{name:"heart",size:12})," Health"]})]})]}),s.urls&&s.urls.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsx("div",{className:"building-editor-section-title",children:o("config:buildings.links")}),e.jsx("div",{className:"building-editor-links",children:s.urls.map((h,y)=>e.jsxs("button",{className:"building-editor-link",onClick:()=>n(h.url),title:h.url,children:[e.jsx($,{name:"link",size:12})," ",h.label||h.url]},y))})]}),r.length>0&&e.jsxs("div",{className:"building-editor-section",children:[e.jsxs("div",{className:"building-editor-section-title",children:[o("config:buildings.recentLogs"),e.jsx("button",{className:"building-editor-clear-logs",onClick:()=>_.clearBuildingLogs(s.id),title:o("common:buttons.clear"),children:o("common:buttons.clear")})]}),e.jsx("div",{className:"building-editor-logs",children:r.slice(-5).map((h,y)=>e.jsx("div",{className:"building-editor-log-entry",children:h},y))})]}),e.jsx("div",{className:"building-editor-footer",children:e.jsxs("button",{className:"building-editor-edit-btn",onClick:t,children:[e.jsx($,{name:"gear",size:12})," ",o("config:buildings.fullSettings")]})})]})}const Xs=[{key:"center",labelKey:"posCenter"},{key:"top-left",labelKey:"posTopLeft"},{key:"top-right",labelKey:"posTopRight"},{key:"bottom-left",labelKey:"posBottomLeft"},{key:"bottom-right",labelKey:"posBottomRight"}];function Qs({area:s,onClose:a,onOpenFolder:t}){var te;const{t:o}=X(["config","common"]),[d,r]=l.useState(s.name),[c,x]=l.useState(s.prompt||""),[n,g]=l.useState(!1),[N,S]=l.useState(""),[u,p]=l.useState(!1),m=l.useRef(null);l.useEffect(()=>{r(s.name)},[s.id,s.name]),l.useEffect(()=>{x(s.prompt||"")},[s.id,s.prompt]);const j=k=>{const O=k.target.value;r(O),_.updateArea(s.id,{name:O})},b=k=>{_.updateArea(s.id,{color:k})},h=k=>{const O=k.target.value;x(O),_.updateArea(s.id,{prompt:O})},y=()=>{N.trim()&&(_.addDirectoryToArea(s.id,N.trim()),S(""),g(!1))},P=(k,O)=>{O.stopPropagation(),_.removeDirectoryFromArea(s.id,k)},I=()=>{_.bringAreaToFront(s.id)},H=()=>{_.sendAreaToBack(s.id)},w=l.useCallback(()=>{let k=2,O=2;s.type==="rectangle"&&s.width&&s.height?(k=s.width,O=s.height):s.type==="circle"&&s.radius&&(k=s.radius*1.414,O=s.radius*1.414);const V=Math.min(k,O)*.4;return{width:Math.round(V*10)/10,height:Math.round(V*10)/10}},[s.type,s.width,s.height,s.radius]),z=async k=>{var V;const O=(V=k.target.files)==null?void 0:V[0];if(O){p(!0);try{const v=await Bs(s.id,O),D=w();_.updateArea(s.id,{logo:{filename:v.filename,position:"center",width:D.width,height:D.height,keepAspectRatio:!0,opacity:.8}})}catch(v){console.error("Failed to upload logo:",v)}finally{p(!1),m.current&&(m.current.value="")}}},B=async()=>{try{await Ms(s.id),_.updateArea(s.id,{logo:void 0})}catch(k){console.error("Failed to remove logo:",k)}},q=k=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,position:k}})},C=k=>{if(!s.logo)return;const O=parseFloat(k.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.width>0){const V=s.logo.height/s.logo.width;_.updateArea(s.id,{logo:{...s.logo,width:O,height:Math.round(O*V*10)/10}})}else _.updateArea(s.id,{logo:{...s.logo,width:O}})},R=k=>{if(!s.logo)return;const O=parseFloat(k.target.value)||.1;if(s.logo.keepAspectRatio&&s.logo.height>0){const V=s.logo.width/s.logo.height;_.updateArea(s.id,{logo:{...s.logo,height:O,width:Math.round(O*V*10)/10}})}else _.updateArea(s.id,{logo:{...s.logo,height:O}})},K=()=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,keepAspectRatio:!s.logo.keepAspectRatio}})},W=k=>{s.logo&&_.updateArea(s.id,{logo:{...s.logo,opacity:parseFloat(k.target.value)}})};return e.jsxs("div",{className:"area-editor",children:[e.jsxs("div",{className:"area-editor-header",children:[e.jsx("span",{className:"area-editor-title",children:o("config:areas.editArea")}),e.jsx("button",{className:"area-editor-close",onClick:a,children:"×"})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("common:labels.name")}),e.jsx("input",{type:"text",className:"area-editor-input",value:d,onChange:j,placeholder:o("config:areas.areaName")})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.color")}),e.jsx("div",{className:"color-picker-row",children:gs.map(k=>e.jsx("button",{type:"button",className:`color-swatch ${s.color===k?"selected":""}`,style:{backgroundColor:k},onClick:()=>b(k),"aria-label":`Set area color ${k}`,"aria-pressed":s.color===k,title:k},k))})]}),e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.layer")}),e.jsxs("div",{className:"area-layer-buttons",children:[e.jsxs("button",{className:"area-layer-btn",onClick:I,title:o("config:areas.bringToFront"),children:[e.jsx($,{name:"arrow-up",size:12})," ",o("config:areas.front")]}),e.jsxs("button",{className:"area-layer-btn",onClick:H,title:o("config:areas.sendToBack"),children:[e.jsx($,{name:"arrow-down",size:12})," ",o("config:areas.back")]})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.logo")}),e.jsxs("div",{className:"area-logo-section",children:[(te=s.logo)!=null&&te.filename?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"area-logo-preview",children:[e.jsx("img",{src:zs(s.logo.filename),alt:"Logo",className:"area-logo-thumbnail"}),e.jsx("button",{className:"area-logo-remove-btn",onClick:B,children:o("config:areas.removeLogo")}),e.jsx("button",{className:"area-logo-replace-btn",onClick:()=>{var k;return(k=m.current)==null?void 0:k.click()},disabled:u,children:u?"...":e.jsx($,{name:"refresh",size:12})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoPosition")}),e.jsx("div",{className:"area-logo-position-row",children:Xs.map(({key:k,labelKey:O})=>{var V;return e.jsx("button",{className:`area-logo-pos-btn ${((V=s.logo)==null?void 0:V.position)===k?"active":""}`,onClick:()=>q(k),children:o(`config:areas.${O}`)},k)})})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoSize")}),e.jsxs("div",{className:"area-logo-size-row",children:[e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoWidth")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.width,onChange:C,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-size-field",children:[e.jsx("span",{children:o("config:areas.logoHeight")}),e.jsx("input",{type:"number",className:"area-logo-size-input",value:s.logo.height,onChange:R,min:.1,step:.1})]}),e.jsxs("label",{className:"area-logo-aspect-label",title:o("config:areas.keepAspectRatio"),children:[e.jsx("input",{type:"checkbox",checked:s.logo.keepAspectRatio,onChange:K}),o("config:areas.keepAspectRatio")]})]})]}),e.jsxs("div",{className:"area-logo-config-row",children:[e.jsx("span",{className:"area-logo-config-label",children:o("config:areas.logoOpacity")}),e.jsxs("div",{className:"area-logo-opacity-row",children:[e.jsx("input",{type:"range",min:0,max:1,step:.05,value:s.logo.opacity??.8,onChange:W,className:"area-logo-opacity-slider"}),e.jsxs("span",{className:"area-logo-opacity-value",children:[Math.round((s.logo.opacity??.8)*100),"%"]})]})]})]}):e.jsx("button",{className:"area-logo-upload-btn",onClick:()=>{var k;return(k=m.current)==null?void 0:k.click()},disabled:u,children:u?"...":o("config:areas.uploadLogo")}),e.jsx("input",{ref:m,type:"file",accept:"image/*",style:{display:"none"},onChange:z})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.folders",{count:s.directories.length})}),e.jsxs("div",{className:"area-folders-list",children:[s.directories.map(k=>e.jsxs("div",{className:"area-folder-item",title:k,children:[e.jsx("span",{className:"area-folder-icon clickable",onClick:()=>t==null?void 0:t(s.id),title:o("config:areas.openFolder"),children:e.jsx($,{name:"folder",size:14})}),e.jsx("span",{className:"area-folder-path",children:k.split("/").pop()||k}),e.jsx("button",{className:"area-folder-remove",onClick:O=>P(k,O),title:o("config:areas.removeFolder"),children:"×"})]},k)),n?e.jsxs("div",{className:"area-add-folder-inline",children:[e.jsx(fs,{value:N,onChange:S,onSubmit:y,placeholder:o("config:areas.folderPlaceholder"),className:"area-add-folder-input",directoriesOnly:!0,autoFocus:!0}),e.jsx("button",{className:"area-add-folder-confirm",onClick:y,children:"+"})]}):e.jsx("button",{className:"area-add-folder-btn",onClick:()=>g(!0),children:o("config:areas.addFolder")})]})]}),e.jsxs("div",{className:"area-editor-row",style:{flexDirection:"column",alignItems:"stretch"},children:[e.jsx("div",{className:"area-editor-label",style:{marginBottom:6},children:o("config:areas.prompt","Prompt")}),e.jsx("textarea",{className:"area-editor-input",value:c,onChange:h,placeholder:o("config:areas.promptPlaceholder","System prompt for agents in this area..."),rows:4,style:{resize:"vertical",fontFamily:"monospace",fontSize:12}}),e.jsx("div",{style:{fontSize:11,color:"var(--text-secondary)",marginTop:4},children:o("config:areas.promptHint","This prompt is injected into agents assigned to this area. Takes effect on next context refresh.")})]}),s.assignedAgentIds.length>0&&e.jsxs("div",{className:"area-editor-row",children:[e.jsx("div",{className:"area-editor-label",children:o("config:areas.assignedAgents",{count:s.assignedAgentIds.length})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:o("config:areas.rightClickUnassign")})]})]})}function et(){const{t:s}=X(["config","common"]),a=xs(),[t,o]=l.useState(!1),[d,r]=l.useState(null),[c,x]=l.useState({name:"",key:"",value:"",description:""}),[n,g]=l.useState(null),N=()=>{o(!0),r(null),x({name:"",key:"",value:"",description:""})},S=h=>{r(h.id),o(!1),x({name:h.name,key:h.key,value:h.value,description:h.description||""})},u=()=>{o(!1),r(null),x({name:"",key:"",value:"",description:""})},p=()=>{!c.name.trim()||!c.key.trim()||(d?_.updateSecret(d,{name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}):_.createSecret({name:c.name.trim(),key:c.key.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_"),value:c.value,description:c.description.trim()||void 0}),u())},m=h=>{g(h)},j=()=>{n&&(_.deleteSecret(n),d===n&&u())},b=h=>{navigator.clipboard.writeText(`{{${h}}}`)};return e.jsxs("div",{className:"secrets-section",children:[e.jsx("div",{className:"secrets-description",children:s("config:secrets.description",{placeholder:"{{KEY}}"})}),e.jsx("div",{className:"secrets-list",children:a.length===0&&!t?e.jsx("div",{className:"secrets-empty",children:s("config:secrets.noSecrets")}):a.map(h=>e.jsxs("div",{className:`secret-item ${d===h.id?"editing":""}`,children:[e.jsxs("div",{className:"secret-item-header",children:[e.jsxs("div",{className:"secret-item-info",children:[e.jsx("span",{className:"secret-item-name",children:h.name}),e.jsx("code",{className:"secret-item-key",onClick:()=>b(h.key),title:s("config:secrets.copyPlaceholder"),children:`{{${h.key}}}`})]}),e.jsxs("div",{className:"secret-item-actions",children:[e.jsx("button",{className:"secret-item-btn edit",onClick:()=>S(h),title:s("common:buttons.edit"),children:e.jsx($,{name:"edit",size:12})}),e.jsx("button",{className:"secret-item-btn delete",onClick:()=>m(h.id),title:s("common:buttons.delete"),children:"×"})]})]}),h.description&&e.jsx("div",{className:"secret-item-description",children:h.description})]},h.id))}),(t||d)&&e.jsxs("div",{className:"secret-form",children:[e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.name")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.namePlaceholder"),value:c.name,onChange:h=>x({...c,name:h.target.value}),autoFocus:!0})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:"Key"}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.keyPlaceholder"),value:c.key,onChange:h=>x({...c,key:h.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")})}),e.jsx("span",{className:"secret-form-hint",children:s("config:secrets.usedAs",{placeholder:`{{${c.key||"KEY"}}}`})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("config:secrets.secretValue")}),e.jsx("input",{type:"password",className:"secret-form-input",placeholder:s("config:secrets.valuePlaceholder"),value:c.value,onChange:h=>x({...c,value:h.target.value})})]}),e.jsxs("div",{className:"secret-form-row",children:[e.jsx("label",{className:"secret-form-label",children:s("common:labels.description")}),e.jsx("input",{type:"text",className:"secret-form-input",placeholder:s("config:secrets.descriptionPlaceholder"),value:c.description,onChange:h=>x({...c,description:h.target.value})})]}),e.jsxs("div",{className:"secret-form-actions",children:[e.jsx("button",{className:"secret-form-btn cancel",onClick:u,children:s("common:buttons.cancel")}),e.jsx("button",{className:"secret-form-btn save",onClick:p,disabled:!c.name.trim()||!c.key.trim(),children:s(d?"config:secrets.update":"common:buttons.add")})]})]}),!t&&!d&&e.jsx("button",{className:"secrets-add-btn",onClick:N,children:s("config:secrets.addSecret")}),e.jsx(he,{isOpen:n!==null,title:s("common:buttons.delete"),message:s("config:secrets.deleteConfirm"),confirmLabel:s("common:buttons.delete"),cancelLabel:s("common:buttons.cancel"),variant:"danger",onConfirm:j,onClose:()=>g(null)})]})}async function st(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch system prompt: ${a.statusText}`);return(await a.json()).prompt||""}async function tt(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({prompt:s})});if(!t.ok)throw new Error(`Failed to update system prompt: ${t.statusText}`)}async function at(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/prompt`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to clear system prompt: ${a.statusText}`)}async function nt(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/echo-prompt`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch echo prompt setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function it(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/echo-prompt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update echo prompt setting: ${t.statusText}`)}async function ot(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/codex-binary`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch codex binary path: ${a.statusText}`);return(await a.json()).path||""}async function lt(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/codex-binary`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({path:s})});if(!t.ok)throw new Error(`Failed to update codex binary path: ${t.statusText}`)}async function ct(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/tmux-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch tmux mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function rt(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/tmux-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update tmux mode setting: ${t.statusText}`)}async function dt(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/interactive-mode`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch interactive mode setting: ${a.statusText}`);return(await a.json()).enabled||!1}async function ut(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/interactive-mode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok)throw new Error(`Failed to update interactive mode setting: ${t.statusText}`)}async function pt(){const s=se(),a=await fetch(`${Y()}/api/agents/system-settings/backup`,{headers:{Authorization:`Bearer ${s}`}});if(!a.ok)throw new Error(`Failed to fetch backup status: ${a.statusText}`);return a.json()}async function ht(s){const a=se(),t=await fetch(`${Y()}/api/agents/system-settings/backup`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({enabled:s})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.error||`Failed to update backup setting: ${t.statusText}`)}return t.json()}function mt({checked:s,onChange:a,disabled:t}){return e.jsxs("label",{className:"config-toggle",children:[e.jsx("input",{type:"checkbox",className:"config-toggle-input",checked:s,disabled:t,onChange:o=>a(o.target.checked)}),e.jsx("span",{className:"config-toggle-track",children:e.jsx("span",{className:"config-toggle-thumb"})})]})}function gt(){const{t:s}=X(["config","common"]),[a,t]=l.useState([]),[o,d]=l.useState(new Set),[r,c]=l.useState(new Set),[x,n]=l.useState(!1),[g,N]=l.useState(!1),[S,u]=l.useState(null),[p,m]=l.useState(null),[j,b]=l.useState(null),[h,y]=l.useState(null),[P,I]=l.useState(!1),[H,w]=l.useState(null);l.useEffect(()=>{je(ke("/api/config/categories")).then(v=>v.json()).then(v=>{const D=Array.isArray(v)?v:[];t(D),d(new Set(D.map(F=>F.id)))}).catch(v=>console.error("Failed to fetch config categories:",v))},[]),l.useEffect(()=>{pt().then(y).catch(v=>{console.error("Failed to fetch backup status:",v),w(v.message||"Failed to fetch backup status")})},[]);const z=async v=>{if(!P){I(!0),w(null);try{const D=await ht(v);y(D)}catch(D){w(D.message||"Failed to update backup setting")}finally{I(!1)}}},B=v=>{d(D=>{const F=new Set(D);return F.has(v)?F.delete(v):F.add(v),F})},q=v=>{c(D=>{const F=new Set(D);return F.has(v)?F.delete(v):F.add(v),F})},C=()=>d(new Set(a.map(v=>v.id))),R=()=>d(new Set),K=()=>{p&&c(new Set(p.categories.map(v=>v.id)))},W=()=>c(new Set),te=async()=>{var v;if(o.size!==0){n(!0),b(null);try{const D=Array.from(o).join(","),F=await je(ke(`/api/config/export?categories=${D}`));if(!F.ok)throw new Error("Export failed");const Q=await F.blob(),ee=window.URL.createObjectURL(Q),T=document.createElement("a");T.href=ee;const A=F.headers.get("Content-Disposition"),J=((v=A==null?void 0:A.match(/filename="(.+)"/))==null?void 0:v[1])||"tide-commander-config.zip";T.download=J,document.body.appendChild(T),T.click(),document.body.removeChild(T),window.URL.revokeObjectURL(ee),b({type:"success",text:s("config:data.exportSuccess")})}catch(D){b({type:"error",text:D.message||"Export failed"})}finally{n(!1)}}},k=async v=>{var F;const D=(F=v.target.files)==null?void 0:F[0];if(D){u(D),b(null),m(null),c(new Set);try{const Q=await je(ke("/api/config/preview"),{method:"POST",headers:{"Content-Type":"application/zip"},body:await D.arrayBuffer()});if(!Q.ok){const A=await Q.json();throw new Error(A.error||"Failed to preview config file")}const ee=await Q.json(),T=Array.isArray(ee.categories)?ee.categories:[];m({...ee,categories:T}),c(new Set(T.map(A=>A.id)))}catch(Q){b({type:"error",text:Q.message||"Failed to read config file"}),u(null)}}},O=async()=>{if(!(!S||r.size===0)){N(!0),b(null);try{const v=Array.from(r).join(","),D=await je(ke(`/api/config/import?categories=${v}`),{method:"POST",headers:{"Content-Type":"application/zip"},body:await S.arrayBuffer()}),F=await D.json();if(!D.ok)throw new Error(F.error||"Import failed");b({type:"success",text:F.message||s("config:data.importSuccess")}),u(null),m(null),c(new Set)}catch(v){b({type:"error",text:v.message||"Import failed"})}finally{N(!1)}}},V=()=>{u(null),m(null),c(new Set),b(null)};return e.jsxs("div",{className:"data-section",children:[j&&e.jsx("div",{className:`data-message data-message-${j.type}`,children:j.text}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:"Hourly Backups"}),e.jsx(mt,{checked:!!(h!=null&&h.enabled),disabled:P||!h,onChange:z})]}),e.jsxs("div",{className:"data-backup-info",children:[h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:["Saves a compressed snapshot of your data every hour to"," ",e.jsx("code",{children:h.backupDir}),". Identical snapshots are skipped. Keeps the 8 newest plus one from each of the 2 most recent prior days."]}),!h.scriptExists&&e.jsxs("div",{style:{marginTop:6,color:"var(--dracula-red, #ff5555)"},children:["Backup script not found at ",e.jsx("code",{children:h.scriptPath})]}),h.lastRunAt&&e.jsxs("div",{style:{marginTop:6},children:["Last run: ",new Date(h.lastRunAt).toLocaleString(),h.lastRunOk===!0&&" — ok",h.lastRunOk===!1&&h.lastRunError&&e.jsxs("span",{style:{color:"var(--dracula-red, #ff5555)"},children:[" — ",h.lastRunError]})]})]}):e.jsx("div",{children:"Loading backup status…"}),H&&e.jsx("div",{className:"data-message data-message-error",style:{marginTop:6},children:H})]})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-title",children:s("config:data.exportData")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:C,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:R,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:a.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:o.has(v.id),onChange:()=>B(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name})]},v.id))}),e.jsx("button",{className:"data-action-btn export",onClick:te,disabled:x||o.size===0,children:x?s("config:data.exporting"):s("config:data.exportCount",{count:o.size})})]}),e.jsxs("div",{className:"data-subsection",children:[e.jsx("div",{className:"data-subsection-header",children:e.jsx("span",{className:"data-subsection-title",children:s("config:data.importData")})}),S?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"data-import-info",children:[e.jsx("div",{className:"data-import-file",children:S.name}),e.jsxs("div",{className:"data-import-date",children:[s("config:data.exported"),": ",new Date(p.exportedAt).toLocaleDateString()]})]}),e.jsxs("div",{className:"data-subsection-header",children:[e.jsx("span",{className:"data-subsection-subtitle",children:s("config:data.selectToImport")}),e.jsxs("div",{className:"data-select-controls",children:[e.jsx("button",{className:"data-select-btn",onClick:K,children:s("common:labels.all")}),e.jsx("button",{className:"data-select-btn",onClick:W,children:s("common:labels.none")})]})]}),e.jsx("div",{className:"data-category-list",children:p.categories.map(v=>e.jsxs("label",{className:"data-category-item",children:[e.jsx("input",{type:"checkbox",checked:r.has(v.id),onChange:()=>q(v.id)}),e.jsx("span",{className:"data-category-name",children:v.name}),v.fileCount&&e.jsxs("span",{className:"data-category-count",children:["(",v.fileCount," ",s("config:data.files"),")"]})]},v.id))}),e.jsxs("div",{className:"data-import-actions",children:[e.jsx("button",{className:"data-action-btn cancel",onClick:V,children:s("common:buttons.cancel")}),e.jsx("button",{className:"data-action-btn import",onClick:O,disabled:g||r.size===0,children:g?s("config:data.importing"):s("config:data.importCount",{count:r.size})})]})]}):e.jsx("div",{className:"data-loading",children:s("config:data.readingFile")}):e.jsxs("label",{className:"data-file-input",children:[e.jsx("input",{type:"file",accept:".zip",onChange:k,style:{display:"none"}}),e.jsx("span",{className:"data-file-input-label",children:s("config:data.selectFile")})]})]})]})}async function ft(){const s=await je(`${Y()}/api/system/install-info`);if(!s.ok)throw new Error(`Failed to fetch install info: ${s.statusText}`);return s.json()}function xt(s,a){const t=new AbortController;return(async()=>{try{const o=await fetch(bs(`${Y()}/api/system/self-update`),{method:"POST",signal:t.signal,headers:{Accept:"text/event-stream"}});if(!o.ok||!o.body){const x=await o.text().catch(()=>"");let n=null;try{n=JSON.parse(x)}catch{}const g=n&&typeof n=="object"&&"error"in n&&typeof n.error=="string"?n.error:`Self-update failed: ${o.status} ${o.statusText}`;s({type:"error",message:g}),a(new Error(g));return}const d=o.body.getReader(),r=new TextDecoder("utf-8");let c="";for(;;){const{value:x,done:n}=await d.read();if(n)break;c+=r.decode(x,{stream:!0});let g=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`);for(;g!==-1;){const N=c.slice(0,g);c=c.slice(g+2);const S=N.split(`
|
|
4
4
|
`);let u="message",p="";for(const m of S)m.startsWith(":")||(m.startsWith("event:")?u=m.slice(6).trim():m.startsWith("data:")&&(p+=(p?`
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-
|
|
2
|
-
import{r as t,h as W,i as V,G as Yt,Z as Bs,S as Ht,_ as _s,s as Be,u as re,j as e,I as M,bJ as zt,f as Vs,bK as Ks,bL as Gn,bM as Ws,bN as qs,bO as Un,bP as Bn,bQ as Pt,bR as _n,bS as Vn,bT as Kn,bU as es,bV as Wn,bW as Ys,bX as Lt,bY as $t,ak as ct,bZ as xt,b_ as yt,b$ as Is,c0 as qn,be as Yn,c1 as Zt,c2 as Ft,c3 as Jn,c4 as Xn,c5 as Qn,c6 as Zn,c7 as ea,c8 as Ps,C as ta,o as sa}from"./main-D5m1NJ8q.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function na(s){const[n,l]=t.useState(null),[d,r]=t.useState(!1),i=t.useCallback(async()=>{if(s){r(!0);try{const m=await W(V(`/api/files/git-status?path=${encodeURIComponent(s)}`)),o=await m.json();m.ok?l(o):l({isGitRepo:!1,files:[]})}catch(m){console.error("[FileExplorer] Failed to load git status:",m),l({isGitRepo:!1,files:[]})}finally{r(!1)}}},[s]);return{gitStatus:n,loading:d,loadGitStatus:i}}async function aa(s){try{const n=await W(V(`/api/files/git-original?path=${encodeURIComponent(s)}`)),l=await n.json();return n.ok&&!l.isNew?{content:l.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const ra=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",""]),ia=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),la=new Set([".pdf"]),oa=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 ca(s){const n=s.toLowerCase();return ia.has(n)?"image":la.has(n)?"pdf":oa.has(n)?"binary":(ra.has(n),"text")}function da(){const[s,n]=t.useState(null),[l,d]=t.useState(!1),[r,i]=t.useState(null),m=t.useCallback(async h=>{var p,j;d(!0),i(null);try{const f=h.substring(h.lastIndexOf(".")).toLowerCase(),b=ca(f),w=h.substring(h.lastIndexOf("/")+1);if(b==="image"){const k=await W(V(`/api/files/binary?path=${encodeURIComponent(h)}`));if(!k.ok){const C=await k.json().catch(()=>({error:"Failed to load image"}));i(C.error||"Failed to load image"),n(null);return}const x=await k.blob(),v=URL.createObjectURL(x);n({path:h,filename:w,extension:f,content:"",size:x.size,modified:new Date().toISOString(),fileType:"image",dataUrl:v});return}if(b==="pdf"){const k=await W(V(`/api/files/info?path=${encodeURIComponent(h)}`)),x=await k.json();if(!k.ok){i(x.error||"Failed to load PDF info"),n(null);return}n({path:h,filename:w,extension:f,content:"",size:x.size,modified:x.modified,fileType:"pdf",dataUrl:V(`/api/files/binary?path=${encodeURIComponent(h)}&token=${encodeURIComponent(Yt())}`)});return}if(b==="binary"){const k=await W(V(`/api/files/info?path=${encodeURIComponent(h)}`)),x=await k.json();if(!k.ok){i(x.error||"Failed to load file info"),n(null);return}n({path:h,filename:w,extension:f,content:"",size:x.size,modified:x.modified,fileType:"binary",dataUrl:V(`/api/files/binary?path=${encodeURIComponent(h)}&download=true&token=${encodeURIComponent(Yt())}`)});return}const R=await W(V(`/api/files/read?path=${encodeURIComponent(h)}`)),g=await R.json();if(!R.ok){if((p=g.error)!=null&&p.includes("too large")||(j=g.error)!=null&&j.includes("binary")){const k=await W(V(`/api/files/info?path=${encodeURIComponent(h)}`)),x=await k.json();if(k.ok){n({path:h,filename:w,extension:f,content:"",size:x.size,modified:x.modified,fileType:"binary",dataUrl:V(`/api/files/binary?path=${encodeURIComponent(h)}&download=true&token=${encodeURIComponent(Yt())}`)});return}}i(g.error||"Failed to load file"),n(null);return}n({...g,fileType:"text"})}catch(f){const b=f instanceof Error?f.message:"Failed to load file";i(b),n(null)}finally{d(!1)}},[]),o=t.useCallback(()=>{n(h=>(h!=null&&h.dataUrl&&h.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(h.dataUrl),null)),i(null)},[]);return{file:s,loading:l,error:r,loadFile:m,clearFile:o,setFile:n}}const Jt="file-explorer-state",ua=10080*60*1e3;function ha(s,n){return n?`${Jt}-folder-${n}`:s?`${Jt}-area-${s}`:`${Jt}-default`}async function ma(s){try{const n=await W(V(`/api/files/exists?path=${encodeURIComponent(s)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function fa({areaId:s,folderPath:n,isOpen:l}){const d=ha(s,n),r=t.useRef(!1);t.useEffect(()=>{r.current=!1},[s,n]);const i=t.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const o=localStorage.getItem(d);if(!o)return null;const h=JSON.parse(o);if(Date.now()-h.timestamp>ua)return localStorage.removeItem(d),null;const j=(await Promise.all(h.tabs.map(async b=>({tab:b,exists:await ma(b.path)})))).filter(({exists:b})=>b).map(({tab:b})=>b);let f=h.activeTabPath;return f&&!j.some(b=>b.path===f)&&(f=j.length>0?j[0].path:null),{tabs:j,activeTabPath:f,viewMode:h.viewMode||"files",selectedFolderIndex:h.selectedFolderIndex||0,expandedPaths:new Set(h.expandedPaths||[])}}catch(o){return console.error("[FileExplorerStorage] Failed to load state:",o),null}},[d]),m=t.useCallback(o=>{if(l)try{const h={tabs:o.tabs,activeTabPath:o.activeTabPath,viewMode:o.viewMode,selectedFolderIndex:o.selectedFolderIndex,expandedPaths:Array.from(o.expandedPaths),timestamp:Date.now()};localStorage.setItem(d,JSON.stringify(h))}catch(h){console.error("[FileExplorerStorage] Failed to save state:",h)}},[d,l]);return{loadStoredState:i,saveState:m}}const Ls=280,$s=150,Hs=1200;function pa(){const[s,n]=t.useState(()=>{const p=Bs(Ht.TREE_PANEL_WIDTH,Ls);return p>=$s&&p<=Hs?p:Ls}),l=t.useRef(!1),[d,r]=t.useState(!1),i=t.useRef(0),m=t.useRef(0),o=t.useRef(s);o.current=s;const h=t.useCallback(p=>{p.preventDefault(),l.current=!0,r(!0),i.current=p.clientX,m.current=s,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[s]);return t.useEffect(()=>{const p=f=>{if(!l.current)return;const b=f.clientX-i.current,w=Math.min(Hs,Math.max($s,m.current+b));n(w)},j=()=>{l.current&&(l.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",_s(Ht.TREE_PANEL_WIDTH,o.current))};return document.addEventListener("mousemove",p),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:s,handleResizeStart:h,isResizing:d}}const ga=100,xa=.65,ya=36;function ba(){const[s,n]=t.useState(()=>Bs(Ht.MOBILE_TREE_PANEL_HEIGHT,0)),l=t.useRef(s);l.current=s;const d=t.useRef(0),r=t.useRef(0),i=()=>Math.floor((window.innerHeight-ya)*xa),m=f=>Math.min(i(),Math.max(ga,f)),o=t.useCallback(f=>{n(f);const b=document.querySelector(".file-explorer-main");b&&b.style.setProperty("--fe-mobile-tree-height",`${f}px`)},[]),h=t.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",_s(Ht.MOBILE_TREE_PANEL_HEIGHT,l.current),Be.setTerminalResizing(!1)},[]),p=t.useCallback(f=>{f.preventDefault();const b=document.querySelector(".file-explorer-tree-panel"),w=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;d.current=f.clientY,r.current=w,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",Be.setTerminalResizing(!0);const R=k=>{const x=k.clientY-d.current;o(m(r.current+x))},g=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",g),h()};document.addEventListener("mousemove",R),document.addEventListener("mouseup",g)},[o,h]),j=t.useCallback(f=>{if(f.touches.length!==1)return;const b=document.querySelector(".file-explorer-tree-panel"),w=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;d.current=f.touches[0].clientY,r.current=w,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",Be.setTerminalResizing(!0);const R=k=>{if(k.touches.length!==1)return;k.preventDefault();const x=k.touches[0].clientY-d.current;o(m(r.current+x))},g=()=>{document.removeEventListener("touchmove",R),document.removeEventListener("touchend",g),document.removeEventListener("touchcancel",g),h()};document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",g),document.addEventListener("touchcancel",g)},[o,h]);return{mobileTreeHeight:s,handleResizeMouseDown:p,handleResizeTouchStart:j}}function ts(){const[s,n]=t.useState([]),[l,d]=t.useState(!1),[r,i]=t.useState(null),[m,o]=t.useState(null),h=t.useCallback(async k=>{d(!0),i(null);try{const x=await W(V(`/api/files/git-branches?path=${encodeURIComponent(k)}`)),v=await x.json();x.ok?n(v.branches||[]):(i(v.error||"Failed to load branches"),n([]))}catch(x){console.error("[GitBranches] Failed to load branches:",x),i("Failed to load branches"),n([])}finally{d(!1)}},[]),p=t.useCallback(async(k,x)=>{o("checkout"),i(null);try{const v=await W(V("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,branch:x})}),C=await v.json();return v.ok||i(C.error||"Checkout failed"),C}catch(v){console.error("[GitBranches] Checkout failed:",v);const C={success:!1,error:"Checkout failed"};return i(C.error),C}finally{o(null)}},[]),j=t.useCallback(async(k,x,v)=>{o("create"),i(null);try{const C=await W(V("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,name:x,startPoint:v})}),D=await C.json();return C.ok||i(D.error||"Failed to create branch"),D}catch(C){console.error("[GitBranches] Create branch failed:",C);const D={success:!1,error:"Failed to create branch"};return i(D.error),D}finally{o(null)}},[]),f=t.useCallback(async k=>{o("pull"),i(null);try{const x=await W(V("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return!x.ok&&!v.conflicts&&i(v.error||"Pull failed"),v}catch(x){console.error("[GitBranches] Pull failed:",x);const v={success:!1,error:"Pull failed"};return i(v.error),v}finally{o(null)}},[]),b=t.useCallback(async k=>{o("push"),i(null);try{const x=await W(V("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return x.ok||i(v.error||"Push failed"),v}catch(x){console.error("[GitBranches] Push failed:",x);const v={success:!1,error:"Push failed"};return i(v.error),v}finally{o(null)}},[]),w=t.useCallback(async(k,x)=>{o("merge"),i(null);try{const v=await W(V("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,branch:x})}),C=await v.json();return!v.ok&&!C.conflicts&&i(C.error||"Merge failed"),C}catch(v){console.error("[GitBranches] Merge failed:",v);const C={success:!1,error:"Merge failed"};return i(C.error),C}finally{o(null)}},[]),R=t.useCallback(async k=>{o("merge-abort"),i(null);try{const x=await W(V("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return x.ok||i(v.error||"Merge abort failed"),v}catch(x){console.error("[GitBranches] Merge abort failed:",x);const v={success:!1,error:"Merge abort failed"};return i(v.error),v}finally{o(null)}},[]),g=t.useCallback(async k=>{o("merge-continue"),i(null);try{const x=await W(V("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return x.ok||i(v.error||"Merge continue failed"),v}catch(x){console.error("[GitBranches] Merge continue failed:",x);const v={success:!1,error:"Merge continue failed"};return i(v.error),v}finally{o(null)}},[]);return{branches:s,loading:l,error:r,operationInProgress:m,loadBranches:h,checkoutBranch:p,createBranch:j,pullFromRemote:f,pushToRemote:b,mergeBranch:w,mergeAbort:R,mergeContinue:g}}const ja=50,va=400,zs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function wa(){const[s,n]=t.useState([]),[l,d]=t.useState(!1),[r,i]=t.useState(!1),[m,o]=t.useState(null),[h,p]=t.useState(!1),[j,f]=t.useState(0),[b,w]=t.useState({...zs}),[R,g]=t.useState(null),[k,x]=t.useState([]),[v,C]=t.useState(!1),[D,N]=t.useState([]),[U,_]=t.useState(!1),O=t.useRef(null),se=t.useRef(""),Q=t.useCallback((z,I,$)=>{const P=$||b,ee=new URLSearchParams;return ee.set("path",z),ee.set("limit",String(ja)),ee.set("offset",String(I)),P.branch&&ee.set("branch",P.branch),P.author&&ee.set("author",P.author),P.since&&ee.set("since",P.since),P.until&&ee.set("until",P.until),P.searchPath&&ee.set("searchPath",P.searchPath),P.search&&ee.set("search",P.search),ee.toString()},[b]),T=t.useCallback(async z=>{se.current=z,d(!0),o(null),g(null),x([]);try{const I=Q(z,0),$=await W(V(`/api/files/git-log?${I}`)),P=await $.json();$.ok?(n(P.commits||[]),f(P.total||0),p(P.hasMore||!1)):(o(P.error||"Failed to load git history"),n([]))}catch(I){console.error("[useGitHistory] loadHistory error:",I),o("Failed to load git history"),n([])}finally{d(!1)}},[Q]),F=t.useCallback(async z=>{if(!(r||!h)){i(!0);try{const I=Q(z,s.length),$=await W(V(`/api/files/git-log?${I}`)),P=await $.json();$.ok&&(n(ee=>[...ee,...P.commits||[]]),f(P.total||0),p(P.hasMore||!1))}catch(I){console.error("[useGitHistory] loadMore error:",I)}finally{i(!1)}}},[Q,s.length,h,r]),K=t.useCallback(async z=>{if(g(z),!z){x([]);return}C(!0);try{const I=se.current,$=new URLSearchParams({path:I,hash:z.hash}),P=await W(V(`/api/files/git-commit-files?${$}`)),ee=await P.json();P.ok?x(ee.files||[]):x([])}catch(I){console.error("[useGitHistory] selectCommit files error:",I),x([])}finally{C(!1)}},[]),ne=t.useCallback((z,I)=>{w($=>({...$,[z]:I}))},[]),ie=t.useCallback(()=>{w({...zs})},[]);t.useEffect(()=>{const z=se.current;if(z)return O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{T(z)},va),()=>{O.current&&clearTimeout(O.current)}},[b]);const fe=t.useCallback(async z=>{_(!0);try{const I=new URLSearchParams({path:z}),$=await W(V(`/api/files/git-authors?${I}`)),P=await $.json();$.ok&&N(P.authors||[])}catch(I){console.error("[useGitHistory] loadAuthors error:",I)}finally{_(!1)}},[]);return{commits:s,loading:l,loadingMore:r,error:m,hasMore:h,total:j,filters:b,setFilter:ne,resetFilters:ie,selectedCommit:R,selectCommit:K,commitFiles:k,commitFilesLoading:v,loadHistory:T,loadMore:F,authors:D,authorsLoading:U,loadAuthors:fe}}function Ca(s){if(!s.current)return null;const n=[".file-viewer-code-with-lines",".file-viewer-markdown-wrapper",".file-viewer-code-wrapper",".file-viewer-diagram-wrapper",".file-viewer-image-wrapper",".file-viewer-pdf-wrapper"];for(const l of n){const d=s.current.querySelector(l);if(d&&Os(d))return d}return Os(s.current)?s.current:null}function Os(s){const n=["auto","scroll"].includes(getComputedStyle(s).overflowY),l=s.scrollHeight>s.clientHeight||s.scrollWidth>s.clientWidth;return n&&l}function Js(s){if(!s)return 19.5;const n=parseFloat(getComputedStyle(s).lineHeight);return isNaN(n)?19.5:n}function Xt(s,n=!0){const l=n?s.scrollHeight:0;s.scrollTo({top:l,behavior:"smooth"})}function Na(s){const{scrollTop:n,scrollHeight:l,clientHeight:d}=s;return l<=d?100:Math.round(n/(l-d)*100)}function ka(s,n){const l=Js(s),d=s.scrollTop,r=Math.floor(d/l)+1,i=n.split(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-DIo_5FuD.js","assets/main-D1dj_wn_.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-rrlO1Py8.css","assets/EmbeddedEditor-O_u2UVA4.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as t,h as W,i as V,G as Yt,Z as Bs,S as Ht,_ as _s,s as Be,u as re,j as e,I as M,bJ as zt,f as Vs,bK as Ks,bL as Gn,bM as Ws,bN as qs,bO as Un,bP as Bn,bQ as Pt,bR as _n,bS as Vn,bT as Kn,bU as es,bV as Wn,bW as Ys,bX as Lt,bY as $t,ak as ct,bZ as xt,b_ as yt,b$ as Is,c0 as qn,be as Yn,c1 as Zt,c2 as Ft,c3 as Jn,c4 as Xn,c5 as Qn,c6 as Zn,c7 as ea,c8 as Ps,C as ta,o as sa}from"./main-D1dj_wn_.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function na(s){const[n,l]=t.useState(null),[d,r]=t.useState(!1),i=t.useCallback(async()=>{if(s){r(!0);try{const m=await W(V(`/api/files/git-status?path=${encodeURIComponent(s)}`)),o=await m.json();m.ok?l(o):l({isGitRepo:!1,files:[]})}catch(m){console.error("[FileExplorer] Failed to load git status:",m),l({isGitRepo:!1,files:[]})}finally{r(!1)}}},[s]);return{gitStatus:n,loading:d,loadGitStatus:i}}async function aa(s){try{const n=await W(V(`/api/files/git-original?path=${encodeURIComponent(s)}`)),l=await n.json();return n.ok&&!l.isNew?{content:l.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const ra=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",""]),ia=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),la=new Set([".pdf"]),oa=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 ca(s){const n=s.toLowerCase();return ia.has(n)?"image":la.has(n)?"pdf":oa.has(n)?"binary":(ra.has(n),"text")}function da(){const[s,n]=t.useState(null),[l,d]=t.useState(!1),[r,i]=t.useState(null),m=t.useCallback(async h=>{var p,j;d(!0),i(null);try{const f=h.substring(h.lastIndexOf(".")).toLowerCase(),b=ca(f),w=h.substring(h.lastIndexOf("/")+1);if(b==="image"){const k=await W(V(`/api/files/binary?path=${encodeURIComponent(h)}`));if(!k.ok){const C=await k.json().catch(()=>({error:"Failed to load image"}));i(C.error||"Failed to load image"),n(null);return}const x=await k.blob(),v=URL.createObjectURL(x);n({path:h,filename:w,extension:f,content:"",size:x.size,modified:new Date().toISOString(),fileType:"image",dataUrl:v});return}if(b==="pdf"){const k=await W(V(`/api/files/info?path=${encodeURIComponent(h)}`)),x=await k.json();if(!k.ok){i(x.error||"Failed to load PDF info"),n(null);return}n({path:h,filename:w,extension:f,content:"",size:x.size,modified:x.modified,fileType:"pdf",dataUrl:V(`/api/files/binary?path=${encodeURIComponent(h)}&token=${encodeURIComponent(Yt())}`)});return}if(b==="binary"){const k=await W(V(`/api/files/info?path=${encodeURIComponent(h)}`)),x=await k.json();if(!k.ok){i(x.error||"Failed to load file info"),n(null);return}n({path:h,filename:w,extension:f,content:"",size:x.size,modified:x.modified,fileType:"binary",dataUrl:V(`/api/files/binary?path=${encodeURIComponent(h)}&download=true&token=${encodeURIComponent(Yt())}`)});return}const R=await W(V(`/api/files/read?path=${encodeURIComponent(h)}`)),g=await R.json();if(!R.ok){if((p=g.error)!=null&&p.includes("too large")||(j=g.error)!=null&&j.includes("binary")){const k=await W(V(`/api/files/info?path=${encodeURIComponent(h)}`)),x=await k.json();if(k.ok){n({path:h,filename:w,extension:f,content:"",size:x.size,modified:x.modified,fileType:"binary",dataUrl:V(`/api/files/binary?path=${encodeURIComponent(h)}&download=true&token=${encodeURIComponent(Yt())}`)});return}}i(g.error||"Failed to load file"),n(null);return}n({...g,fileType:"text"})}catch(f){const b=f instanceof Error?f.message:"Failed to load file";i(b),n(null)}finally{d(!1)}},[]),o=t.useCallback(()=>{n(h=>(h!=null&&h.dataUrl&&h.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(h.dataUrl),null)),i(null)},[]);return{file:s,loading:l,error:r,loadFile:m,clearFile:o,setFile:n}}const Jt="file-explorer-state",ua=10080*60*1e3;function ha(s,n){return n?`${Jt}-folder-${n}`:s?`${Jt}-area-${s}`:`${Jt}-default`}async function ma(s){try{const n=await W(V(`/api/files/exists?path=${encodeURIComponent(s)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function fa({areaId:s,folderPath:n,isOpen:l}){const d=ha(s,n),r=t.useRef(!1);t.useEffect(()=>{r.current=!1},[s,n]);const i=t.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const o=localStorage.getItem(d);if(!o)return null;const h=JSON.parse(o);if(Date.now()-h.timestamp>ua)return localStorage.removeItem(d),null;const j=(await Promise.all(h.tabs.map(async b=>({tab:b,exists:await ma(b.path)})))).filter(({exists:b})=>b).map(({tab:b})=>b);let f=h.activeTabPath;return f&&!j.some(b=>b.path===f)&&(f=j.length>0?j[0].path:null),{tabs:j,activeTabPath:f,viewMode:h.viewMode||"files",selectedFolderIndex:h.selectedFolderIndex||0,expandedPaths:new Set(h.expandedPaths||[])}}catch(o){return console.error("[FileExplorerStorage] Failed to load state:",o),null}},[d]),m=t.useCallback(o=>{if(l)try{const h={tabs:o.tabs,activeTabPath:o.activeTabPath,viewMode:o.viewMode,selectedFolderIndex:o.selectedFolderIndex,expandedPaths:Array.from(o.expandedPaths),timestamp:Date.now()};localStorage.setItem(d,JSON.stringify(h))}catch(h){console.error("[FileExplorerStorage] Failed to save state:",h)}},[d,l]);return{loadStoredState:i,saveState:m}}const Ls=280,$s=150,Hs=1200;function pa(){const[s,n]=t.useState(()=>{const p=Bs(Ht.TREE_PANEL_WIDTH,Ls);return p>=$s&&p<=Hs?p:Ls}),l=t.useRef(!1),[d,r]=t.useState(!1),i=t.useRef(0),m=t.useRef(0),o=t.useRef(s);o.current=s;const h=t.useCallback(p=>{p.preventDefault(),l.current=!0,r(!0),i.current=p.clientX,m.current=s,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[s]);return t.useEffect(()=>{const p=f=>{if(!l.current)return;const b=f.clientX-i.current,w=Math.min(Hs,Math.max($s,m.current+b));n(w)},j=()=>{l.current&&(l.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",_s(Ht.TREE_PANEL_WIDTH,o.current))};return document.addEventListener("mousemove",p),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:s,handleResizeStart:h,isResizing:d}}const ga=100,xa=.65,ya=36;function ba(){const[s,n]=t.useState(()=>Bs(Ht.MOBILE_TREE_PANEL_HEIGHT,0)),l=t.useRef(s);l.current=s;const d=t.useRef(0),r=t.useRef(0),i=()=>Math.floor((window.innerHeight-ya)*xa),m=f=>Math.min(i(),Math.max(ga,f)),o=t.useCallback(f=>{n(f);const b=document.querySelector(".file-explorer-main");b&&b.style.setProperty("--fe-mobile-tree-height",`${f}px`)},[]),h=t.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",_s(Ht.MOBILE_TREE_PANEL_HEIGHT,l.current),Be.setTerminalResizing(!1)},[]),p=t.useCallback(f=>{f.preventDefault();const b=document.querySelector(".file-explorer-tree-panel"),w=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;d.current=f.clientY,r.current=w,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",Be.setTerminalResizing(!0);const R=k=>{const x=k.clientY-d.current;o(m(r.current+x))},g=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",g),h()};document.addEventListener("mousemove",R),document.addEventListener("mouseup",g)},[o,h]),j=t.useCallback(f=>{if(f.touches.length!==1)return;const b=document.querySelector(".file-explorer-tree-panel"),w=l.current>0?l.current:(b==null?void 0:b.getBoundingClientRect().height)??240;d.current=f.touches[0].clientY,r.current=w,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",Be.setTerminalResizing(!0);const R=k=>{if(k.touches.length!==1)return;k.preventDefault();const x=k.touches[0].clientY-d.current;o(m(r.current+x))},g=()=>{document.removeEventListener("touchmove",R),document.removeEventListener("touchend",g),document.removeEventListener("touchcancel",g),h()};document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",g),document.addEventListener("touchcancel",g)},[o,h]);return{mobileTreeHeight:s,handleResizeMouseDown:p,handleResizeTouchStart:j}}function ts(){const[s,n]=t.useState([]),[l,d]=t.useState(!1),[r,i]=t.useState(null),[m,o]=t.useState(null),h=t.useCallback(async k=>{d(!0),i(null);try{const x=await W(V(`/api/files/git-branches?path=${encodeURIComponent(k)}`)),v=await x.json();x.ok?n(v.branches||[]):(i(v.error||"Failed to load branches"),n([]))}catch(x){console.error("[GitBranches] Failed to load branches:",x),i("Failed to load branches"),n([])}finally{d(!1)}},[]),p=t.useCallback(async(k,x)=>{o("checkout"),i(null);try{const v=await W(V("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,branch:x})}),C=await v.json();return v.ok||i(C.error||"Checkout failed"),C}catch(v){console.error("[GitBranches] Checkout failed:",v);const C={success:!1,error:"Checkout failed"};return i(C.error),C}finally{o(null)}},[]),j=t.useCallback(async(k,x,v)=>{o("create"),i(null);try{const C=await W(V("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,name:x,startPoint:v})}),D=await C.json();return C.ok||i(D.error||"Failed to create branch"),D}catch(C){console.error("[GitBranches] Create branch failed:",C);const D={success:!1,error:"Failed to create branch"};return i(D.error),D}finally{o(null)}},[]),f=t.useCallback(async k=>{o("pull"),i(null);try{const x=await W(V("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return!x.ok&&!v.conflicts&&i(v.error||"Pull failed"),v}catch(x){console.error("[GitBranches] Pull failed:",x);const v={success:!1,error:"Pull failed"};return i(v.error),v}finally{o(null)}},[]),b=t.useCallback(async k=>{o("push"),i(null);try{const x=await W(V("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return x.ok||i(v.error||"Push failed"),v}catch(x){console.error("[GitBranches] Push failed:",x);const v={success:!1,error:"Push failed"};return i(v.error),v}finally{o(null)}},[]),w=t.useCallback(async(k,x)=>{o("merge"),i(null);try{const v=await W(V("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,branch:x})}),C=await v.json();return!v.ok&&!C.conflicts&&i(C.error||"Merge failed"),C}catch(v){console.error("[GitBranches] Merge failed:",v);const C={success:!1,error:"Merge failed"};return i(C.error),C}finally{o(null)}},[]),R=t.useCallback(async k=>{o("merge-abort"),i(null);try{const x=await W(V("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return x.ok||i(v.error||"Merge abort failed"),v}catch(x){console.error("[GitBranches] Merge abort failed:",x);const v={success:!1,error:"Merge abort failed"};return i(v.error),v}finally{o(null)}},[]),g=t.useCallback(async k=>{o("merge-continue"),i(null);try{const x=await W(V("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),v=await x.json();return x.ok||i(v.error||"Merge continue failed"),v}catch(x){console.error("[GitBranches] Merge continue failed:",x);const v={success:!1,error:"Merge continue failed"};return i(v.error),v}finally{o(null)}},[]);return{branches:s,loading:l,error:r,operationInProgress:m,loadBranches:h,checkoutBranch:p,createBranch:j,pullFromRemote:f,pushToRemote:b,mergeBranch:w,mergeAbort:R,mergeContinue:g}}const ja=50,va=400,zs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function wa(){const[s,n]=t.useState([]),[l,d]=t.useState(!1),[r,i]=t.useState(!1),[m,o]=t.useState(null),[h,p]=t.useState(!1),[j,f]=t.useState(0),[b,w]=t.useState({...zs}),[R,g]=t.useState(null),[k,x]=t.useState([]),[v,C]=t.useState(!1),[D,N]=t.useState([]),[U,_]=t.useState(!1),O=t.useRef(null),se=t.useRef(""),Q=t.useCallback((z,I,$)=>{const P=$||b,ee=new URLSearchParams;return ee.set("path",z),ee.set("limit",String(ja)),ee.set("offset",String(I)),P.branch&&ee.set("branch",P.branch),P.author&&ee.set("author",P.author),P.since&&ee.set("since",P.since),P.until&&ee.set("until",P.until),P.searchPath&&ee.set("searchPath",P.searchPath),P.search&&ee.set("search",P.search),ee.toString()},[b]),T=t.useCallback(async z=>{se.current=z,d(!0),o(null),g(null),x([]);try{const I=Q(z,0),$=await W(V(`/api/files/git-log?${I}`)),P=await $.json();$.ok?(n(P.commits||[]),f(P.total||0),p(P.hasMore||!1)):(o(P.error||"Failed to load git history"),n([]))}catch(I){console.error("[useGitHistory] loadHistory error:",I),o("Failed to load git history"),n([])}finally{d(!1)}},[Q]),F=t.useCallback(async z=>{if(!(r||!h)){i(!0);try{const I=Q(z,s.length),$=await W(V(`/api/files/git-log?${I}`)),P=await $.json();$.ok&&(n(ee=>[...ee,...P.commits||[]]),f(P.total||0),p(P.hasMore||!1))}catch(I){console.error("[useGitHistory] loadMore error:",I)}finally{i(!1)}}},[Q,s.length,h,r]),K=t.useCallback(async z=>{if(g(z),!z){x([]);return}C(!0);try{const I=se.current,$=new URLSearchParams({path:I,hash:z.hash}),P=await W(V(`/api/files/git-commit-files?${$}`)),ee=await P.json();P.ok?x(ee.files||[]):x([])}catch(I){console.error("[useGitHistory] selectCommit files error:",I),x([])}finally{C(!1)}},[]),ne=t.useCallback((z,I)=>{w($=>({...$,[z]:I}))},[]),ie=t.useCallback(()=>{w({...zs})},[]);t.useEffect(()=>{const z=se.current;if(z)return O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{T(z)},va),()=>{O.current&&clearTimeout(O.current)}},[b]);const fe=t.useCallback(async z=>{_(!0);try{const I=new URLSearchParams({path:z}),$=await W(V(`/api/files/git-authors?${I}`)),P=await $.json();$.ok&&N(P.authors||[])}catch(I){console.error("[useGitHistory] loadAuthors error:",I)}finally{_(!1)}},[]);return{commits:s,loading:l,loadingMore:r,error:m,hasMore:h,total:j,filters:b,setFilter:ne,resetFilters:ie,selectedCommit:R,selectCommit:K,commitFiles:k,commitFilesLoading:v,loadHistory:T,loadMore:F,authors:D,authorsLoading:U,loadAuthors:fe}}function Ca(s){if(!s.current)return null;const n=[".file-viewer-code-with-lines",".file-viewer-markdown-wrapper",".file-viewer-code-wrapper",".file-viewer-diagram-wrapper",".file-viewer-image-wrapper",".file-viewer-pdf-wrapper"];for(const l of n){const d=s.current.querySelector(l);if(d&&Os(d))return d}return Os(s.current)?s.current:null}function Os(s){const n=["auto","scroll"].includes(getComputedStyle(s).overflowY),l=s.scrollHeight>s.clientHeight||s.scrollWidth>s.clientWidth;return n&&l}function Js(s){if(!s)return 19.5;const n=parseFloat(getComputedStyle(s).lineHeight);return isNaN(n)?19.5:n}function Xt(s,n=!0){const l=n?s.scrollHeight:0;s.scrollTo({top:l,behavior:"smooth"})}function Na(s){const{scrollTop:n,scrollHeight:l,clientHeight:d}=s;return l<=d?100:Math.round(n/(l-d)*100)}function ka(s,n){const l=Js(s),d=s.scrollTop,r=Math.floor(d/l)+1,i=n.split(`
|
|
3
3
|
`).length;return Math.min(r,i)}function Ea(s,n,l=!1){if(!n)return[];l||s.toLowerCase();const d=l?n:n.toLowerCase(),r=[];let i=0;const m=s.split(`
|
|
4
4
|
`);let o=0;for(let h=0;h<m.length;h++){const p=m[h],j=l?p:p.toLowerCase();let f=0,b=j.indexOf(d);for(;b!==-1;){const w=o+b;r.push({index:i++,line:h+1,column:b,length:d.length,charIndex:w}),f=b+d.length,b=j.indexOf(d,f)}o+=p.length+1}return r}function dt(s){return/[\w]/.test(s)}function _e(s){return/\s/.test(s)}function Sa(s,n,l){let d=n-1,r=l;const i=s.length,m=s[d]||"";if(r<m.length){const p=dt(m[r]);if(!_e(m[r]))for(;r<m.length&&!_e(m[r])&&dt(m[r])===p;)r++}for(;d<i;){const p=s[d]||"";for(;r<p.length&&_e(p[r]);)r++;if(r<p.length)return{line:d+1,col:r};d++,r=0}const o=i,h=Math.max(0,(s[i-1]||"").length-1);return{line:o,col:h}}function Ta(s,n,l){let d=n-1,r=l+1;const i=s.length;for(;d<i;){const h=s[d]||"";for(;r<h.length&&_e(h[r]);)r++;if(r<h.length)break;d++,r=0}if(d>=i)return{line:i,col:Math.max(0,(s[i-1]||"").length-1)};const m=s[d]||"",o=dt(m[r]);for(;r+1<m.length&&!_e(m[r+1])&&dt(m[r+1])===o;)r++;return{line:d+1,col:r}}function Ma(s,n,l){let d=n-1,r=l-1;for(;d>=0;){const o=s[d]||"";for(;r>=0&&_e(o[r]);)r--;if(r>=0)break;d--,d>=0&&(r=(s[d]||"").length-1)}if(d<0)return{line:1,col:0};const i=s[d]||"",m=dt(i[r]);for(;r>0&&!_e(i[r-1])&&dt(i[r-1])===m;)r--;return{line:d+1,col:r}}function Da(s,n,l,d){if(d==="none")return"";const{anchorLine:r,anchorCol:i,headLine:m,headCol:o}=l;if(d==="line"){const w=Math.min(r,m),R=Math.max(r,m);return n.slice(w-1,R).join(`
|
|
5
5
|
`)}let h,p,j,f;if(r<m||r===m&&i<=o?(h=r,p=i,j=m,f=o):(h=m,p=o,j=r,f=i),h===j)return(n[h-1]||"").substring(p,f+1);const b=[];b.push((n[h-1]||"").substring(p));for(let w=h;w<j-1;w++)b.push(n[w]||"");return b.push((n[j-1]||"").substring(0,f+1)),b.join(`
|
|
6
6
|
`)}function Xs(s){const{containerRef:n,isEnabled:l=!0,content:d="",onClose:r,onSearchOpen:i}=s,m=t.useRef({percentage:0,line:1,column:1}),o=t.useRef(null),h=t.useRef(19.5),p=t.useMemo(()=>d.split(`
|
|
7
|
-
`),[d]),j=p.length,[f,b]=t.useState(1),[w,R]=t.useState(0),[g,k]=t.useState(!1),[x,v]=t.useState("none"),[C,D]=t.useState(null),[N,U]=t.useState(!1),[_,O]=t.useState(""),[se,Q]=t.useState(0),[T,F]=t.useState(!1),K=t.useMemo(()=>Ea(d,_,!1),[d,_]),ne=t.useCallback(()=>{const c=o.current;if(!c)return;const G=Na(c),ae=ka(c,d),A=Math.max(1,Math.round(c.scrollLeft/7.8)+1);m.current={percentage:G,line:ae,column:A}},[d]),ie=t.useCallback(()=>{U(!0),O(""),Q(0),i==null||i()},[i]),fe=t.useCallback(()=>{U(!1),O(""),Q(0)},[]),z=t.useCallback(()=>{F(c=>!c)},[]),I=t.useCallback(c=>{const G=o.current;if(!G)return;const ae=G.querySelector(".file-viewer-pre"),ce=ae&&parseFloat(getComputedStyle(ae).lineHeight)||h.current,A=ae&&parseFloat(getComputedStyle(ae).paddingTop)||0,q=(ae?ae.offsetTop:0)+A+(c-1)*ce,Z=ce*3;G.scrollTo({top:Math.max(0,q-Z),behavior:"smooth"})},[]);t.useEffect(()=>{!N||K.length===0||Q(0)},[K,N]),t.useEffect(()=>{if(!N||K.length===0)return;const c=K[se];c&&(b(c.line),R(c.column),I(c.line))},[N,K,se,I]);const $=t.useCallback(()=>{K.length!==0&&Q(c=>(c+1)%K.length)},[K]),P=t.useCallback(()=>{K.length!==0&&Q(c=>(c-1+K.length)%K.length)},[K]),ee=t.useCallback(c=>{const G=o.current;if(!G)return;const ae=G.querySelector(".file-viewer-pre");if(!ae)return;const ce=parseFloat(getComputedStyle(ae).lineHeight),A=isNaN(ce)?h.current:ce,S=parseFloat(getComputedStyle(ae).paddingTop)||0,Z=ae.offsetTop+S+(c-1)*A,Te=Z+A,ve=G.scrollTop,X=ve+G.clientHeight;Z<ve?G.scrollTo({top:Math.max(0,Z),behavior:"auto"}):Te>X&&G.scrollTo({top:Te-G.clientHeight,behavior:"auto"})},[]),te=t.useCallback((c,G)=>{b(c),R(G),ee(c),x!=="none"&&D(ae=>ae?{...ae,headLine:c,headCol:G}:null)},[x,ee]),ge=t.useCallback(()=>{if(x==="none"||!C)return;const c=Da(d,p,C,x);c&&navigator.clipboard.writeText(c).catch(()=>{const G=document.createElement("textarea");G.value=c,G.style.position="fixed",G.style.left="-9999px",document.body.appendChild(G),G.select(),document.execCommand("copy"),document.body.removeChild(G)}),v("none"),D(null)},[x,C,d,p]),je=t.useCallback(c=>{const G=c.target;if((G.tagName==="INPUT"||G.tagName==="TEXTAREA")&&c.key!=="Escape")return;const ce=o.current;if(!ce)return;let A=!1;const S=h.current,q=Math.max(1,Math.floor(ce.clientHeight/S)),Z=Math.max(1,Math.floor(q/2)),Te=(X,xe)=>{const ze=Math.max(0,(p[X-1]||"").length-1);return Math.min(xe,Math.max(0,ze))},ve=(X,xe)=>{const ze=Te(X,xe);te(X,ze)};if(c.key==="v"&&!c.shiftKey&&!c.ctrlKey&&!N)c.preventDefault(),c.stopPropagation(),x==="char"?(v("none"),D(null)):(v("char"),D({anchorLine:f,anchorCol:w,headLine:f,headCol:w})),A=!0;else if(c.key==="V"&&c.shiftKey&&!c.ctrlKey&&!N)c.preventDefault(),c.stopPropagation(),x==="line"?(v("none"),D(null)):(v("line"),D({anchorLine:f,anchorCol:0,headLine:f,headCol:0})),A=!0;else if(c.key==="y"&&!c.ctrlKey&&x!=="none")c.preventDefault(),c.stopPropagation(),ge(),A=!0;else if(c.key==="j"||c.key==="ArrowDown"){c.preventDefault(),c.stopPropagation();const X=Math.min(f+1,j);ve(X,w),A=!0}else if(c.key==="k"||c.key==="ArrowUp"){c.preventDefault(),c.stopPropagation();const X=Math.max(f-1,1);ve(X,w),A=!0}else if(c.key==="d"&&c.ctrlKey||c.key==="d"&&x==="none"&&!N){c.preventDefault(),c.stopPropagation();const X=Math.min(f+Z,j);ve(X,w),A=!0}else if(c.key==="u"&&c.ctrlKey||c.key==="u"&&x==="none"&&!N){c.preventDefault(),c.stopPropagation();const X=Math.max(f-Z,1);ve(X,w),A=!0}else if((c.ctrlKey||c.metaKey)&&c.key==="f")c.preventDefault(),c.stopPropagation(),ie(),A=!0;else if(c.key==="f"&&!c.ctrlKey&&!c.metaKey&&x==="none"&&!N){c.preventDefault(),c.stopPropagation();const X=Math.min(f+q,j);ve(X,w),A=!0}else if(c.key===" "||c.key==="PageDown"){c.preventDefault(),c.stopPropagation();const X=Math.min(f+q,j);ve(X,w),A=!0}else if(c.key==="b"&&!g&&x==="none"&&!N||c.key==="PageUp"){c.preventDefault(),c.stopPropagation();const X=Math.max(f-q,1);ve(X,w),A=!0}else if(c.key==="g"&&!c.shiftKey&&x==="none"&&!N)c.preventDefault(),c.stopPropagation(),te(1,0),Xt(ce,!1),A=!0;else if(c.key==="Home")c.preventDefault(),c.stopPropagation(),te(1,0),Xt(ce,!1),A=!0;else if(c.key==="G"&&c.shiftKey||c.key==="End")c.preventDefault(),c.stopPropagation(),te(j,0),Xt(ce,!0),A=!0;else if(c.key==="h"||c.key==="ArrowLeft")c.preventDefault(),c.stopPropagation(),te(f,Math.max(0,w-1)),A=!0;else if(c.key==="l"||c.key==="ArrowRight"){c.preventDefault(),c.stopPropagation();const X=(p[f-1]||"").length;te(f,Math.min(w+1,Math.max(0,X-1))),A=!0}else if(c.key==="w"&&!c.ctrlKey&&!N){c.preventDefault(),c.stopPropagation();const X=Sa(p,f,w);te(X.line,X.col),A=!0}else if(c.key==="e"&&!c.ctrlKey&&!N){c.preventDefault(),c.stopPropagation();const X=Ta(p,f,w);te(X.line,X.col),A=!0}else if(c.key==="b"&&!N){c.preventDefault(),c.stopPropagation();const X=Ma(p,f,w);te(X.line,X.col),A=!0}else if(c.key==="0")c.preventDefault(),c.stopPropagation(),te(f,0),A=!0;else if(c.key==="$")c.preventDefault(),c.stopPropagation(),te(f,Math.max(0,(p[f-1]||"").length-1)),A=!0;else if(c.key==="^"){c.preventDefault(),c.stopPropagation();const xe=(p[f-1]||"").search(/\S/);te(f,xe>=0?xe:0),A=!0}else c.key==="/"?(c.preventDefault(),c.stopPropagation(),ie(),A=!0):c.key==="n"&&!N?(c.preventDefault(),c.stopPropagation(),$(),A=!0):c.key==="N"&&c.shiftKey&&!N?(c.preventDefault(),c.stopPropagation(),P(),A=!0):c.key==="?"&&x==="none"?(c.preventDefault(),c.stopPropagation(),z(),A=!0):c.key==="q"&&x==="none"?(c.preventDefault(),c.stopPropagation(),r==null||r(),A=!0):c.key==="Escape"&&(x!=="none"?(c.preventDefault(),c.stopPropagation(),v("none"),D(null),A=!0):N?(c.preventDefault(),c.stopPropagation(),fe(),A=!0):g&&(c.preventDefault(),c.stopPropagation(),k(!1),A=!0));A&&(c.key!=="Escape"&&!g&&k(!0),requestAnimationFrame(ne))},[r,ne,j,p,f,w,ee,N,fe,x,g,te,ge,ie,$,P,z]);return t.useEffect(()=>{if(!l)return;const c=Ca(n);if(o.current=c,!c){console.warn("[useLessNavigation] Could not find scrollable container");return}h.current=Js(c);const G=()=>{ne()};return window.addEventListener("keydown",je,{capture:!0}),c.addEventListener("scroll",G,{passive:!0}),ne(),()=>{window.removeEventListener("keydown",je,{capture:!0}),c.removeEventListener("scroll",G)}},[l,je,ne]),{scrollPercentage:m.current.percentage,currentLine:m.current.line,currentColumn:m.current.column,totalLines:j,cursorLine:f,cursorCol:w,cursorModeActive:g,visualMode:x,selection:C,searchActive:N,searchQuery:_,searchMatches:K,currentMatchIndex:se,startSearch:ie,setSearchQuery:O,nextMatch:$,prevMatch:P,clearSearch:fe,helpActive:T,toggleHelp:z}}const ss=({query:s,onQueryChange:n,matchCount:l,currentIndex:d,onNext:r,onPrev:i,onClose:m})=>{const{t:o}=re(["terminal"]),h=t.useRef(null);t.useEffect(()=>{var f;(f=h.current)==null||f.focus()},[]);const p=t.useCallback(f=>{f.stopPropagation(),f.key==="Enter"||f.key==="ArrowDown"?(f.preventDefault(),r()):f.key==="ArrowUp"&&(f.preventDefault(),i())},[r,i]),j=l===0&&s?o("terminal:fileExplorer.noMatches"):l>0?`${d+1}/${l}`:"";return e.jsxs("div",{className:"file-viewer-search-bar",children:[e.jsxs("div",{className:"file-viewer-search-input-wrapper",children:[e.jsx("span",{className:"file-viewer-search-prefix",children:"/"}),e.jsx("input",{ref:h,type:"text",className:"file-viewer-search-input",placeholder:o("terminal:fileExplorer.searchInFile"),value:s,onChange:f=>n(f.target.value),onKeyDown:p,autoComplete:"off",spellCheck:"false"})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"file-viewer-search-counter",children:j}),e.jsxs("div",{className:"file-viewer-search-nav",children:[e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-prev",onClick:i,disabled:l===0,title:o("terminal:fileExplorer.previousMatch"),"aria-label":o("terminal:fileExplorer.previousMatch"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:l===0,title:o("terminal:fileExplorer.nextMatch"),"aria-label":o("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:m,title:o("terminal:fileExplorer.closeSearch"),"aria-label":o("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};ss.displayName="SearchBar";const Ra=[{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"}],ns=({onClose:s})=>{const{t:n}=re(["terminal"]),l=t.useCallback(i=>{i.target===i.currentTarget&&s()},[s]),d=t.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),s())},[s]),r=Ra.reduce((i,m)=>(i[m.category]||(i[m.category]=[]),i[m.category].push(m),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:l,onKeyDown:d,tabIndex:0,role:"dialog","aria-label":n("terminal:fileExplorer.keybindingsHelp"),children:e.jsxs("div",{className:"keybindings-help-content",children:[e.jsx("button",{className:"keybindings-help-close",onClick:s,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(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,m])=>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:m.map((o,h)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:o.keys.map((p,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:p},j))}),e.jsx("div",{className:"keybindings-help-description",children:o.description})]},h))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};ns.displayName="KeybindingsHelp";const As=t.lazy(()=>Gn(()=>import("./EmbeddedEditor-BDzAm2JK.js"),__vite__mapDeps([0,1,2,3,4,5])).then(s=>({default:s.EmbeddedEditor}))),Fa=[".md",".mdx",".markdown"],Gs="file-viewer-markdown-render",Ia=[".puml",".plantuml",".iuml",".pu"],Us="file-viewer-plantuml-render",Pa="https://kroki.io/plantuml/svg";function La(s){return Fa.includes(s.toLowerCase())}function $a(s){return Ia.includes(s.toLowerCase())}function Ha(){const[s,n]=t.useState(()=>{try{const d=localStorage.getItem(Gs);return d===null?!0:d==="true"}catch{return!0}}),l=t.useCallback(()=>{n(d=>{const r=!d;try{localStorage.setItem(Gs,String(r))}catch{}return r})},[]);return[s,l]}function za(){const[s,n]=t.useState(()=>{try{const d=localStorage.getItem(Us);return d===null?!0:d==="true"}catch{return!0}}),l=t.useCallback(()=>{n(d=>{const r=!d;try{localStorage.setItem(Us,String(r))}catch{}return r})},[]);return[s,l]}function Oa(s){const n=new TextEncoder().encode(s);let l="";for(const d of n)l+=String.fromCharCode(d);return`data:image/svg+xml;base64,${window.btoa(l)}`}function Ve({file:s,rightContent:n,onRevealInTree:l,editMode:d,onToggleEdit:r}){const{t:i}=re(["terminal","common"]),[m,o]=t.useState("idle"),[h,p]=t.useState("idle"),[j,f]=t.useState("idle"),b=s.fileType==="text"?zt(s.extension):s.extension.slice(1).toUpperCase(),w=s.fileType==="text"&&s.content!=null,{settings:R}=Vs(),g=async()=>{try{await Pt(s.content),f("copied"),setTimeout(()=>f("idle"),2e3)}catch{f("error"),setTimeout(()=>f("idle"),2e3)}},k=()=>{const D=new Blob([s.content],{type:"text/plain;charset=utf-8"}),N=URL.createObjectURL(D),U=document.createElement("a");U.href=N,U.download=s.filename,document.body.appendChild(U),U.click(),U.remove(),setTimeout(()=>URL.revokeObjectURL(N),1e3)},x=async()=>{o("loading");try{const D=await W(V("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,...R.externalEditorCommand&&{editorCommand:R.externalEditorCommand}})});if(!D.ok){const N=await D.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",N),o("error"),setTimeout(()=>o("idle"),2e3);return}o("success"),setTimeout(()=>o("idle"),2e3)}catch(D){console.error("Error opening file in editor:",D),o("error"),setTimeout(()=>o("idle"),2e3)}},v=async()=>{if(s.path)try{await Kn(s.path),p("success"),setTimeout(()=>p("idle"),2e3)}catch(D){console.error("Error opening file explorer:",D),p("error"),setTimeout(()=>p("idle"),2e3)}},C=i("terminal:fileExplorer.openInFileExplorer");return e.jsxs("div",{className:"file-viewer-header",children:[e.jsxs("div",{className:"file-viewer-header-left",children:[e.jsx("span",{className:"file-viewer-filename",children:s.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[Ks(s.size)," • ",b,s.content&&` • ${s.content.split(`
|
|
7
|
+
`),[d]),j=p.length,[f,b]=t.useState(1),[w,R]=t.useState(0),[g,k]=t.useState(!1),[x,v]=t.useState("none"),[C,D]=t.useState(null),[N,U]=t.useState(!1),[_,O]=t.useState(""),[se,Q]=t.useState(0),[T,F]=t.useState(!1),K=t.useMemo(()=>Ea(d,_,!1),[d,_]),ne=t.useCallback(()=>{const c=o.current;if(!c)return;const G=Na(c),ae=ka(c,d),A=Math.max(1,Math.round(c.scrollLeft/7.8)+1);m.current={percentage:G,line:ae,column:A}},[d]),ie=t.useCallback(()=>{U(!0),O(""),Q(0),i==null||i()},[i]),fe=t.useCallback(()=>{U(!1),O(""),Q(0)},[]),z=t.useCallback(()=>{F(c=>!c)},[]),I=t.useCallback(c=>{const G=o.current;if(!G)return;const ae=G.querySelector(".file-viewer-pre"),ce=ae&&parseFloat(getComputedStyle(ae).lineHeight)||h.current,A=ae&&parseFloat(getComputedStyle(ae).paddingTop)||0,q=(ae?ae.offsetTop:0)+A+(c-1)*ce,Z=ce*3;G.scrollTo({top:Math.max(0,q-Z),behavior:"smooth"})},[]);t.useEffect(()=>{!N||K.length===0||Q(0)},[K,N]),t.useEffect(()=>{if(!N||K.length===0)return;const c=K[se];c&&(b(c.line),R(c.column),I(c.line))},[N,K,se,I]);const $=t.useCallback(()=>{K.length!==0&&Q(c=>(c+1)%K.length)},[K]),P=t.useCallback(()=>{K.length!==0&&Q(c=>(c-1+K.length)%K.length)},[K]),ee=t.useCallback(c=>{const G=o.current;if(!G)return;const ae=G.querySelector(".file-viewer-pre");if(!ae)return;const ce=parseFloat(getComputedStyle(ae).lineHeight),A=isNaN(ce)?h.current:ce,S=parseFloat(getComputedStyle(ae).paddingTop)||0,Z=ae.offsetTop+S+(c-1)*A,Te=Z+A,ve=G.scrollTop,X=ve+G.clientHeight;Z<ve?G.scrollTo({top:Math.max(0,Z),behavior:"auto"}):Te>X&&G.scrollTo({top:Te-G.clientHeight,behavior:"auto"})},[]),te=t.useCallback((c,G)=>{b(c),R(G),ee(c),x!=="none"&&D(ae=>ae?{...ae,headLine:c,headCol:G}:null)},[x,ee]),ge=t.useCallback(()=>{if(x==="none"||!C)return;const c=Da(d,p,C,x);c&&navigator.clipboard.writeText(c).catch(()=>{const G=document.createElement("textarea");G.value=c,G.style.position="fixed",G.style.left="-9999px",document.body.appendChild(G),G.select(),document.execCommand("copy"),document.body.removeChild(G)}),v("none"),D(null)},[x,C,d,p]),je=t.useCallback(c=>{const G=c.target;if((G.tagName==="INPUT"||G.tagName==="TEXTAREA")&&c.key!=="Escape")return;const ce=o.current;if(!ce)return;let A=!1;const S=h.current,q=Math.max(1,Math.floor(ce.clientHeight/S)),Z=Math.max(1,Math.floor(q/2)),Te=(X,xe)=>{const ze=Math.max(0,(p[X-1]||"").length-1);return Math.min(xe,Math.max(0,ze))},ve=(X,xe)=>{const ze=Te(X,xe);te(X,ze)};if(c.key==="v"&&!c.shiftKey&&!c.ctrlKey&&!N)c.preventDefault(),c.stopPropagation(),x==="char"?(v("none"),D(null)):(v("char"),D({anchorLine:f,anchorCol:w,headLine:f,headCol:w})),A=!0;else if(c.key==="V"&&c.shiftKey&&!c.ctrlKey&&!N)c.preventDefault(),c.stopPropagation(),x==="line"?(v("none"),D(null)):(v("line"),D({anchorLine:f,anchorCol:0,headLine:f,headCol:0})),A=!0;else if(c.key==="y"&&!c.ctrlKey&&x!=="none")c.preventDefault(),c.stopPropagation(),ge(),A=!0;else if(c.key==="j"||c.key==="ArrowDown"){c.preventDefault(),c.stopPropagation();const X=Math.min(f+1,j);ve(X,w),A=!0}else if(c.key==="k"||c.key==="ArrowUp"){c.preventDefault(),c.stopPropagation();const X=Math.max(f-1,1);ve(X,w),A=!0}else if(c.key==="d"&&c.ctrlKey||c.key==="d"&&x==="none"&&!N){c.preventDefault(),c.stopPropagation();const X=Math.min(f+Z,j);ve(X,w),A=!0}else if(c.key==="u"&&c.ctrlKey||c.key==="u"&&x==="none"&&!N){c.preventDefault(),c.stopPropagation();const X=Math.max(f-Z,1);ve(X,w),A=!0}else if((c.ctrlKey||c.metaKey)&&c.key==="f")c.preventDefault(),c.stopPropagation(),ie(),A=!0;else if(c.key==="f"&&!c.ctrlKey&&!c.metaKey&&x==="none"&&!N){c.preventDefault(),c.stopPropagation();const X=Math.min(f+q,j);ve(X,w),A=!0}else if(c.key===" "||c.key==="PageDown"){c.preventDefault(),c.stopPropagation();const X=Math.min(f+q,j);ve(X,w),A=!0}else if(c.key==="b"&&!g&&x==="none"&&!N||c.key==="PageUp"){c.preventDefault(),c.stopPropagation();const X=Math.max(f-q,1);ve(X,w),A=!0}else if(c.key==="g"&&!c.shiftKey&&x==="none"&&!N)c.preventDefault(),c.stopPropagation(),te(1,0),Xt(ce,!1),A=!0;else if(c.key==="Home")c.preventDefault(),c.stopPropagation(),te(1,0),Xt(ce,!1),A=!0;else if(c.key==="G"&&c.shiftKey||c.key==="End")c.preventDefault(),c.stopPropagation(),te(j,0),Xt(ce,!0),A=!0;else if(c.key==="h"||c.key==="ArrowLeft")c.preventDefault(),c.stopPropagation(),te(f,Math.max(0,w-1)),A=!0;else if(c.key==="l"||c.key==="ArrowRight"){c.preventDefault(),c.stopPropagation();const X=(p[f-1]||"").length;te(f,Math.min(w+1,Math.max(0,X-1))),A=!0}else if(c.key==="w"&&!c.ctrlKey&&!N){c.preventDefault(),c.stopPropagation();const X=Sa(p,f,w);te(X.line,X.col),A=!0}else if(c.key==="e"&&!c.ctrlKey&&!N){c.preventDefault(),c.stopPropagation();const X=Ta(p,f,w);te(X.line,X.col),A=!0}else if(c.key==="b"&&!N){c.preventDefault(),c.stopPropagation();const X=Ma(p,f,w);te(X.line,X.col),A=!0}else if(c.key==="0")c.preventDefault(),c.stopPropagation(),te(f,0),A=!0;else if(c.key==="$")c.preventDefault(),c.stopPropagation(),te(f,Math.max(0,(p[f-1]||"").length-1)),A=!0;else if(c.key==="^"){c.preventDefault(),c.stopPropagation();const xe=(p[f-1]||"").search(/\S/);te(f,xe>=0?xe:0),A=!0}else c.key==="/"?(c.preventDefault(),c.stopPropagation(),ie(),A=!0):c.key==="n"&&!N?(c.preventDefault(),c.stopPropagation(),$(),A=!0):c.key==="N"&&c.shiftKey&&!N?(c.preventDefault(),c.stopPropagation(),P(),A=!0):c.key==="?"&&x==="none"?(c.preventDefault(),c.stopPropagation(),z(),A=!0):c.key==="q"&&x==="none"?(c.preventDefault(),c.stopPropagation(),r==null||r(),A=!0):c.key==="Escape"&&(x!=="none"?(c.preventDefault(),c.stopPropagation(),v("none"),D(null),A=!0):N?(c.preventDefault(),c.stopPropagation(),fe(),A=!0):g&&(c.preventDefault(),c.stopPropagation(),k(!1),A=!0));A&&(c.key!=="Escape"&&!g&&k(!0),requestAnimationFrame(ne))},[r,ne,j,p,f,w,ee,N,fe,x,g,te,ge,ie,$,P,z]);return t.useEffect(()=>{if(!l)return;const c=Ca(n);if(o.current=c,!c){console.warn("[useLessNavigation] Could not find scrollable container");return}h.current=Js(c);const G=()=>{ne()};return window.addEventListener("keydown",je,{capture:!0}),c.addEventListener("scroll",G,{passive:!0}),ne(),()=>{window.removeEventListener("keydown",je,{capture:!0}),c.removeEventListener("scroll",G)}},[l,je,ne]),{scrollPercentage:m.current.percentage,currentLine:m.current.line,currentColumn:m.current.column,totalLines:j,cursorLine:f,cursorCol:w,cursorModeActive:g,visualMode:x,selection:C,searchActive:N,searchQuery:_,searchMatches:K,currentMatchIndex:se,startSearch:ie,setSearchQuery:O,nextMatch:$,prevMatch:P,clearSearch:fe,helpActive:T,toggleHelp:z}}const ss=({query:s,onQueryChange:n,matchCount:l,currentIndex:d,onNext:r,onPrev:i,onClose:m})=>{const{t:o}=re(["terminal"]),h=t.useRef(null);t.useEffect(()=>{var f;(f=h.current)==null||f.focus()},[]);const p=t.useCallback(f=>{f.stopPropagation(),f.key==="Enter"||f.key==="ArrowDown"?(f.preventDefault(),r()):f.key==="ArrowUp"&&(f.preventDefault(),i())},[r,i]),j=l===0&&s?o("terminal:fileExplorer.noMatches"):l>0?`${d+1}/${l}`:"";return e.jsxs("div",{className:"file-viewer-search-bar",children:[e.jsxs("div",{className:"file-viewer-search-input-wrapper",children:[e.jsx("span",{className:"file-viewer-search-prefix",children:"/"}),e.jsx("input",{ref:h,type:"text",className:"file-viewer-search-input",placeholder:o("terminal:fileExplorer.searchInFile"),value:s,onChange:f=>n(f.target.value),onKeyDown:p,autoComplete:"off",spellCheck:"false"})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"file-viewer-search-counter",children:j}),e.jsxs("div",{className:"file-viewer-search-nav",children:[e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-prev",onClick:i,disabled:l===0,title:o("terminal:fileExplorer.previousMatch"),"aria-label":o("terminal:fileExplorer.previousMatch"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:l===0,title:o("terminal:fileExplorer.nextMatch"),"aria-label":o("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:m,title:o("terminal:fileExplorer.closeSearch"),"aria-label":o("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};ss.displayName="SearchBar";const Ra=[{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"}],ns=({onClose:s})=>{const{t:n}=re(["terminal"]),l=t.useCallback(i=>{i.target===i.currentTarget&&s()},[s]),d=t.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),s())},[s]),r=Ra.reduce((i,m)=>(i[m.category]||(i[m.category]=[]),i[m.category].push(m),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:l,onKeyDown:d,tabIndex:0,role:"dialog","aria-label":n("terminal:fileExplorer.keybindingsHelp"),children:e.jsxs("div",{className:"keybindings-help-content",children:[e.jsx("button",{className:"keybindings-help-close",onClick:s,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(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,m])=>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:m.map((o,h)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:o.keys.map((p,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:p},j))}),e.jsx("div",{className:"keybindings-help-description",children:o.description})]},h))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};ns.displayName="KeybindingsHelp";const As=t.lazy(()=>Gn(()=>import("./EmbeddedEditor-DIo_5FuD.js"),__vite__mapDeps([0,1,2,3,4,5])).then(s=>({default:s.EmbeddedEditor}))),Fa=[".md",".mdx",".markdown"],Gs="file-viewer-markdown-render",Ia=[".puml",".plantuml",".iuml",".pu"],Us="file-viewer-plantuml-render",Pa="https://kroki.io/plantuml/svg";function La(s){return Fa.includes(s.toLowerCase())}function $a(s){return Ia.includes(s.toLowerCase())}function Ha(){const[s,n]=t.useState(()=>{try{const d=localStorage.getItem(Gs);return d===null?!0:d==="true"}catch{return!0}}),l=t.useCallback(()=>{n(d=>{const r=!d;try{localStorage.setItem(Gs,String(r))}catch{}return r})},[]);return[s,l]}function za(){const[s,n]=t.useState(()=>{try{const d=localStorage.getItem(Us);return d===null?!0:d==="true"}catch{return!0}}),l=t.useCallback(()=>{n(d=>{const r=!d;try{localStorage.setItem(Us,String(r))}catch{}return r})},[]);return[s,l]}function Oa(s){const n=new TextEncoder().encode(s);let l="";for(const d of n)l+=String.fromCharCode(d);return`data:image/svg+xml;base64,${window.btoa(l)}`}function Ve({file:s,rightContent:n,onRevealInTree:l,editMode:d,onToggleEdit:r}){const{t:i}=re(["terminal","common"]),[m,o]=t.useState("idle"),[h,p]=t.useState("idle"),[j,f]=t.useState("idle"),b=s.fileType==="text"?zt(s.extension):s.extension.slice(1).toUpperCase(),w=s.fileType==="text"&&s.content!=null,{settings:R}=Vs(),g=async()=>{try{await Pt(s.content),f("copied"),setTimeout(()=>f("idle"),2e3)}catch{f("error"),setTimeout(()=>f("idle"),2e3)}},k=()=>{const D=new Blob([s.content],{type:"text/plain;charset=utf-8"}),N=URL.createObjectURL(D),U=document.createElement("a");U.href=N,U.download=s.filename,document.body.appendChild(U),U.click(),U.remove(),setTimeout(()=>URL.revokeObjectURL(N),1e3)},x=async()=>{o("loading");try{const D=await W(V("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,...R.externalEditorCommand&&{editorCommand:R.externalEditorCommand}})});if(!D.ok){const N=await D.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",N),o("error"),setTimeout(()=>o("idle"),2e3);return}o("success"),setTimeout(()=>o("idle"),2e3)}catch(D){console.error("Error opening file in editor:",D),o("error"),setTimeout(()=>o("idle"),2e3)}},v=async()=>{if(s.path)try{await Kn(s.path),p("success"),setTimeout(()=>p("idle"),2e3)}catch(D){console.error("Error opening file explorer:",D),p("error"),setTimeout(()=>p("idle"),2e3)}},C=i("terminal:fileExplorer.openInFileExplorer");return e.jsxs("div",{className:"file-viewer-header",children:[e.jsxs("div",{className:"file-viewer-header-left",children:[e.jsx("span",{className:"file-viewer-filename",children:s.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[Ks(s.size)," • ",b,s.content&&` • ${s.content.split(`
|
|
8
8
|
`).length} lines`]})]}),e.jsxs("div",{className:"file-viewer-header-right",children:[r&&s.fileType==="text"&&e.jsx("button",{className:`file-viewer-edit-btn${d?" active":""}`,onClick:r,title:i(d?"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"})})}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:g,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:k,title:i("terminal:fileExplorer.downloadFileTitle"),children:i("common:buttons.download")})]}),e.jsx("button",{className:`file-viewer-reveal-explorer-btn ${h}`,onClick:v,disabled:!s.path,title:C,"aria-label":C,children:h==="success"?e.jsx(M,{name:"check",size:14}):h==="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 ${m}`,onClick:x,disabled:m==="loading",title:i(m==="error"?"terminal:fileExplorer.failedToOpenEditor":m==="success"?"terminal:fileExplorer.openingInEditor":"terminal:fileExplorer.openInEditor"),children:m==="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"})}):m==="error"?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"})}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M1.5 1h6v1.5h-5v11h11v-5H15v6.5H0V1h1.5zm8 0H15v5.5h-1.5V3.56L7.28 9.78l-1.06-1.06L12.44 2.5H9.5V1z"})})}),l&&e.jsx("button",{className:"file-viewer-locate-btn",onClick:()=>l(s.path),title:i("terminal:fileExplorer.locateInTree"),children:e.jsx(M,{name:"target",size:14})}),n]})]})}function Aa({file:s,onRevealInTree:n,renderMarkdown:l,onToggleRender:d,editMode:r,onToggleEdit:i}){const m=t.useRef(null),o=t.useRef(null),h=t.useRef(null),{t:p}=re(["terminal","common"]),[j,f]=t.useState("idle"),[b,w]=t.useState("idle"),[R,g]=t.useState("idle"),[k,x]=t.useState("idle"),v=Xs({containerRef:h,isEnabled:!0,content:s.content});t.useEffect(()=>{if(!l&&m.current){const O=zt(s.extension);Ws(O).then(()=>{m.current&&qs(m.current)})}},[s,l]);const C=t.useCallback(async()=>{if(!o.current){f("error"),setTimeout(()=>f("idle"),2e3);return}try{const O=o.current.innerHTML,se=Un(O),Q=o.current.innerText;await Bn(se,Q),f("copied"),setTimeout(()=>f("idle"),2e3)}catch{f("error"),setTimeout(()=>f("idle"),2e3)}},[]),D=t.useCallback(async()=>{if(!o.current){w("error"),setTimeout(()=>w("idle"),2e3);return}try{const O=o.current.innerHTML;await Pt(O),w("copied"),setTimeout(()=>w("idle"),2e3)}catch{w("error"),setTimeout(()=>w("idle"),2e3)}},[]),N=t.useCallback(async()=>{try{await Pt(s.content),g("copied"),setTimeout(()=>g("idle"),2e3)}catch{g("error"),setTimeout(()=>g("idle"),2e3)}},[s.content]),U=t.useCallback(async()=>{try{await Pt(s.content),x("copied"),setTimeout(()=>x("idle"),2e3)}catch{x("error"),setTimeout(()=>x("idle"),2e3)}},[s.content]),_=e.jsxs("div",{className:"file-viewer-header-buttons",children:[l&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:C,title:p("terminal:fileExplorer.copyRichTextTitle"),children:p(j==="copied"?"terminal:fileExplorer.copied":j==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyRichText")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${b}`,onClick:D,title:p("terminal:fileExplorer.copyHtmlTitle"),children:p(b==="copied"?"terminal:fileExplorer.copied":b==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyHtml")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${R}`,onClick:N,title:p("terminal:fileExplorer.copyMarkdownTitle"),children:p(R==="copied"?"terminal:fileExplorer.copied":R==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyMarkdown")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${k}`,onClick:U,title:p("terminal:fileExplorer.copyOriginalTitle"),children:p(k==="copied"?"terminal:fileExplorer.copied":k==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyOriginal")})]}),e.jsx("button",{className:`file-viewer-render-toggle ${l?"active":""}`,onClick:d,title:p(l?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderMarkdown"),children:l?"</>":"Aa"})]});return e.jsxs(e.Fragment,{children:[e.jsx(Ve,{file:s,onRevealInTree:n,rightContent:_,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:h,children:[l?e.jsx("div",{className:"file-viewer-markdown-wrapper",children:e.jsx("div",{className:"markdown-content",ref:o,children:e.jsx(_n,{remarkPlugins:[Vn],children:s.content})})}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:m,className:"language-markdown",children:s.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${v.currentLine}/${v.totalLines}`,children:v.scrollPercentage===100?"END":v.scrollPercentage===0?"TOP":`${v.scrollPercentage}%`}),v.searchActive&&e.jsx(ss,{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(ns,{onClose:v.toggleHelp})]})}function Ga({file:s,onRevealInTree:n,renderPlantUml:l,onToggleRender:d,editMode:r,onToggleEdit:i}){const{t:m}=re(["terminal"]),o=t.useRef(null),h=t.useRef(null),[p,j]=t.useState(null),[f,b]=t.useState(!1),[w,R]=t.useState(null),g=Xs({containerRef:h,isEnabled:!0,content:s.content});t.useEffect(()=>{if(!l&&o.current){const x=zt(s.extension);Ws(x).then(()=>{o.current&&qs(o.current)})}},[s,l]),t.useEffect(()=>{if(!l)return;if(!s.content.trim()){j(null),R("Diagram is empty");return}const x=new AbortController;return b(!0),R(null),(async()=>{try{const C=await fetch(Pa,{method:"POST",headers:{"Content-Type":"text/plain; charset=utf-8",Accept:"image/svg+xml"},body:s.content,signal:x.signal});if(!C.ok)throw new Error(`Render failed (${C.status})`);const D=await C.text();if(!D.includes("<svg"))throw new Error("Invalid SVG output");j(Oa(D))}catch(C){if(x.signal.aborted)return;const D=C instanceof Error?C.message:"Failed to render diagram";R(D),j(null)}finally{x.signal.aborted||b(!1)}})(),()=>x.abort()},[s.path,s.content,l]);const k=e.jsx("div",{className:"file-viewer-header-buttons",children:e.jsx("button",{className:`file-viewer-render-toggle ${l?"active":""}`,onClick:d,title:m(l?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderDiagram"),children:l?"</>":m("terminal:fileExplorer.diagram")})});return e.jsxs(e.Fragment,{children:[e.jsx(Ve,{file:s,onRevealInTree:n,rightContent:k,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:h,children:[l?e.jsxs("div",{className:"file-viewer-diagram-wrapper",children:[f&&e.jsx("div",{className:"file-viewer-placeholder",children:m("terminal:fileExplorer.renderingDiagram")}),!f&&p&&e.jsx("img",{src:p,alt:s.filename,className:"file-viewer-diagram-image"}),!f&&w&&e.jsxs("div",{className:"file-viewer-diagram-error",children:[e.jsxs("div",{children:[m("terminal:fileExplorer.couldNotRender"),": ",w]}),e.jsx("button",{className:"file-viewer-render-toggle",onClick:d,children:m("terminal:fileExplorer.showSource")})]})]}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:o,className:"language-plaintext",children:s.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${g.currentLine}/${g.totalLines}`,children:g.scrollPercentage===100?"END":g.scrollPercentage===0?"TOP":`${g.scrollPercentage}%`}),g.searchActive&&e.jsx(ss,{query:g.searchQuery,onQueryChange:g.setSearchQuery,matchCount:g.searchMatches.length,currentIndex:g.currentMatchIndex,onNext:g.nextMatch,onPrev:g.prevMatch,onClose:g.clearSearch})]}),g.helpActive&&e.jsx(ns,{onClose:g.toggleHelp})]})}function Ua({file:s,onRevealInTree:n}){const{t:l}=re(["common","terminal"]),d=()=>{if(s.dataUrl){const r=document.createElement("a");r.href=s.dataUrl,r.download=s.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ve,{file:s,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:d,title:l("common:buttons.download"),children:l("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-image-wrapper",children:s.dataUrl?e.jsx("img",{src:s.dataUrl,alt:s.filename,className:"file-viewer-image"}):e.jsx("div",{className:"file-viewer-placeholder",children:l("terminal:fileExplorer.failedToLoadImage")})})]})}function Ba({file:s,onRevealInTree:n}){const{t:l}=re(["common","terminal"]),d=()=>{if(s.dataUrl){const r=document.createElement("a");r.href=s.dataUrl,r.download=s.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ve,{file:s,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:d,title:l("common:buttons.download"),children:l("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-pdf-wrapper",children:s.dataUrl?e.jsx("iframe",{src:s.dataUrl,title:s.filename,className:"file-viewer-pdf"}):e.jsx("div",{className:"file-viewer-placeholder",children:l("terminal:fileExplorer.failedToLoadPdf")})})]})}function _a({file:s,onRevealInTree:n}){const{t:l}=re(["terminal","common"]),d=()=>{if(s.dataUrl){const i=document.createElement("a");i.href=s.dataUrl,i.download=s.filename,i.click()}},r=()=>{const i=s.extension.toLowerCase();return[".xlsx",".xls"].includes(i)?e.jsx(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(Ve,{file:s,onRevealInTree:n}),e.jsxs("div",{className:"file-viewer-binary",children:[e.jsx("div",{className:"file-viewer-binary-icon",children:r()}),e.jsx("div",{className:"file-viewer-binary-name",children:s.filename}),e.jsx("div",{className:"file-viewer-binary-size",children:Ks(s.size)}),e.jsx("div",{className:"file-viewer-binary-message",children:l("terminal:fileExplorer.cannotPreview")}),e.jsx("button",{className:"file-viewer-download-btn large",onClick:d,children:l("terminal:fileExplorer.downloadFile")})]})]})}function Va({file:s,loading:n,error:l,onRevealInTree:d,onFileEdited:r}){const{t:i}=re(["terminal","common"]),[m,o]=Ha(),[h,p]=za(),[j,f]=t.useState(!1);t.useEffect(()=>{f(!1)},[s==null?void 0:s.path]);const b=t.useCallback(async C=>{if(!s)return;const D=await W(V("/api/files/write"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,content:C})});if(!D.ok){const N=await D.json().catch(()=>({error:"Save failed"}));throw new Error(N.error||"Save failed")}},[s]),w=t.useCallback(()=>{f(C=>(C&&s&&(r==null||r(s.path)),!C))},[s,r]),R=t.useCallback(()=>{s&&(r==null||r(s.path))},[s,r]);if(n)return e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")});if(l)return e.jsx("div",{className:"file-viewer-placeholder error",children:l});if(!s)return e.jsxs("div",{className:"file-viewer-placeholder",children:[e.jsx("div",{className:"placeholder-icon",children:e.jsx(M,{name:"folder-open",size:32})}),e.jsx("div",{className:"placeholder-text",children:i("terminal:fileExplorer.selectFileToView")})]});const g=s.fileType||"text",k=g==="text"&&La(s.extension),x=g==="text"&&$a(s.extension),v=k||x;return v&&j&&s.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ve,{file:s,onRevealInTree:d,editMode:!0,onToggleEdit:w}),e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(As,{content:s.content,extension:s.extension,onSave:b,onCancel:w},s.path)})]}):g==="text"&&!v&&s.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ve,{file:s,onRevealInTree:d}),e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(As,{content:s.content,extension:s.extension,onSave:b,onCancel:R},s.path)})]}):e.jsxs("div",{className:"file-viewer-content",children:[k&&e.jsx(Aa,{file:s,onRevealInTree:d,renderMarkdown:m,onToggleRender:o,editMode:j,onToggleEdit:w}),x&&!k&&e.jsx(Ga,{file:s,onRevealInTree:d,renderPlantUml:h,onToggleRender:p,editMode:j,onToggleEdit:w}),g==="image"&&e.jsx(Ua,{file:s,onRevealInTree:d}),g==="pdf"&&e.jsx(Ba,{file:s,onRevealInTree:d}),g==="binary"&&e.jsx(_a,{file:s,onRevealInTree:d})]})}const Qs=t.memo(Va,(s,n)=>s.loading!==n.loading||s.error!==n.error?!1:s.file===null&&n.file===null?!0:s.file===null||n.file===null?!1:s.file.path===n.file.path&&s.file.content===n.file.content&&s.file.modified===n.file.modified);Qs.displayName="FileViewer";function Zs({text:s,query:n}){if(!n)return e.jsx(e.Fragment,{children:s});const l=Wn(s,n);if(l)return e.jsxs(e.Fragment,{children:[s.slice(0,l.start),e.jsx("mark",{className:"search-highlight",children:s.slice(l.start,l.end)}),s.slice(l.end)]});const d=n.toLowerCase(),i=s.toLowerCase().indexOf(d);return i===-1?e.jsx(e.Fragment,{children:s}):e.jsxs(e.Fragment,{children:[s.slice(0,i),e.jsx("mark",{className:"search-highlight",children:s.slice(i,i+n.length)}),s.slice(i+n.length)]})}const Ka=t.memo(function({node:n,query:l,isSelected:d,onSelect:r,lineNumber:i}){const m=n.isDirectory?null:es(n),o=n.path.split("/");o[o.length-1];const h=o.slice(0,-1).join("/");return e.jsxs("div",{className:`search-result-item ${d?"selected":""}`,onClick:()=>r(n),children:[n.isDirectory?e.jsx("span",{className:"search-result-icon",children:e.jsx(M,{name:"folder",size:14})}):m?e.jsx("span",{className:"search-result-icon",style:{backgroundImage:`url('${m}')`},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(Zs,{text:n.name,query:l}),i&&e.jsxs("span",{className:"search-result-line-badge",children:[":",i]})]}),e.jsx("span",{className:"search-result-path",children:h})]})]})}),Wa=t.memo(function({match:n,query:l,isSelected:d,onSelect:r}){const{t:i}=re(["terminal"]),m={name:n.name,path:n.path,isDirectory:!1,extension:n.extension},o=es(m),h=n.path.split("/"),p=h[h.length-1],j=h.slice(0,-1).join("/");return e.jsxs("div",{className:`content-search-item ${d?"selected":""}`,children:[e.jsxs("div",{className:`content-search-header ${d?"selected":""}`,onClick:()=>r(n.path),children:[o?e.jsx("span",{className:"content-search-icon",style:{backgroundImage:`url('${o}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"content-search-icon",children:e.jsx(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:p}),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((f,b)=>e.jsxs("div",{className:"content-search-match",onClick:()=>r(n.path,f.line),children:[e.jsx("span",{className:"content-search-line-num",children:f.line}),e.jsx("span",{className:"content-search-line-content",children:e.jsx(Zs,{text:f.content.trim(),query:l})})]},`${n.path}-${f.line}-${b}`)),n.matches.length>5&&e.jsxs("div",{className:"content-search-match",style:{opacity:.6,cursor:"default"},children:[e.jsx("span",{className:"content-search-line-num",children:"..."}),e.jsx("span",{className:"content-search-line-content",children:i("terminal:fileExplorer.moreMatches",{count:n.matches.length-5})})]})]})]})});function qa({filenameResults:s,contentResults:n,onSelectFile:l,onSelectContent:d,selectedPath:r,query:i,lineNumber:m}){const{t:o}=re(["terminal"]),h=s.length>0,p=n.length>0;return!h&&!p?e.jsx("div",{className:"search-no-results",children:o("terminal:fileExplorer.noMatchesFound")}):e.jsxs("div",{className:"unified-search-results",children:[h&&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:o("terminal:fileExplorer.files")}),e.jsx("span",{className:"unified-search-section-count",children:s.length})]}),e.jsx("div",{className:"unified-search-section-content",children:s.map(j=>e.jsx(Ka,{node:j,query:i,isSelected:r===j.path,onSelect:l,lineNumber:m},j.path))})]}),p&&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:o("terminal:fileExplorer.content")}),e.jsx("span",{className:"unified-search-section-count",children:o("terminal:fileExplorer.matchesInFiles",{matches:n.reduce((j,f)=>j+f.matches.length,0),files:n.length})})]}),e.jsx("div",{className:"unified-search-section-content",children:n.map(j=>e.jsx(Wa,{match:j,query:i,isSelected:r===j.path,onSelect:d},j.path))})]})]})}const en=t.memo(qa,(s,n)=>!(s.query!==n.query||s.selectedPath!==n.selectedPath||s.filenameResults.length!==n.filenameResults.length||s.contentResults.length!==n.contentResults.length));en.displayName="UnifiedSearchResults";const Ya=t.memo(function({file:n,isSelected:l,onSelect:d,onStage:r,isStaging:i,showDirPath:m,isChecked:o,onToggleCheck:h,onContextMenu:p,onDiscard:j}){const{t:f}=re(["terminal"]),b=n.status,w=yt[b],R=b==="deleted",g=b==="untracked"&&r,k=n.name.includes(".")?"."+n.name.split(".").pop():"",x=m&&n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"";return e.jsxs("div",{className:`git-file-item ${l?"selected":""}`,onClick:()=>!R&&d(n.path,b),onContextMenu:v=>{v.preventDefault(),p==null||p(v,n,b)},style:{cursor:R?"not-allowed":"pointer"},title:n.path,children:[h&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:o||!1,onChange:v=>{v.stopPropagation(),h(n.path)},onClick:v=>v.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:xt(k),alt:"file"}),e.jsxs("span",{className:"git-file-name",children:[n.name,x&&e.jsx("span",{className:"git-file-dir",children:x})]}),e.jsx("span",{className:"git-file-status",style:{color:w.color},children:w.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()]}),g&&e.jsx("button",{className:`git-stage-btn ${i?"staging":""}`,onClick:v=>{v.stopPropagation(),i||r(n.path)},title:f("terminal:fileExplorer.stageFile"),disabled:i,children:i?"...":"+"}),j&&e.jsx("button",{className:"git-discard-btn",onClick:v=>{v.stopPropagation(),j(n,b)},title:b==="untracked"||b==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}),Ja=16,Xa=22,Qa=t.memo(function s({node:n,depth:l,expandedDirs:d,onToggleDir:r,selectedPath:i,onSelect:m,onStage:o,stagingPaths:h,checkedFiles:p,onToggleCheck:j,onContextMenu:f,onDirContextMenu:b,onDiscard:w}){const{t:R}=re(["terminal"]),g=l*Ja;if(!n.isDirectory){const x=n.file.status,v=yt[x];return e.jsxs("div",{className:`git-file-item ${i===n.path?"selected":""}`,onClick:()=>x!=="deleted"&&m(n.file.path,x),onContextMenu:C=>{C.preventDefault(),f==null||f(C,n.file,x)},style:{paddingLeft:`${g+Xa}px`,cursor:x==="deleted"?"not-allowed":"pointer"},title:n.file.path,children:[j&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:(p==null?void 0:p.has(n.file.path))||!1,onChange:C=>{C.stopPropagation(),j(n.file.path)},onClick:C=>C.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:xt(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()]}),x==="untracked"&&o&&e.jsx("button",{className:`git-stage-btn ${h!=null&&h.has(n.path)?"staging":""}`,onClick:C=>{C.stopPropagation(),h!=null&&h.has(n.path)||o(n.file.path)},title:R("terminal:fileExplorer.stageFile"),disabled:h==null?void 0:h.has(n.path),children:h!=null&&h.has(n.path)?"...":"+"}),w&&e.jsx("button",{className:"git-discard-btn",onClick:C=>{C.stopPropagation(),w(n.file,x)},title:x==="untracked"||x==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}const k=d.has(n.path);return e.jsxs("div",{className:"tree-node-wrapper",children:[e.jsxs("div",{className:`tree-node directory ${k?"expanded":""}`,style:{paddingLeft:`${g}px`},onClick:()=>r(n.path),onContextMenu:x=>{x.preventDefault(),x.stopPropagation(),b==null||b(x,n)},children:[e.jsx("span",{className:`tree-arrow ${k?"expanded":""}`,children:e.jsx(M,{name:"caret-right",size:10})}),e.jsx("img",{className:"tree-folder-icon",src:k?"/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})})]}),k&&e.jsx("div",{className:"tree-children",children:n.children.map(x=>e.jsx(s,{node:x,depth:l+1,expandedDirs:d,onToggleDir:r,selectedPath:i,onSelect:m,onStage:o,stagingPaths:h,checkedFiles:p,onToggleCheck:j,onContextMenu:f,onDirContextMenu:b,onDiscard:w},x.path))})]})}),Qt=t.memo(function({groupLabel:n,groupIcon:l,groupColor:d,files:r,treeNodes:i,viewMode:m,selectedPath:o,expandedDirs:h,onToggleDir:p,onFileSelect:j,onStageFile:f,onStageAll:b,stagingPaths:w,checkedFiles:R,onToggleCheck:g,onContextMenu:k,onDirContextMenu:x,onDiscardFile:v,onDiscardAll:C}){const{t:D}=re(["terminal"]);if(r.length===0)return null;const N=r.some(O=>O.status==="untracked"),U=N&&b&&r.length>0,_=w?r.every(O=>w.has(O.path)):!1;return e.jsxs("div",{className:"git-status-group",children:[e.jsxs("div",{className:"git-status-group-header",style:{color:d},children:[e.jsx("span",{className:"git-status-badge",style:{background:d},children:l}),n," (",r.length,")",U&&e.jsx("button",{className:`git-stage-all-btn ${_?"staging":""}`,onClick:O=>{O.stopPropagation(),_||b()},title:D("terminal:fileExplorer.stageAllUntracked"),disabled:_,children:_?"...":D("terminal:fileExplorer.stageAll")}),C&&e.jsxs("button",{className:"git-discard-all-btn",onClick:O=>{O.stopPropagation(),C()},title:N?`Delete all ${r.length} files`:`Discard all ${r.length} changes`,children:[e.jsx(M,{name:"revert",size:12})," All"]})]}),m==="tree"?e.jsx("div",{className:"git-tree-content",children:i.map(O=>e.jsx(Qa,{node:O,depth:0,expandedDirs:h,onToggleDir:p,selectedPath:o,onSelect:j,onStage:f,stagingPaths:w,checkedFiles:R,onToggleCheck:g,onContextMenu:k,onDirContextMenu:x,onDiscard:v},O.path))}):e.jsx("div",{className:"git-flat-content",children:r.map(O=>e.jsx(Ya,{file:O,isSelected:o===O.path,onSelect:j,onStage:O.status==="untracked"?f:void 0,isStaging:w==null?void 0:w.has(O.path),showDirPath:!0,isChecked:R==null?void 0:R.has(O.path),onToggleCheck:g,onContextMenu:k,onDiscard:v},O.path))})]})});function Za({gitStatus:s,loading:n,onFileSelect:l,selectedPath:d,onRefresh:r,onStageFiles:i,stagingPaths:m,currentFolder:o,onCommitComplete:h,mergeInProgress:p,mergingBranch:j,onMergeContinue:f,onMergeAbort:b,onConflictOpen:w,onRevealInTree:R}){const{t:g}=re(["terminal","common"]),[k,x]=t.useState("tree"),[v,C]=t.useState(new Set),[D,N]=t.useState(""),[U,_]=t.useState(""),[O,se]=t.useState(!1),[Q,T]=t.useState(new Set),[F,K]=t.useState(!1),[ne,ie]=t.useState(null),fe=t.useRef(null),{showToast:z}=Ys(),[I,$]=t.useState(null),[P,ee]=t.useState(null),[te,ge]=t.useState(null),je=t.useCallback((E,L)=>{ge({files:[E],label:E.name})},[]),c=t.useCallback(async()=>{if(!(!te||!o))try{const E=await W(V("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:te.files.map(B=>({path:B.path,status:B.status})),directory:o})}),L=await E.json();E.ok&&L.success?(z("success","Discarded",`Reverted ${te.files.length} file(s)`),r()):z("error","Discard Failed",L.error||"Could not discard changes")}catch{z("error","Discard Failed","Network error")}finally{ge(null)}},[te,o,r,z]),G=t.useCallback((E,L,B)=>{E.preventDefault(),E.stopPropagation(),$({isOpen:!0,position:{x:E.clientX,y:E.clientY},file:L,status:B})},[]),ae=t.useCallback(async(E,L)=>{if(o)try{const B=await W(V("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{path:E.path,status:L}],directory:o})}),pe=await B.json();B.ok&&pe.success?(z("success","Discarded",`Restored ${E.name}`),r()):z("error","Discard Failed",pe.error||"Could not discard changes")}catch{z("error","Discard Failed","Network error")}},[o,r,z]),ce=t.useCallback(async E=>{try{await navigator.clipboard.writeText(E),z("success","Copied","Full path copied")}catch{z("error","Copy Failed","Could not copy path")}},[z]),A=t.useCallback(async E=>{const L=o&&E.startsWith(o+"/")?E.slice(o.length+1):E;try{await navigator.clipboard.writeText(L),z("success","Copied","Relative path copied")}catch{z("error","Copy Failed","Could not copy path")}},[o,z]),S=t.useMemo(()=>{if(!I)return[];const{file:E,status:L}=I,B=[];return L==="conflict"&&w?B.push({id:"open-conflict",label:g("terminal:fileExplorer.gitContextMenu.openConflictResolver"),icon:e.jsx(M,{name:"warn",size:14}),onClick:()=>w(E.path)}):L!=="deleted"&&B.push({id:"open-file",label:g("terminal:fileExplorer.gitContextMenu.openFile"),icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>l(E.path,L)}),L!=="conflict"&&B.push({id:"stage-file",label:g("terminal:fileExplorer.gitContextMenu.stageFile"),icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i([E.path])}}),B.push({id:"divider-1",label:"",divider:!0,onClick:()=>{}}),(L==="modified"||L==="deleted"||L==="renamed"||L==="conflict")&&B.push({id:"discard-changes",label:g("terminal:fileExplorer.gitContextMenu.discardChanges"),icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{ae(E,L)}}),(L==="untracked"||L==="added")&&B.push({id:"delete-file",label:g("terminal:fileExplorer.gitContextMenu.deleteFile"),icon:e.jsx(M,{name:"trash",size:14}),danger:!0,onClick:()=>{ae(E,L)}}),B.push({id:"divider-2",label:"",divider:!0,onClick:()=>{}}),B.push({id:"copy-full-path",label:g("terminal:fileExplorer.gitContextMenu.copyFullPath"),icon:e.jsx(M,{name:"pin",size:14}),onClick:()=>{ce(E.path)}}),B.push({id:"copy-relative-path",label:g("terminal:fileExplorer.gitContextMenu.copyRelativePath"),icon:e.jsx(M,{name:"clipboard",size:14}),onClick:()=>{A(E.path)}}),R&&L!=="deleted"&&B.push({id:"reveal-in-tree",label:g("terminal:fileExplorer.gitContextMenu.revealInTree"),icon:e.jsx(M,{name:"target",size:14}),onClick:()=>R(E.path)}),B},[I,l,i,w,R,ae,ce,A,g]),q=t.useCallback((E,L)=>{E.preventDefault(),E.stopPropagation(),ee({isOpen:!0,position:{x:E.clientX,y:E.clientY},node:L})},[]),Z=t.useCallback(E=>!E.isDirectory&&E.file?[E.file]:E.children.flatMap(L=>Z(L)),[]),Te=t.useCallback(async E=>{if(!o)return;const L=Z(E);if(L.length!==0)try{const B=await W(V("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:L.map(ye=>({path:ye.path,status:ye.status})),directory:o})}),pe=await B.json();B.ok&&pe.success?(z("success","Discarded",`Reverted ${L.length} file(s) in ${E.name}`),r()):z("error","Discard Failed",pe.error||"Could not discard changes")}catch{z("error","Discard Failed","Network error")}},[o,Z,r,z]),ve=t.useMemo(()=>{if(!P)return[];const{node:E}=P,L=Z(E);return[{id:"discard-dir",label:`Discard Changes (${L.length} files)`,icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{Te(E)}},{id:"stage-dir",label:`Stage All (${L.length} files)`,icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i(L.map(B=>B.path))}}]},[P,Z,Te,i]),X=t.useCallback(E=>{C(L=>{const B=new Set(L);return B.has(E)?B.delete(E):B.add(E),B})},[]),{conflictFiles:xe,conflictTree:ze,changesFiles:Le,changesTree:bt,untrackedFiles:de,untrackedTree:ue,allDirPaths:Ee}=t.useMemo(()=>{if(!s||!s.isGitRepo||s.files.length===0)return{conflictFiles:[],conflictTree:[],changesFiles:[],changesTree:[],untrackedFiles:[],untrackedTree:[],allDirPaths:new Set};const E=new Set,L=s.files.filter(De=>De.status==="conflict"),B=Lt(L);$t(B,E);const pe=s.files.filter(De=>De.status==="modified"||De.status==="added"||De.status==="deleted"||De.status==="renamed"),ye=Lt(pe);$t(ye,E);const Je=s.files.filter(De=>De.status==="untracked"),$e=Lt(Je);return $t($e,E),{conflictFiles:L,conflictTree:B,changesFiles:pe,changesTree:ye,untrackedFiles:Je,untrackedTree:$e,allDirPaths:E}},[s]);t.useEffect(()=>{C(Ee)},[Ee]),t.useEffect(()=>{s!=null&&s.files&&T(new Set(s.files.map(E=>E.path)))},[s==null?void 0:s.files]);const we=t.useCallback(()=>{Le.length!==0&&ge({files:Le,label:`${Le.length} changed files`})},[Le]),Ke=t.useCallback(()=>{de.length!==0&&ge({files:de,label:`${de.length} unversioned files`})},[de]),Oe=t.useCallback(()=>{xe.length!==0&&ge({files:xe,label:`${xe.length} conflicted files`})},[xe]),jt=xe.length>0;t.useEffect(()=>{if(ne){const E=ne.type==="error"?8e3:4e3,L=setTimeout(()=>ie(null),E);return()=>clearTimeout(L)}},[ne]);const We=t.useCallback(async()=>{const E=!O;if(se(E),E&&o){_(D);try{const B=await(await W(V(`/api/files/git-log-message?path=${encodeURIComponent(o)}`))).json();B.message&&N(B.message)}catch{}}else N(U)},[O,o,D,U]),ut=t.useCallback(E=>{T(L=>{const B=new Set(L);return B.has(E)?B.delete(E):B.add(E),B})},[]),qe=t.useCallback(()=>{if(!(s!=null&&s.files))return;const E=s.files.map(B=>B.path),L=E.every(B=>Q.has(B));T(L?new Set:new Set(E))},[s==null?void 0:s.files,Q]),Ye=t.useCallback(async E=>{if(!(!o||!D.trim()||Q.size===0||F)){K(!0),ie(null);try{const L=await W(V("/api/files/git-commit"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:o,message:D.trim(),amend:O,paths:Array.from(Q)})}),B=await L.json();if(!L.ok||!B.success){ie({type:"error",text:B.error||"Commit failed"}),K(!1);return}if(E)try{const pe=await W(V("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:o})}),ye=await pe.json();pe.ok&&ye.success?ie({type:"success",text:g("terminal:fileExplorer.committedAndPushed")}):ie({type:"error",text:g("terminal:fileExplorer.committedButPushFailed",{error:ye.error||"Unknown error"})})}catch{ie({type:"error",text:g("terminal:fileExplorer.committedButPushFailed",{error:"Network error"})})}else ie({type:"success",text:g("terminal:fileExplorer.committedSuccessfully")});N(""),_(""),se(!1),r(),h==null||h()}catch(L){ie({type:"error",text:L.message||"Commit failed"})}finally{K(!1)}}},[o,D,O,Q,F,r,h]);if(n)return e.jsx("div",{className:"git-changes-loading",children:g("terminal:fileExplorer.loadingGitStatus")});if(!s||!s.isGitRepo)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{name:"package",size:32})}),e.jsx("div",{className:"git-empty-text",children:g("terminal:fileExplorer.notGitRepo")})]});if(s.files.length===0)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{name:"sparkle",size:32})}),e.jsx("div",{className:"git-empty-text",children:g("terminal:fileExplorer.workingTreeClean")}),e.jsx("div",{className:"git-empty-branch",children:g("terminal:fileExplorer.onBranch",{branch:s.branch})})]});const ht=E=>{i([E])},vt=()=>{const E=de.map(L=>L.path);E.length>0&&i(E)},Ce=(E,L)=>{L==="conflict"&&w?w(E):l(E,L)};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})}),s.branch]}),s.counts&&e.jsxs("div",{className:"git-changes-summary",children:[(s.counts.conflict??0)>0&&e.jsxs("span",{className:"git-count conflict",children:[s.counts.conflict,"C"]}),s.counts.modified>0&&e.jsxs("span",{className:"git-count modified",children:[s.counts.modified,"M"]}),s.counts.added>0&&e.jsxs("span",{className:"git-count added",children:[s.counts.added,"A"]}),s.counts.deleted>0&&e.jsxs("span",{className:"git-count deleted",children:[s.counts.deleted,"D"]}),s.counts.untracked>0&&e.jsxs("span",{className:"git-count untracked",children:[s.counts.untracked,"?"]})]}),e.jsxs("div",{className:"git-view-toggle",children:[e.jsx("button",{className:`git-view-toggle-btn ${k==="flat"?"active":""}`,onClick:()=>x("flat"),title:g("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 ${k==="tree"?"active":""}`,onClick:()=>x("tree"),title:g("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:g("common:buttons.refresh"),children:e.jsx(M,{name:"refresh",size:12})})]}),p&&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:g("terminal:fileExplorer.mergeInProgress",{branch:j?` (${j})`:""})}),e.jsxs("div",{className:"git-merge-actions",children:[e.jsx("button",{className:"git-merge-continue-btn",onClick:f,disabled:jt,title:g(jt?"terminal:fileExplorer.resolveAllConflictsFirst":"terminal:fileExplorer.continueMerge"),children:g("terminal:fileExplorer.continue")}),e.jsx("button",{className:"git-merge-abort-btn",onClick:b,title:g("terminal:fileExplorer.abortMerge"),children:g("terminal:fileExplorer.abort")})]})]}),e.jsxs("div",{className:"git-changes-list",children:[e.jsx(Qt,{groupLabel:g("terminal:fileExplorer.gitGroups.conflicts"),groupIcon:"C",groupColor:"#ff5555",files:xe,treeNodes:ze,viewMode:k,selectedPath:d,expandedDirs:v,onToggleDir:X,onFileSelect:Ce,checkedFiles:Q,onToggleCheck:ut,onContextMenu:G,onDirContextMenu:q,onDiscardFile:je,onDiscardAll:Oe}),e.jsx(Qt,{groupLabel:g("terminal:fileExplorer.gitGroups.changes"),groupIcon:"~",groupColor:"#c89a5a",files:Le,treeNodes:bt,viewMode:k,selectedPath:d,expandedDirs:v,onToggleDir:X,onFileSelect:Ce,checkedFiles:Q,onToggleCheck:ut,onContextMenu:G,onDirContextMenu:q,onDiscardFile:je,onDiscardAll:we}),e.jsx(Qt,{groupLabel:g("terminal:fileExplorer.gitGroups.unversioned"),groupIcon:"?",groupColor:"#6ab8c8",files:de,treeNodes:ue,viewMode:k,selectedPath:d,expandedDirs:v,onToggleDir:X,onFileSelect:Ce,onStageFile:ht,onStageAll:vt,stagingPaths:m,checkedFiles:Q,onToggleCheck:ut,onContextMenu:G,onDirContextMenu:q,onDiscardFile:je,onDiscardAll:Ke})]}),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:O,onChange:We}),g("terminal:fileExplorer.amend")]}),e.jsx("span",{className:"git-commit-file-count",children:g("terminal:fileExplorer.fileCount",{count:Q.size})}),e.jsx("button",{className:"git-commit-select-toggle",onClick:qe,title:Q.size===s.files.length?g("terminal:fileExplorer.deselectAll"):g("terminal:fileExplorer.selectAll"),children:Q.size===s.files.length?g("terminal:fileExplorer.deselectAll"):g("terminal:fileExplorer.selectAll")})]}),e.jsx("textarea",{ref:fe,className:"git-commit-message",placeholder:g("terminal:fileExplorer.commitMessagePlaceholder"),value:D,onChange:E=>N(E.target.value),onKeyDown:E=>{(E.metaKey||E.ctrlKey)&&E.key==="Enter"&&(E.preventDefault(),Ye(!1)),(E.metaKey||E.ctrlKey)&&E.shiftKey&&E.key==="Enter"&&(E.preventDefault(),Ye(!0)),E.stopPropagation()},rows:3,disabled:F}),ne&&e.jsx("div",{className:`git-commit-status ${ne.type}`,children:ne.text}),e.jsxs("div",{className:"git-commit-actions",children:[e.jsx("button",{className:"git-commit-btn",onClick:()=>Ye(!1),disabled:!D.trim()||Q.size===0||F,title:g("terminal:fileExplorer.commitCtrlEnter"),children:g(F?"terminal:fileExplorer.committing":"terminal:fileExplorer.commitAction")}),e.jsx("button",{className:"git-commit-push-btn",onClick:()=>Ye(!0),disabled:!D.trim()||Q.size===0||F,title:g("terminal:fileExplorer.commitAndPushCtrlShiftEnter"),children:F?"...":g("terminal:fileExplorer.commitAndPush")})]})]}),I&&e.jsx(ct,{isOpen:I.isOpen,position:I.position,worldPosition:{x:0,z:0},actions:S,onClose:()=>$(null)}),P&&e.jsx(ct,{isOpen:P.isOpen,position:P.position,worldPosition:{x:0,z:0},actions:ve,onClose:()=>ee(null)}),te&&e.jsx("div",{className:"git-discard-confirm-overlay",onClick:()=>ge(null),children:e.jsxs("div",{className:"git-discard-confirm",onClick:E=>E.stopPropagation(),children:[e.jsx("p",{children:te.files.some(E=>E.status==="untracked"||E.status==="added")?e.jsxs(e.Fragment,{children:["Delete ",e.jsx("strong",{children:te.label}),"?"]}):e.jsxs(e.Fragment,{children:["Discard changes to ",e.jsx("strong",{children:te.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:()=>ge(null),children:"Cancel"}),e.jsx("button",{className:"git-discard-confirm-btn",onClick:c,children:te.files.some(E=>E.status==="untracked"||E.status==="added")?"Delete":"Discard"})]})]})})]})}const tn=t.memo(Za,(s,n)=>s.loading!==n.loading||s.selectedPath!==n.selectedPath||s.stagingPaths!==n.stagingPaths||s.currentFolder!==n.currentFolder||s.mergeInProgress!==n.mergeInProgress||s.mergingBranch!==n.mergingBranch?!1:s.gitStatus===null&&n.gitStatus===null?!0:!(s.gitStatus===null||n.gitStatus===null||s.gitStatus.isGitRepo!==n.gitStatus.isGitRepo||s.gitStatus.branch!==n.gitStatus.branch||s.gitStatus.files.length!==n.gitStatus.files.length||s.gitStatus.mergeInProgress!==n.gitStatus.mergeInProgress));tn.displayName="GitChanges";const er=t.memo(function({tab:n,isActive:l,onSelect:d,onClose:r,onContextMenu:i}){const{t:m}=re(["terminal"]),o={name:n.filename,path:n.path,isDirectory:!1,extension:n.extension},h=t.useCallback(()=>{d(n.path)},[d,n.path]),p=t.useCallback(b=>{b.button===1&&(b.preventDefault(),b.stopPropagation(),r(n.path))},[r,n.path]),j=t.useCallback(b=>{b.preventDefault(),b.stopPropagation(),r(n.path)},[r,n.path]),f=t.useCallback(b=>{b.preventDefault(),b.stopPropagation(),i(b,n)},[i,n]);return e.jsxs("div",{className:`file-tab ${l?"active":""}`,onClick:h,onMouseDown:p,onContextMenu:f,title:n.path,children:[e.jsx("img",{className:"file-tab-icon",src:es(o),alt:"file"}),e.jsx("span",{className:"file-tab-name",children:n.filename}),e.jsx("button",{className:"file-tab-close",onClick:j,title:m("terminal:fileExplorer.closeMiddleClick"),children:"×"})]})});function tr(s){return typeof s.path=="string"&&s.path.startsWith("/")}function sr({tabs:s,activeTabPath:n,onSelectTab:l,onCloseTab:d,onCloseAllTabs:r,onShowGitHistory:i}){const{t:m}=re(["terminal"]),[o,h]=t.useState(null),p=t.useCallback((b,w)=>{h({isOpen:!0,position:{x:b.clientX,y:b.clientY},tab:w})},[]),j=t.useCallback(()=>h(null),[]),f=t.useMemo(()=>{if(!o)return[];const b=o.tab,w=!!i&&tr(b),R=[{id:"git-history",label:m("terminal:fileExplorer.showGitHistory")??"Show Git History",icon:e.jsx(M,{name:"git-commit",size:14}),disabled:!w,onClick:()=>{w&&i(b.path)}}];return r&&R.push({id:"divider-close-all",label:"",divider:!0,onClick:()=>{}},{id:"close-all-tabs",label:m("terminal:fileExplorer.closeAllTabs")??"Close all tabs",icon:e.jsx(M,{name:"cross",size:14}),danger:!0,onClick:()=>r()}),R},[o,i,r,m]);return s.length===0?null:e.jsxs("div",{className:"file-tabs-bar",children:[e.jsx("div",{className:"file-tabs-container",children:s.map(b=>e.jsx(er,{tab:b,isActive:n===b.path,onSelect:l,onClose:d,onContextMenu:p},b.path))}),o&&e.jsx(ct,{isOpen:o.isOpen,position:o.position,worldPosition:{x:0,z:0},actions:f,onClose:j})]})}const sn=t.memo(sr,(s,n)=>{if(s.activeTabPath!==n.activeTabPath||s.tabs.length!==n.tabs.length||s.onShowGitHistory!==n.onShowGitHistory||s.onCloseAllTabs!==n.onCloseAllTabs)return!1;for(let l=0;l<s.tabs.length;l++)if(s.tabs[l].path!==n.tabs[l].path)return!1;return!0});sn.displayName="FileTabs";const nr=t.memo(function({currentFolder:n,gitStatus:l,onBranchChanged:d,onMerge:r,onCompare:i,onPullConflicts:m}){const{t:o}=re(["terminal","common"]),[h,p]=t.useState(!1),[j,f]=t.useState(""),[b,w]=t.useState(!1),[R,g]=t.useState(""),[k,x]=t.useState(!1),[v,C]=t.useState(null),[D,N]=t.useState(null),U=t.useRef(null),_=t.useRef(null),O=t.useRef(null),{branches:se,loading:Q,operationInProgress:T,loadBranches:F,checkoutBranch:K,createBranch:ne,pullFromRemote:ie,pushToRemote:fe}=ts();t.useEffect(()=>{h&&n&&(F(n),setTimeout(()=>{var S;return(S=_.current)==null?void 0:S.focus()},50)),h||(f(""),w(!1),g(""),C(null))},[h,n,F]),t.useEffect(()=>{if(v){const S=v.type==="error"?8e3:3e3,q=setTimeout(()=>C(null),S);return()=>clearTimeout(q)}},[v]),t.useEffect(()=>{b&&setTimeout(()=>{var S;return(S=O.current)==null?void 0:S.focus()},50)},[b]),t.useEffect(()=>{if(!h)return;const S=Z=>{const Te=Z.target;!Te.closest(".branch-widget-selector")&&!Te.closest(".branch-widget-dropdown")&&p(!1)},q=Z=>{Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),p(!1))};return document.addEventListener("click",S),document.addEventListener("keydown",q,!0),()=>{document.removeEventListener("click",S),document.removeEventListener("keydown",q,!0)}},[h]);const z=t.useCallback(async S=>{if(!n||T||S.isCurrent)return;const q=await K(n,S.name);q.success?(C({type:"success",text:o("terminal:fileExplorer.switchedToBranch",{branch:q.branch||S.name})}),d(),F(n)):C({type:"error",text:q.error||o("terminal:fileExplorer.checkoutFailed")})},[n,T,K,d,F]),I=t.useCallback(async()=>{if(!n||!R.trim()||T)return;const S=await ne(n,R.trim());S.success?(C({type:"success",text:o("terminal:fileExplorer.createdBranch",{branch:S.branch})}),w(!1),g(""),d(),F(n)):C({type:"error",text:S.error||o("terminal:fileExplorer.createBranchFailed")})},[n,R,T,ne,d,F]),$=t.useCallback(async()=>{if(!n||T)return;const S=await ie(n);S.success?(S.stashConflicts&&S.stashConflicts.length>0?(C({type:"error",text:`Pull succeeded but stash pop had conflicts: ${S.stashConflicts.length} file(s). Resolve manually.`}),m==null||m(S.stashConflicts),p(!1)):S.stashed?C({type:"success",text:"Pull complete. Local changes were auto-stashed and restored."}):C({type:"success",text:o("terminal:fileExplorer.pullComplete")}),d(),F(n)):S.conflicts&&S.conflicts.length>0?(C({type:"error",text:`Pull conflicts: ${S.conflicts.length} file(s)`}),m==null||m(S.conflicts),p(!1)):C({type:"error",text:S.error||o("terminal:fileExplorer.pullFailed")})},[n,T,ie,d,F,m]),P=t.useCallback(async()=>{if(!n||T)return;const S=await fe(n);S.success?C({type:"success",text:o("terminal:fileExplorer.pushComplete")}):C({type:"error",text:S.error||o("terminal:fileExplorer.pushFailed")})},[n,T,fe]),[ee,te]=t.useState(!1),ge=t.useCallback(async()=>{if(!(!n||T||ee)){te(!0);try{const S=await W(V("/api/files/git-fetch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(S.ok)C({type:"success",text:"Fetch complete"}),d(),F(n);else{const q=await S.json().catch(()=>({error:"Fetch failed"}));C({type:"error",text:q.error||"Fetch failed"})}}catch{C({type:"error",text:"Fetch failed"})}finally{te(!1)}}},[n,T,ee,d,F]),je=(l==null?void 0:l.branch)||"unknown",c=!!T,G=t.useCallback((S,q)=>{q.isCurrent||(S.preventDefault(),S.stopPropagation(),N({isOpen:!0,position:{x:S.clientX,y:S.clientY},branch:q.name}))},[]),ae=t.useMemo(()=>{if(!D)return[];const S=!!T||(l==null?void 0:l.mergeInProgress);return[{id:"compare",label:o("terminal:fileExplorer.showDiffWith",{branch:D.branch}),icon:e.jsx(M,{name:"arrows-horizontal",size:14}),disabled:!!T,onClick:()=>{i==null||i(D.branch),p(!1)}},{id:"merge",label:o("terminal:fileExplorer.mergeInto",{source:D.branch,target:je}),icon:"⤵",disabled:!!S,onClick:()=>{r&&r(D.branch),p(!1)}},{id:"divider-1",label:"",divider:!0,onClick:()=>{}},{id:"checkout",label:o("terminal:fileExplorer.checkoutBranch",{branch:D.branch}),icon:e.jsx(M,{name:"git-branch",size:14}),disabled:!!T,onClick:()=>{const q=se.find(Z=>Z.name===D.branch);q&&z(q)}}]},[D,T,l==null?void 0:l.mergeInProgress,je,r,i,se,z]),ce=t.useMemo(()=>{const S=se.filter(Z=>!Z.isRemote);if(!j)return S;const q=j.toLowerCase();return S.filter(Z=>Z.name.toLowerCase().includes(q))},[se,j]),A=t.useMemo(()=>{const S=se.filter(Z=>Z.isRemote);if(!j)return S;const q=j.toLowerCase();return S.filter(Z=>Z.name.toLowerCase().includes(q))},[se,j]);return e.jsxs("div",{className:"branch-widget",style:{position:"relative"},children:[e.jsxs("div",{className:"branch-widget-selector",onClick:S=>{S.stopPropagation(),p(!h)},title:`Branch: ${je}`,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:je}),e.jsx("span",{className:"branch-widget-arrow",children:"▼"})]}),h&&e.jsxs("div",{className:"branch-widget-dropdown",ref:U,children:[e.jsx("div",{className:"branch-widget-search",children:e.jsx("input",{ref:_,type:"text",className:"branch-widget-search-input",placeholder:o("terminal:fileExplorer.searchBranches"),value:j,onChange:S=>f(S.target.value),onKeyDown:S=>S.stopPropagation()})}),v&&e.jsx("div",{className:`branch-widget-status ${v.type}`,children:v.text}),e.jsx("div",{className:"branch-widget-section-header",children:o("terminal:fileExplorer.actions")}),e.jsxs("div",{className:"branch-widget-actions",children:[e.jsxs("div",{className:`branch-widget-action-item ${c||ee?"disabled":""}`,onClick:ge,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:ee?"Fetching...":"Fetch"})]}),e.jsxs("div",{className:`branch-widget-action-item ${c?"disabled":""}`,onClick:$,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 12l-4-4h2.5V3h3v5H12L8 12z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:o(T==="pull"?"terminal:fileExplorer.pulling":"terminal:fileExplorer.pull")})]}),e.jsxs("div",{className:`branch-widget-action-item ${c?"disabled":""}`,onClick:P,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 4l4 4h-2.5v5h-3V8H4l4-4z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:o(T==="push"?"terminal:fileExplorer.pushing":"terminal:fileExplorer.push")})]}),e.jsxs("div",{className:`branch-widget-action-item ${c?"disabled":""}`,onClick:()=>{c||w(!b)},children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 2v5H3v2h5v5h2V9h5V7H10V2H8z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:o("terminal:fileExplorer.newBranch")})]})]}),b&&e.jsxs("div",{className:"branch-widget-new-branch",children:[e.jsx("input",{ref:O,type:"text",className:"branch-widget-new-branch-input",placeholder:o("terminal:fileExplorer.branchNamePlaceholder"),value:R,onChange:S=>g(S.target.value),onKeyDown:S=>{S.stopPropagation(),S.key==="Enter"&&I(),S.key==="Escape"&&(w(!1),g(""))}}),e.jsx("button",{className:"branch-widget-new-branch-confirm",onClick:I,disabled:!R.trim()||c,children:T==="create"?"...":o("common:buttons.create")})]}),e.jsxs("div",{className:"branch-widget-section-header",children:[o("terminal:fileExplorer.localBranches"),Q&&e.jsxs("span",{className:"branch-widget-loading-hint",children:[" ",o("terminal:fileExplorer.loading")]})]}),e.jsxs("div",{className:"branch-widget-branch-list",children:[ce.length===0&&!Q&&e.jsx("div",{className:"branch-widget-empty",children:o("terminal:fileExplorer.noBranchesFound")}),ce.map(S=>e.jsxs("div",{className:`branch-widget-branch-item ${S.isCurrent?"current":""} ${c?"disabled":""}`,onClick:()=>z(S),onContextMenu:q=>G(q,S),title:S.lastMessage||S.name,children:[e.jsxs("span",{className:"branch-widget-branch-name",children:[S.isCurrent&&e.jsx("span",{className:"branch-widget-current-marker",children:"*"}),S.name]}),S.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:S.lastCommit})]},S.name))]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"branch-widget-section-header clickable",onClick:()=>x(!k),children:[e.jsx("span",{className:"branch-widget-section-toggle",children:k?"▾":"▸"}),o("terminal:fileExplorer.remoteBranches",{count:A.length})]}),k&&e.jsx("div",{className:"branch-widget-branch-list",children:A.map(S=>e.jsxs("div",{className:`branch-widget-branch-item remote ${c?"disabled":""}`,onClick:()=>z(S),onContextMenu:q=>G(q,S),title:S.lastMessage||S.name,children:[e.jsx("span",{className:"branch-widget-branch-name",children:S.name}),S.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:S.lastCommit})]},S.name))})]})]}),D&&e.jsx(ct,{isOpen:D.isOpen,position:D.position,worldPosition:{x:0,z:0},actions:ae,onClose:()=>N(null)})]})});function ar(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function It(s,n){if(!s)return"";const l=Is.languages[n];return l?Is.highlight(s,l,n):ar(s)}function rr(s){const n=[],l=s.split(`
|
|
9
9
|
`);let d=[],r=!1,i=[],m=[],o=!1;for(const h of l)h.startsWith("<<<<<<<")?(d.length>0&&(n.push({type:"unchanged",content:d.join(`
|
|
10
10
|
`)}),d=[]),r=!0,o=!1,i=[],m=[]):h.startsWith("=======")&&r?o=!0:h.startsWith(">>>>>>>")&&r?(n.push({type:"conflict",ours:i.join(`
|